inflearn logo
강의

講義

知識共有

私たちのためのプログラミング:Python 中級 (Inflearn Original)

AsyncIO マルチ スクレイピング 実習 (1-1)

chapter 07-01 실행 오류

66

Zetta Kim

投稿した質問数 7

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...

python django

回答 1

0

communityai8509

안녕하세요, 인프런 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로 코루틴을 직접 실행할 수 있으므로, 이렇게 코드를 변경하면 문제가 해결될 것이라 예상됩니다.

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

진도미확인 (진도가 안 넘어감)

0

39

1

RuntimeError: There is no current event loop in thread 'MainThread'

0

83

1

Chapter05-04 : sum_func의 합이 이중 출력됩니다.

0

76

2

45. 병렬성 2 - Futures(5-1) wait가 의도된 대로 동작하지 않습니다.

0

92

2

멀티스레딩 - 44. 병렬성 1 - Futures(4-2)

0

70

2

chapter05_02 클로저 질문사항 !

0

49

1

LV1 설정

0

87

2

매직 메소드의 호출 방법 차이 문의

0

131

2

왜 numbers리스트를 만들때 str으로 숫자를 감싸나요?

0

93

2

스크랩핑 실습 중 Mac OS 인증서 문제

0

128

1

AsyncIO 멀티 스크랩핑 실습 예제 관련 질문

0

167

1

강의자료가 영상과 다릅니다

0

255

2

closure.cell_contents 초기화 하기 문의

0

128

2

map함수 사용 시, list변환 방법 문의

0

335

2

__mul__ 백터 * 숫지, 백터 * 백터 처리

0

143

1

del처리후 질문입니다.

0

153

1

car_list(car1,car2,car3) 인스턴스 tuple 타입 문의

0

223

1

coroutine에 대한 질문

0

242

1

제너레이터 이터레이터 질문이 있습니다.

0

248

1

atom install package search not working

0

275

1

Magic Method - Not Implemented

0

394

1

가상환경 질문!

0

401

1

병렬처리 추가 질문이 있습니다.

0

243

1

멀티프로세싱 관련 질의

0

278

1