긴 지연 시간동안 CPU 클록을 낭비하지 않기 위해서 네트워크 입출력을 효율적으로 처리하라면 동시성을 이용해야하고, 네트워크에서 응답이 오는 동안 다른 일을 처리하는 것이 좋다.
순차 내려받기 스크립트
#순차 내려 받기 스크립트, 몇몇 함수는 다른 스크립트에서 재사용할 것이다.
import os
import time
import sys
import requests
POP20_CC = ('CN IN US ID BR PK NG BD RU JP '
'MK PH VN ET EG DE IR TR CD FR').split()
BASE_URL = 'http://flupy.org/data/flags'
DEST_DIR = 'downloads'/
def save_flag(img, filename):
path = os.path.join(DEST_DIR, filename)
with open(path,'wb') as fp:
fp.write(img)
def get_flag(cc):
url = '{}/{cc}/{cc}/gif'.format(BASE_URL, cc=cc.lower())
resp = requests.get(url)
return resp.content
def show(text):
print(text, end=' ')
sys.stdout.flush()
def download_many(cc_list):
for cc in sorted(cc_list):
image= get_flag(cc)
show(cc)
save_flag(image, cc.lower() + '.gif')
return len(cc_list)
def main(download_many):
t0 =time.time()
count = download_many(POP20_CC)
elapsed = time.time() - t0
msg = '\n{} flags downloaded in {:.2f}s'
print(msg.format(count,elapsed))
if __name__ == '__main__':
main(download_many)
동시성 버전을 구현할 때 중복을 피하기 위해 하나의 라이브러리로 사용