简体   繁体   English

Python 异步未执行

[英]Python asyncio not executing

I'm not really a Python expert, so excuse me if this is really obvious.我不是真正的 Python 专家,如果这真的很明显,请原谅。 I'm trying to run a script using asyncio.我正在尝试使用 asyncio 运行脚本。 Relevant bits of code:相关代码:

import websockets
import asyncio

stream = websockets.connect(<resource_uri>)

async def main():
    async with stream as receiver:
        while True:
            data = receiver.recv()
            # do stuff


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

When I run this, I get:当我运行它时,我得到:

DeprecationWarning: There is no current event loop loop = asyncio.get_event_loop()弃用警告:没有当前事件循环 loop = asyncio.get_event_loop()

Similarly, using同样,使用

''' loop = asyncio.get_running_loop() ''' ''' 循环 = asyncio.get_running_loop() '''

instead, I get相反,我得到

RuntimeError: no running event loop. RuntimeError:没有正在运行的事件循环。

Any ideas?有任何想法吗? I guess it's something to do with main() not running in the correct thread...我想这与 main() 没有在正确的线程中运行有关...

I'm using Python 3.10.我正在使用 Python 3.10。

Try this, works for me on 3.8 (and probably originally got from someone smarter than me that posted it on here!!)试试这个,在 3.8 上为我工作(可能最初是从比我更聪明的人那里得到的,把它贴在这里!!)

 try:
    loop = asyncio.get_running_loop()
 except RuntimeError:  # 'RuntimeError: There is no current event loop...'
    loop = None

 if loop and loop.is_running():
     print('Async event loop already running. Adding coroutine to the event loop.')
     tsk = loop.create_task(main())
     # ^-- https://docs.python.org/3/library/asyncio-task.html#task-object
     # Optionally, a callback function can be executed when the coroutine completes
     tsk.add_done_callback(
        lambda t: print(f'Task done with result = {t.result()}'))
 else:
    print('Starting new event loop')
    asyncio.run(main())

Newer code should use just asyncio.run(main()) - that will automatically create a new instance loop and "run until complete" on the awaitable.较新的代码应该只使用asyncio.run(main()) - 这将自动创建一个新的实例循环并在可等待对象上“运行直到完成”。

It seems there's an issue with websockets and Python 3.10. websockets 和 Python 3.10 似乎存在问题。 Looks like I'll have to find a workaround.看来我得想办法解决了。 Thanks for your time!谢谢你的时间!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM