簡體   English   中英

RuntimeError:線程“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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM