RuntimeError:线程“Dummy-1”中没有当前事件循环
Posted
技术标签:
【中文标题】RuntimeError:线程“Dummy-1”中没有当前事件循环【英文标题】:RuntimeError: There is no current event loop in thread 'Dummy-1' 【发布时间】:2018-06-19 18:49:36 【问题描述】:我正在开发一个带有 Python 后端和 Django 服务器的 Web 应用程序。我有一些树莓派正在向服务器发送数据,然后我应该从我的后端获取这些数据。我成功地完成了我的项目,所以我很确定代码。现在我想将此功能集成到我的项目中,所以这是文件:
loop = asyncio.get_event_loop()
class StartApp:
def __init__(self, interval=1):
self.interval = interval
Mqtt = multiprocessing.Process(target = self.runMqtt)
loop.run_until_complete(runCoap())
async def runCoap():
print('COUCOU C cOAP')
protocol = await Context.create_client_context()
requestTemp = Message(code=GET, uri='coap://129.6.60.38/other/sensors/temperature')
requestHumidity = Message(code=GET, uri='coap://129.6.60.38/other/sensors/humidity')
while True:
time.sleep(1)
try:
responseTemp = await protocol.request(requestTemp).response
responseHumidity = await protocol.request(requestHumidity).response
except Exception as e:
print('Failed to fetch resource:')
print(e)
else:
print('Result: %s\n%r'%(responseTemp.code, responseTemp.payload))
print('Result: %s\n%r'%(responseHumidity.code, responseHumidity.payload))
运行我的应用程序时出现此错误:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f55cdc989d8>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 147, in inner_run
handler = self.get_handler(*args, **options)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/staticfiles/management/commands/runserver.py", line 28, in get_handler
handler = super(Command, self).get_handler(*args, **options)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 68, in get_handler
return get_internal_wsgi_application()
File "/usr/local/lib/python3.5/dist-packages/django/core/servers/basehttp.py", line 47, in get_internal_wsgi_application
return import_string(app_path)
File "/usr/local/lib/python3.5/dist-packages/django/utils/module_loading.py", line 20, in import_string
module = import_module(module_path)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/vincentnahmias/Workspace/IOT-Testbed-Dashboard/IOT-Testbed-Dashboard/wsgi.py", line 13, in <module>
from Dashboard.pySharkToDb.LAN_to_DB import StartApp
File "/home/vincentnahmias/Workspace/IOT-Testbed-Dashboard/Dashboard/pySharkToDb/LAN_to_DB.py", line 17, in <module>
loop = asyncio.get_event_loop()
File "/usr/lib/python3.5/asyncio/events.py", line 632, in get_event_loop
return get_event_loop_policy().get_event_loop()
File "/usr/lib/python3.5/asyncio/events.py", line 578, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Dummy-1'.
我尝试打印循环,但似乎没有创建循环,所以我假设 Django 和 asyncio 之间存在冲突,因为我可以使用以下方法在项目外运行这个相同的函数:
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(main())
其中 main 是我命名为 runCoap 的方法的名称。
【问题讨论】:
我假设 Django 在主线程之外运行您的代码。尝试在***run_until_complete()
之前使用loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop)
,在其之后使用loop.close()
。另外,将time.sleep(1)
替换为await asyncio.sleep(1)
。
非常感谢它的魅力!
【参考方案1】:
感谢@user4815162342,这是解决方案:
def __init__(self, interval=1):
self.interval = interval
logging.basicConfig(level=logging.INFO)
loop = asyncio.new_event_loop();
asyncio.set_event_loop(loop)
loop.run_until_complete(self.runCoap())
loop.close()
Mqtt = multiprocessing.Process(target = self.runMqtt)
async def runCoap(self):
print('COUCOU C cOAP')
protocol = await Context.create_client_context()
requestTemp = Message(code=GET, uri='coap://129.6.60.38/other/sensors/temperature')
requestHumidity = Message(code=GET, uri='coap://129.6.60.38/other/sensors/humidity')
while True:
await asyncio.sleep(1)
try:
responseTemp = await protocol.request(requestTemp).response
responseHumidity = await protocol.request(requestHumidity).response
except Exception as e:
print('Failed to fetch resource:')
print(e)
else:
print('Result: %s\n%r'%(responseTemp.code, responseTemp.payload))
print('Result: %s\n%r'%(responseHumidity.code, responseHumidity.payload))
【讨论】:
asyncio.sleep(1)
除非等待,否则不会做任何事情。换句话说,你需要await asyncio.sleep(1)
才能真正入睡。以上是关于RuntimeError:线程“Dummy-1”中没有当前事件循环的主要内容,如果未能解决你的问题,请参考以下文章
Flask asyncio aiohttp - RuntimeError:线程'Thread-2'中没有当前事件循环
Matplotlib 和 :RuntimeError: 主线程不在主循环中:
RuntimeError:异步+ apscheduler中的线程中没有当前事件循环
Discord.py 带线程,RuntimeError: Timeout context manager 应该在任务内部使用
Python线程:“RuntimeError:thread .__ init __()not called”
Discordbot 使用线程引发“RuntimeError:set_wakeup_fd 仅适用于主线程”仅在 linux 上