Microsoft MVP성태의 닷넷 이야기
스크립트: 58. 파이썬 - async/await 기본 사용법 [링크 복사], [링크+제목 복사],
조회: 3519
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

파이썬 - async/await 기본 사용법

C# 개발자라면, 파이썬의 async/await를 유사한 경험으로 사용할 수 있습니다. 우선, 간단하게 콘솔 앱으로 예제를 작성해 볼까요? ^^

async def main_async():
    print('async called')

await main_async()

""" 
실행 결과:

  File "C:\test\main.py", line 6
    await main_async()
    ^
SyntaxError: 'await' outside function
"""

위의 코드를 실행하면 "실행 결과"에서 보는 바대로 await을 함수 밖에서 사용했다고 오류가 발생합니다. 그래서 이것을 함수에 담아서 다시 호출해 보면,

import time

async def do_something(delay: int=0):
    time.sleep(delay)
    return delay

def main():
    await do_something(3)

main()


""" 
실행 결과:

  File "/home/testusr/main.py", line 10
    await do_something(3)
    ^
SyntaxError: 'await' outside async function
"""

이번엔 async 함수가 아닌 곳에서 사용했다고 나옵니다. 그렇다면 main 함수를 async로 만들어야 하지만,

async def main():
    await do_something(3)

main()

""" 
실행 결과:

/home/testusr/main.py:12: RuntimeWarning: coroutine 'main' was never awaited
  main()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
"""

그럼 main 함수가 비동기 호출 처리가 안 되었다는 불평을 하게 되므로, 결국 main 호출도 "await main()"으로 바꿔야 하고 문제가 다시 원점으로 돌아가게 됩니다.




C#은 Main 메서드 시작부터 async Main으로 만드는 것이 가능하지만 파이썬은 그에 대한 처리는 없기 때문에 이런 경우 라이브러리의 도움을 받아야 합니다. 실제로 최초의 async 진입 함수를 asyncio.run 등의 함수를 이용해 실행하면,

import time
import asyncio

async def main_async():
    print('async calling', time.strftime('%X'))
    time.sleep(5)
    print('async called', time.strftime('%X'))

asyncio.run(main_async())

""" 
실행 결과:

async calling 14:06:08
async called 14:06:13
""" 

아무런 문제 없이 코드가 수행됩니다. 또한 await을 순차적으로 비동기 처리하는 것은 C#의 체계와 같습니다. 그래서 아래의 코드는 총 9초를 소요하게 되는데요,

import time
import asyncio

async def do_something(delay: int=0):
    time.sleep(delay)


async def main_async():
    print('async calling', time.strftime('%X'))
    await do_something(3)
    await do_something(6)
    print('async called', time.strftime('%X'))  # 9초 지나서 실행
                                                # 아래에서 다루겠지만, do_something 함수 내부의 코드 문제로 비동기 처리와 무관하게 9초가 걸립니다.
    

asyncio.run(main_async())

그렇다면 병렬처리는 어떻게 할 수 있을까요? C#의 경우라면 개별 호출을 Task로 받아 await을 별도로 진행하거나 Task.WhenAll로 받을 수 있는데요, 파이썬도 유사한 사용자 경험을 제공합니다.

실제로 해볼까요? ^^ 우선, C#처럼 다음과 같이 코딩하면,

task1 = do_something(3)  # 동기 호출: 이곳에서 time.sleep(3) 코드 동작
task2 = do_something(6)  # 동기 호출: 이곳에서 time.sleep(6) 코드 동작

await task1
await task2

위의 호출은 총 9초가 소요됩니다. 사실 "task1 = do_something(...)" 형식이 동기 호출이든 비동기 호출이든 상관없이 저 코드는 총 9초가 소요됩니다. 왜냐하면 do_something의 내부에 있는 time.sleep이 동기적으로 호출되기 때문에 그것을 호출하는 측의 스레드가 그대로 묶이기 때문입니다.

따라서, 이 문제를 없애려면 time.sleep도 비동기 버전을 사용해야 합니다.

async def do_something(delay: int=0):
    await asyncio.sleep(delay)


task1 = do_something(3)  # 동기 호출이지만 asyncio.sleep 비동기 호출로 3초를 대기하지 않고 제어 반환
task2 = do_something(6)  # 동기 호출이지만 asyncio.sleep 비동기 호출로 6초를 대기하지 않고 제어 반환

await task1  # 이곳에서 비동기 3초 작업 대기
await task2  # 이미 3초가 흘렀으므로 남은 비동기 3초 대기

# 총 6초 소요

