Python/Advanced
[Python] Multiprocessing(3) - ProcessPoolExecutor
unsungIT
2021. 5. 18. 05:15
ProcessPoolExecutor 을 이용한 샘플 코드 - 여러 사이트 크롤링 샘플 코드
from concurrent.futures import ProcessPoolExecutor, as_completed
import urllib.request
# 조회 URLS, url 이 정상동작 안하면 오류 발생
URLS = [
'https://www.daum.net/',
'http://www.cnn.com/',
'https://naver.com/',
'http://www.bbc.co.uk/',
'http://ruliweb.com'
]
# 실행 함수
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout=timeout) as conn:
return conn.read()
def main():
# 프로세스풀 Context 영역
with ProcessPoolExecutor(max_workers=5) as executor:
# Future 로드(실행X)
# arguments 가 여러개인 경우, dict 형식으로 처리가능
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
# 중간 확인(Dict)
# print(future_to_url)
# 실행, for 문 예제는 외울것, 깔금한 샘플 예제
for future in as_completed(future_to_url): # timeout=1(테스트 추천)
# Key값이 Future 객체, 키값을 입력해서 url 추출
url = future_to_url[future] # or future_to_url.get()
try:
# 결과
data = future.result()
except Exception as exc:
# 예외 처리
print('%r generated an exception: %s' % (url, exc))
else:
# 결과 확인
print('%r page is %d bytes' % (url, len(data)))
# print(data)
# 메인 시작
if __name__ == '__main__':
main()