본문 바로가기
기록/Python

[Python] 파이썬 비동기처리 asyncio 모듈

by 자임 2022. 7. 13.

 

외부 연계로 API를 동시에 10개 호출해야 하는데 시간을 줄일 수 있는 방법이 뭐가 있을까, 파이썬에서 비동기 처리를 하려면 어떻게 해야 할까 찾아보다가 발견한 asyncio 모듈.

결국 사용하진 않았지만 일단 기록해둔다.

 

 

asyncio(Asynchronous I/O)는 비동기 프로그래밍을 위한 모듈이며 CPU 작업과 I/O를 병렬로 처리하게 해준다.

 

 

 

asyncio 모듈 테스트 오류 :
AttributeError: partially initialized module 'asyncio' has no attribute 'get_event_loop' (most likely due to a circular import)

원인 : 파이썬 파일 이름을 asyncio.py 로 해서 오류남. 하하..
참고 : https://python-forum.io/thread-3004.html

해결 : 파일 이름 변경 

 

 

 

 

- 테스트 해본 코드 

from time import time
import asyncio

keyword = 'keyword'

async def scienceOn(keyword):
	...

async def kci(keyword):
    ...

async def wos(keyword):
    ...

async def main():
    result = await asyncio.gather(
        scienceOn(keyword),
        kci(keyword),
        wos(keyword)
    )  # 결과를 한꺼번에 가져옴

    return result


begin = time()

final = asyncio.run(main())
print(final)

end = time()
print('실행 시간: {0:.3f}초'.format(end - begin))

 

asyncio 모듈에서는 여러 비동기 함수를 한번에 등록 할 수 있는 *gather() 함수를 제공

*aws 시퀀스에 있는 어웨이터블 객체들을 동시에 실행한다. aws에 있는 어웨이터블이 자동으로 이벤트 루프에 등록된다. 모든 어웨이터블이 성공적으로 완료되면, 각 어웨이터블에서 반환된 값들이 합쳐진 리스트를 반환한다. 반환된 결과값들의 순서는 aws에 있는 어웨이터블의 순서와 동일하다. 

출처 : https://kukuta.tistory.com/345




참고 및 나중에 공부 : 
https://ffoorreeuunn.tistory.com/462
https://www.daleseo.com/python-asyncio/
https://dojang.io/mod/page/view.php?id=2469
https://brownbears.tistory.com/540
https://wikidocs.net/21046