asyncio 事件循环可以在后台运行而不暂停 Python 解释器吗? [英] Can an asyncio event loop run in the background without suspending the Python interpreter?

查看:36
本文介绍了asyncio 事件循环可以在后台运行而不暂停 Python 解释器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

asyncio 的文档给出了两个示例,说明如何每两秒打印一次Hello World":https://docs.python.org/3/library/asyncio-eventloop.html#asyncio-hello-world-callbackhttps://docs.python.org/3/library/asyncio-task.html#asyncio-hello-world-coroutine

我可以从解释器运行那些,但如果我这样做,我将无法访问解释器.是否可以在后台运行 asyncio 事件循环,以便我可以继续在解释器中输入命令?

解决方案

如果使用 Python 3.8 或更高版本,您应该使用 asyncio repl,如 zeronone 的回答中所述.如果使用 3.7 或更低版本,您可以使用此答案.

<小时>

您可以在后台线程中运行事件循环:

<预><代码>>>>导入异步>>>>>>@asyncio.coroutine... def greet_every_two_seconds():...而真:...打印('你好世界')... 从 asyncio.sleep(2) 产生...>>>def loop_in_thread(循环):... asyncio.set_event_loop(loop)... loop.run_until_complete(greet_every_two_seconds())...>>>>>>loop = asyncio.get_event_loop()>>>进口螺纹>>>t = threading.Thread(target=loop_in_thread, args=(loop,))>>>t.start()你好世界>>>>>>你好世界

注意你必须loop上调用asyncio.set_event_loop,否则你会得到一个错误,说当前线程没有'没有事件循环.

如果你想从主线程与事件循环交互,你需要坚持 loop.call_soon_threadsafe 调用.

虽然这种事情是在解释器中进行试验的好方法,但在实际程序中,您可能希望所有代码在事件循环内运行,而不是引入线程.>

The documentation for asyncio gives two examples for how to print "Hello World" every two seconds: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio-hello-world-callback https://docs.python.org/3/library/asyncio-task.html#asyncio-hello-world-coroutine

I can run those from the interpreter, but if I do I lose access to the interpreter. Can an asyncio event loop be run in the background, so that I can keep typing commands at the interpreter?

解决方案

Edit:

If using Python 3.8 or above, you should use the asyncio repl, as explained in zeronone's answer. If using 3.7 or lower, you can use this answer.


You can run the event loop inside a background thread:

>>> import asyncio
>>> 
>>> @asyncio.coroutine
... def greet_every_two_seconds():
...     while True:
...         print('Hello World')
...         yield from asyncio.sleep(2)
... 
>>> def loop_in_thread(loop):
...     asyncio.set_event_loop(loop)
...     loop.run_until_complete(greet_every_two_seconds())
... 
>>> 
>>> loop = asyncio.get_event_loop()
>>> import threading
>>> t = threading.Thread(target=loop_in_thread, args=(loop,))
>>> t.start()
Hello World
>>> 
>>> Hello World

Note that you must call asyncio.set_event_loop on the loop, otherwise you'll get an error saying that the current thread doesn't have an event loop.

If you want to interact with the event loop from the main thread, you'll need to stick to loop.call_soon_threadsafe calls.

While this kind of thing is an ok way to experiment in the interpreter, in actual programs, you'll probably want all your code running inside the event loop, rather than introducing threads.

这篇关于asyncio 事件循环可以在后台运行而不暂停 Python 解释器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