파이썬, asyncio 함수 실행 취소 및 예외 처리 

 

글. 수알치 오상문

 

예제 코드에 대한 설명 아래쪽 동영상 링크를 참고하세요.

 

import asyncio

async def afunc():
    try:
        print('Working')
        await asyncio.sleep(1)  # 작업용 코루틴 수행 
        print('Done')
    except asyncio.CancelledError:  # asyncio.CancelledError
        print('Cancelled')
        raise  # 호출한 곳으로 에러 넘김
    except Exception:
        await asyncio.sleep(1)  # Clean up 코루틴 수행 
        print('Cleaned up')

# 1: 명시적인 취소 
async def main1():
    t = asyncio.create_task(afunc())
    await asyncio.sleep(0.5)
    t.cancel()
    try:
        await t  # 다른 작업 필요하면 await 한번 더 수행 
    except asyncio.CancelledError:  # 에러 종류는 CanclelledError 
        print('Cancellation detected!')

# 2: timeout을 이용한 취소 
async def main2():
    t = asyncio.create_task(afunc())
    try:
        await asyncio.wait_for(t, timeout=0.5)  # 0.5초 지나면 취소  
    except asyncio.TimeoutError:  # 에러 종류는 TimeoutError
        print('Timeout detected!')
 
# TEST ---------------------------------
loop = asyncio.get_event_loop()
loop.run_until_complete(main1())  # main2()
loop.close()

 

 

[실행결과] main1()

Working
Cancelled
Cancellation detected!

 

[실행결과] main2()

Working
Cancelled
Timeout detected!

 

 

<참고> 

https://www.youtube.com/watch?v=QaiczQzJAmA 

 

반응형

+ Recent posts