보는 바와 같이, 이제야 원하는 대로 병렬 처리가 잘 되었습니다. (저렇게 보면 C#의 코드와 거의 같습니다.)

또한, 파이썬 역시 C#의 Task.WhenAll과 유사하게 병렬 처리를 위한 전용 함수인 asyncio.gather를 제공합니다. 따라서 이것을 이용하면 다음과 같이 재작성할 수 있습니다.

# Can I use await on multiple functions at once?
# https://stackoverflow.com/questions/68733675/can-i-use-await-on-multiple-functions-at-once

import time
import asyncio

async def do_something(delay: int=0):
    await asyncio.sleep(delay)


async def main_async():
    print('async calling', time.strftime('%X'))

    await asyncio.gather(do_something(3), do_something(6))  # 6초 소요

    print('async called', time.strftime('%X'))


asyncio.run(main_async())

참고로, gather의 경우 인자를 개별적으로 지정하는데, 인자가 포함된 리스트를 받는 wait 함수를 쓰는 것도 가능합니다. (gather/wait)

async def main_async():
    print('async calling', time.strftime('%X'))

    jobs = [do_something(3), do_something(6)]  # 리스트로 전달
    await asyncio.wait(jobs)  # 6초 소요

    print('async called', time.strftime('%X'))




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/13/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  [27]  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
12977정성태2/21/202211450.NET Framework: 1160. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 qsv 디코딩
12976정성태2/21/20227047VS.NET IDE: 174. Visual C++ - "External Dependencies" 노드 비활성화하는 방법
12975정성태2/20/20228752.NET Framework: 1159. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 qsvdec.c 예제 포팅파일 다운로드1
12974정성태2/20/20226865.NET Framework: 1158. C# - SqlConnection의 최소 Pooling 수를 초과한 DB 연결은 언제 해제될까요?
12973정성태2/16/20229254개발 환경 구성: 639. ffmpeg.exe - Intel Quick Sync Video(qsv)를 이용한 인코딩 [3]
12972정성태2/16/20228594Windows: 200. Intel CPU의 내장 그래픽 GPU가 작업 관리자에 없다면? [4]
12971정성태2/15/202210219.NET Framework: 1157. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 muxing.c 예제 포팅 [7]파일 다운로드2
12970정성태2/15/20228299.NET Framework: 1156. C# - ffmpeg(FFmpeg.AutoGen): Bitmap으로부터 h264 형식의 파일로 쓰기 [1]파일 다운로드1
12969정성태2/14/20226779개발 환경 구성: 638. Visual Studio의 Connection Manager 기능(Remote SSH 관리)을 위한 명령행 도구 - 두 번째 이야기파일 다운로드1
12968정성태2/14/20227029오류 유형: 794. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for '...'.
12967정성태2/14/20227421VC++: 153. Visual C++ - C99 표준의 Compund Literals 빌드 방법 [4]
12966정성태2/13/20227222.NET Framework: 1155. C# - ffmpeg(FFmpeg.AutoGen): Bitmap으로부터 yuv420p + rawvideo 형식의 파일로 쓰기파일 다운로드1
12965정성태2/13/20227245.NET Framework: 1154. "Hanja Hangul Project v1.01 (파이썬)"의 C# 버전
12964정성태2/11/20227512.NET Framework: 1153. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 avio_reading.c 예제 포팅파일 다운로드1
12963정성태2/11/20228268.NET Framework: 1152. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 (저해상도 현상 해결)파일 다운로드1
12962정성태2/9/20228138오류 유형: 793. 마이크로소프트 스토어 - 제품이 존재하지 않습니다. 재고가 없는 것일 수 있습니다.
12961정성태2/8/20228271.NET Framework: 1151. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 프레임의 크기 및 포맷 변경 예제(scaling_video.c) [7]파일 다운로드1
12960정성태2/8/20227667개발 환경 구성: 637. ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) - 세 번째 이야기
12959정성태2/7/20228380.NET Framework: 1150. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) - 두 번째 이야기 [2]파일 다운로드1
12958정성태2/6/20228396.NET Framework: 1149. C# - ffmpeg(FFmpeg.AutoGen) - 비디오 프레임 디코딩 [2]파일 다운로드1
12957정성태2/6/20228019개발 환경 구성: 636. ffmpeg.exe를 이용해 planar 포맷의 데이터를 packed 형식으로 변환하는 방법? [2]
12956정성태2/4/20227252.NET Framework: 1148. C# - ffmpeg(FFmpeg.AutoGen) - decoding 과정 [2]파일 다운로드1
12955정성태2/4/20226704개발 환경 구성: 635. 비주얼 스튜디오에서 실행하던 ASP.NET Core (.NET Framework) 응용 프로그램을 명령행에서 실행하는 방법 (2)
12954정성태2/4/20226521VS.NET IDE: 173. 비주얼 스튜디오 - Output 창에 색상이 지정된 출력 결과가 "[39m[22m" 식의 문자로 나오는 문제
12953정성태2/2/20226727Linux: 48. Windows 11 + WSL 우분투 GUI 환경에서 한글 출력
12952정성태2/2/20227260.NET Framework: 1148. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 오디오 필터 예제(filter_audio.c)파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  [27]  28  29  30  ...