要关闭python解释器_可以在后台运行asyncio事件循环,而不需要暂停Python解释器?...

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值