강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

Zetta Kim님의 프로필 이미지
Zetta Kim

작성한 질문수

우리를 위한 프로그래밍 : 파이썬 중급 (Inflearn Original)

AsyncIO 멀티 스크랩핑 실습 (1-1)

chapter 07-01 실행 오류

작성

·

26

·

수정됨

0

안녕하세요 강사님.

chapter 07-01 실행 오류가 납니다.

아니콘다 설치한 파이썬 3.13.5이고 주피터에서 실행했습니다. 무슨 오류인지도 모르겠어요. 도와주세요.

import asyncio
import timeit
from urllib.request import urlopen
from concurrent.futures import ThreadPoolExecutor
import threading

# 실행 시작 시간
start = timeit.default_timer()

# 서비스 방향이 비슷한 사이트로 실습 권장(예, 게시판성 커뮤니티)
urls = ['http://daum.net', 'https://naver.com', 'http://mlbpark.donga.com/', 'https://tistory.com', 'https://wemakeprice.com/']
# 동시 실행, urliopen 함수는 블록 IO임, 쓰레드로 사용해서 urlpen을 따로 사용해 준다면 asyncio에서 제어권을 넘기는 넘기는 방식으로 코딩

async def fetch(url, executor): # 쓰레드가 ulrs 리스크 겟수만큼 들어 옴
    # 실행
    res = await loop.run_in_executor(executor, urlopen, url)

    # 결과 반환
    return res.read()[0:5] # 내용이 많아 짜름 [0:5] 


# def main(): # --> async
    # yield --> await
    # 함수 내 yield 사용은 Generator

async def main():
    # 쓰레드 풀 생성
    executor = ThreadPoolExecutor(max_workers=None)

    # future 객체 모아 gather에서 실행 (중요)
    futures = [
        asyncio.ensure_future(fetch(url, executor)) for url in urls # fetch가 갯수만큼 생성
    ]

    # 결과 취합
    rst = await asyncio.gether(*futures) # future가 끝날 때가지 기다려 줄거예요, 리스트이기 때문에 언패킹

    print('Result : ', rst)

    # 자~ 위에 fetch함수 만들자 


if __name__ == '__main__':
    ## 패턴이 있음
    # 루프 초기화
    loop = asyncio.get_event_loop()
    ## 제어권을 주고 받는 핑퐁 게임 하겠다는 것
    # 작업 완료까지 대기
    loop.run_until_complete(main()) # run을 complete까지,끝날 때까지 루프는 계속된다s
    # 수행 시간 계산
    duration = timeit.default_timer() - start
    # 총 실행 시간
    print('Total Running Time : ', duration)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[1], line 49
     46 loop = asyncio.get_event_loop()
     47 ## 제어권을 주고 받는 핑퐁 게임 하겠다는 것
     48 # 작업 완료까지 대기
---> 49 loop.run_until_complete(main()) # run을 complete까지,끝날 때까지 루프는 계속된다s
     50 # 수행 시간 계산
     51 duration = timeit.default_timer() - start

File /opt/anaconda3/lib/python3.13/asyncio/base_events.py:701, in BaseEventLoop.run_until_complete(self, future)
    690 """Run until the Future is done.
    691 
    692 If the argument is a coroutine, it is wrapped in a Task.
   (...)
    698 Return the Future's result, or raise its exception.
    699 """
    700 self._check_closed()
--> 701 self._check_running()
    703 new_task = not futures.isfuture(future)
    704 future = tasks.ensure_future(future, loop=self)

File /opt/anaconda3/lib/python3.13/asyncio/base_events.py:637, in BaseEventLoop._check_running(self)
    635 def _check_running(self):
    636     if self.is_running():
...
    638     if events._get_running_loop() is not None:
    639         raise RuntimeError(
    640             'Cannot run the event loop while another loop is running')

RuntimeError: This event loop is already running
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...

답변 1

0

안녕하세요, 인프런 AI 인턴입니다. Zetta Kim님.

오류 내용을 보니, “RuntimeError: This event loop is already running”라는 메시지가 나오고 있습니다. 이는 현재 이벤트 루프가 이미 실행 중일 때 loop.run_until_complete()를 호출하려고 해서 발생하는 오류입니다. 주피터 노트북 환경에서는 이미 기본적인 이벤트 루프가 설정되어 있어서 이런 문제가 발생할 수 있습니다.

이 문제를 해결하기 위해, 주피터 노트북에서도 정상적으로 코루틴을 실행할 수 있도록 조금의 코드 수정이 필요합니다. 주피터 노트북에서는 아래와 같이 직접 이벤트 루프를 관리하는 대신, await를 사용하여 코루틴을 바로 실행하는 방법을 사용합니다.

우선 gether 부분의 오타가 있구요. gather로 수정해 주세요. 수정한 코드는 아래와 같습니다:

# 기존 코드의 문제를 수정한 부분입니다.
import asyncio
import timeit
from urllib.request import urlopen
from concurrent.futures import ThreadPoolExecutor
import threading

start = timeit.default_timer()

urls = ['http://daum.net', 'https://naver.com', 'http://mlbpark.donga.com/', 'https://tistory.com', 'https://wemakeprice.com/']

async def fetch(url, executor):
    res = await loop.run_in_executor(executor, urlopen, url)
    return res.read()[0:5]

async def main():
    executor = ThreadPoolExecutor(max_workers=None)
    futures = [
        fetch(url, executor) for url in urls
    ]
    rst = await asyncio.gather(*futures)
    print('Result : ', rst)

loop = asyncio.get_event_loop()
await main()
duration = timeit.default_timer() - start
print('Total Running Time : ', duration)

주피터 노트북에서는 await로 코루틴을 직접 실행할 수 있으므로, 이렇게 코드를 변경하면 문제가 해결될 것이라 예상됩니다.

저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.

Zetta Kim님의 프로필 이미지
Zetta Kim

작성한 질문수

질문하기