인프런 커뮤니티 질문&답변
RuntimeError: There is no current event loop in thread 'MainThread'
작성
·
23
0
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)
코드를 작성했을때 아래와 같은 오류가 발생하는데 왜 그런지 그리고 해결방법이 무엇인가요?

답변 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()메서드를 사용해서 직접 루프를 생성하고 설정하는 방법입니다.
위 방법들은 현재 실행 환경에 따라 다를 수 있습니다. 위의 코드 예시를 참고하여 수정해보시길 바랍니다. 이로 인해 문제가 해결될 가능성이 높습니다.
저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.





