python-3.x - Python3 asyncio产生新线程时线程中没有当前事件循环
问题描述
我可以用这个例子很容易地重现这个问题:
from threading import Thread
import asyncio
def func():
asyncio.get_event_loop()
Thread(target=func).start()
根据文件:
如果当前 OS 线程中没有设置当前事件循环,OS 线程为 main,并且尚未调用 set_event_loop(),则 asyncio 将创建一个新的事件循环并将其设置为当前。
解决方案
新事件循环的自动分配只发生在主线程上。来自 asyncio DefaultEventLoopPolicy 的来源events.py
def get_event_loop(self):
"""Get the event loop for the current context.
Returns an instance of EventLoop or raises an exception.
"""
if (self._local._loop is None and
not self._local._set_called and
isinstance(threading.current_thread(), threading._MainThread)):
self.set_event_loop(self.new_event_loop())
if self._local._loop is None:
raise RuntimeError('There is no current event loop in thread %r.'
% threading.current_thread().name)
return self._local._loop
所以对于非主线程,你必须手动设置事件循环asyncio.set_event_loop(asyncio.new_event_loop())
推荐阅读
- python - 如何使用Python将excel文件数据动态转换为json文件
- tomcat - 在tomcat上部署grpc jar
- c# - 无法从 SelectList Razor Pages 中获取选定的值
- javascript - 背景没有相对于滑块正确改变
- android - 我需要在android的分页中使用的数据源
- python - 如何概括python中所有字符串的给定代码?
- javascript - 如何在 html li 标记中呈现快速验证器映射的错误值
- javascript - 尝试根据游戏是否结束来更改文本 react.js
- angular - 如何从 Angular 获取 OneDrive API 的访问令牌
- java - 无法建立与数据库的连接