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

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

问题描述

asyncio的文档给出了两个如何每两秒打印一次Hello World的示例:
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



我可以从解释器运行,但是如果我不能访问解释器。

解决方案

可以运行一个asyncio事件循环在后台运行,以便我可以在解释器上继续输入命令在后台线程中的事件循环:

 >> 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

请注意,您必须呼叫 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?

解决方案

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天全站免登陆