-
asyncio 라이브러리python 2025. 8. 23. 20:02
python 도 js처럼 async await 문법을 사용해 비동기 처리를 할 수 있다.
1. import
import asyncio파이썬은 js와 다르게 asyncio라는 라이브러리를 import해야 한다.
2. 함수 정의 & 실행
async def sleep(n): await asyncio.sleep(n) print(f'{n}초 sleep 완료') async def main(): await sleep(3) asyncio.run(main())async def로 비동기 함수를 정의할 수 있다.
비동기 함수는 비동기 함수 내부에서 await가 붙여져 실행되거나 asyncio.run()으로 실행된다.
3. asyncio 메소드
3.1. asyncio.sleep(delay, result=None)
delay초 동안 sleep한다. 이 메소드는 time.sleep과 다르게 cpu를 다른 작업에 넘긴다.
3.2. asyncio.gather(*aws, return_exceptions=False)
aws시퀀스에 있는 어웨이터블 객체를 동시에 실행한다.
async def sleep(n): await asyncio.sleep(n) print(f'{n}초 sleep 완료') async def main(): await asyncio.gather( sleep(3), sleep(2), sleep(1) ) asyncio.run(main())3.3. asyncio.run()
비동기 작업을 시작한다. 보통 메인 진입점으로 사용된다.
3.4. asyncio.create_task()
비동기 작업을 시작한다. 다른 비동기 작업과 같이 실행된다.
js에서는 일반적인 비동기 함수를 실행시키려면 그냥 호출하면 되지만 python에서는 이 함수를 실행시켜야 한다.
참고: https://www.youtube.com/watch?v=yYD_brv9R0o
https://docs.python.org/ko/3.13/library/asyncio-task.html
-
'python' 카테고리의 다른 글
PyQt5 라이브러리 (0) 2025.12.08 파이썬 소켓 통신 (0) 2025.12.03 selenium v4.0 (python) (0) 2023.04.10 파이썬 sorted 정렬 조건 정해주기 (0) 2022.07.08 파이썬 리스트 인덱스 여러개 찾기 (0) 2022.06.30