RuntimeError: There is no current event loop in thread 'MainThread'
83
4 câu hỏi đã được viết
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://google.com']
async def fetch(url, executor):
print('Thread Name : ', threading.current_thread().getName(), 'start', url)
res = await loop.run_in_executor(executor, urlopen, url)
print('Thread Name : ', threading.current_thread().getName(), 'Done', url)
return res.read()[0:5]
async def main():
executor = ThreadPoolExecutor(max_workers=10)
futures = [
asyncio.ensure_future(fetch(url, executor)) for url in urls
]
rst = await asyncio.gather(*futures)
print()
print()
print('Result : ', rst)
if name == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
duration = timeit.default_timer() - start
print('Total Running Time : ', duration)
코드를 작성했을때 아래와 같은 오류가 발생하는데 왜 그런지 그리고 해결방법이 무엇인가요?

Câu trả lời 1
0
안녕하세요, 인프런 AI 인턴입니다.
열심학습자님께서 문의하신 “RuntimeError: There is no current event loop in thread ‘MainThread’” 오류는 asyncio 모듈을 사용하면서 발생할 수 있는 오류 중 하나로, 이 오류는 현재 스레드에서 사용할 수 있는 이벤트 루프가 없다는 것을 의미합니다. 주로 asyncio.get_event_loop()를 사용하려고 할 때 이벤트 루프가 초기화되지 않았을 경우 발생합니다.
해결 방법:
- Python 3.7 이상에서는
asyncio.run()를 사용하는 방식으로 이벤트 루프를 생성하고 실행할 수 있습니다. 이 방법은 코드가 더 간결하고 안정적으로 실행될 수 있습니다.
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://google.com']
async def fetch(url, executor):
print('Thread Name : ', threading.current_thread().getName(), 'start', url)
res = await loop.run_in_executor(executor, urlopen, url)
print('Thread Name : ', threading.current_thread().getName(), 'Done', url)
return res.read()[0:5]
async def main():
executor = ThreadPoolExecutor(max_workers=10)
futures = [asyncio.ensure_future(fetch(url, executor)) for url in urls]
rst = await asyncio.gather(*futures)
print()
print('Result : ', rst)
if __name__ == '__main__':
asyncio.run(main())
duration = timeit.default_timer() - start
print('Total Running Time : ', duration)
- 이벤트 루프 직접 생성:
get_event_loop()대신new_event_loop()와set_event_loop()메서드를 사용해서 직접 루프를 생성하고 설정하는 방법입니다.
위 방법들은 현재 실행 환경에 따라 다를 수 있습니다. 위의 코드 예시를 참고하여 수정해보시길 바랍니다. 이로 인해 문제가 해결될 가능성이 높습니다.
저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.
진도미확인 (진도가 안 넘어감)
0
36
1
chapter 07-01 실행 오류
0
65
1
Chapter05-04 : sum_func의 합이 이중 출력됩니다.
0
76
2
45. 병렬성 2 - Futures(5-1) wait가 의도된 대로 동작하지 않습니다.
0
91
2
멀티스레딩 - 44. 병렬성 1 - Futures(4-2)
0
70
2
chapter05_02 클로저 질문사항 !
0
49
1
LV1 설정
0
87
2
매직 메소드의 호출 방법 차이 문의
0
131
2
왜 numbers리스트를 만들때 str으로 숫자를 감싸나요?
0
92
2
스크랩핑 실습 중 Mac OS 인증서 문제
0
128
1
AsyncIO 멀티 스크랩핑 실습 예제 관련 질문
0
167
1
강의자료가 영상과 다릅니다
0
254
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
392
1
가상환경 질문!
0
400
1
병렬처리 추가 질문이 있습니다.
0
241
1
멀티프로세싱 관련 질의
0
276
1

