[英]Pytest: runtimeerror there is no current event loop in thread 'mainthread'
[英]RuntimeError: There is no current event loop in thread 'MainThread'
我目前正在从事一个项目,我正在寻找信息更新,然后将状态消息发布到松弛通道。 这是我的第一个 python 项目,我对出了什么问题有点不知所措。 但是,我收到的RuntimeError: There is no current event loop in thread 'MainThread'
错误似乎是由我的主 function 中有两个异步请求引起的。
我想知道是否有人能够告诉我最佳做法是什么以及我如何避免更多问题?
def main():
configure()
print("the project has started")
asyncio.run(post_message("the project has started"))
event_filter = [my api call to another service goes here]
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(
asyncio.gather(
log_loop(event_filter, 2)))
finally:
# close loop to free up system resources
loop.close()
async def post_message(message):
try:
client = AsyncWebClient(token=os.getenv('SLACK_BOT_TOKEN'))
response = await client.chat_postMessage(channel='#notifications', text=message)
assert response["message"]["text"] == message
except SlackApiError as e:
assert e.response["ok"] is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
print(f"Got an error: {e.response['error']}")
在我看来,调用asyncio.run(post_message("the project has started"))
与我的loop = asyncio.get_event_loop()
配合得不好,但我又不确定为什么。
任何帮助将非常感激!
编辑
这是要求的完整追溯:
Traceback (most recent call last):
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "myprojectpath/__main__.py", line 4, in <module>
app.main()
File "myprojectpath/app.py", line 54, in main
loop = asyncio.get_event_loop()
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/events.py", line 639, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'MainThread'.
这会重现您的错误:
import asyncio
async def test():
pass
def main():
asyncio.run(test())
loop = asyncio.get_event_loop()
loop.run_until_complete(test())
问题是asyncio.run
创建一个事件循环,运行你的协程,然后关闭事件循环。 因此您以后不能使用该循环。 相反,将 main 更改为异步 function 并仅使用 await 或使用asyncio.run
进行收集调用。 除非必须,否则尽量避免使用循环 api。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.