[Python] asyncio: 비동기 프로그래밍
py-async-await, python-asyncio, asyncio, 파이썬 비동기, async python
정의
asyncio 는 Python 의 표준 비동기 I/O 라이브러리 (3.4+). event loop 위에서 coroutine 을 스케줄링.
기본
import asyncio
async def fetch(url):
await asyncio.sleep(1)
return f"result for {url}"
async def main():
result = await fetch("https://example.com")
print(result)
asyncio.run(main())
병렬 실행
gather
async def main():
results = await asyncio.gather(
fetch("url1"),
fetch("url2"),
fetch("url3"),
)
세 요청이 병렬 실행, 결과 순서는 인자 순서와 동일.
as_completed
async def main():
tasks = [fetch(u) for u in urls]
for future in asyncio.as_completed(tasks):
result = await future
print(result) # 완료된 순서
Task 생성
task = asyncio.create_task(fetch(url))
# ...다른 일...
result = await task
Semaphore 로 동시 실행 제한
sem = asyncio.Semaphore(10)
async def limited_fetch(url):
async with sem:
return await fetch(url)
함정
- 동기 코드 블로킹:
time.sleep()대신await asyncio.sleep(). 다른 블로킹 함수는run_in_executor로. - event loop 하나:
asyncio.run()을 중첩하면 안 됨. Jupyter 는 이미 loop 있어서 다른 처리 필요. - 취소 처리:
asyncio.CancelledError반드시 전파
실전 라이브러리
- aiohttp: HTTP client/server
- asyncpg: PostgreSQL
- motor: MongoDB
- httpx (async mode)
- FastAPI, Starlette: 웹 프레임워크
💬 댓글