簡體   English   中英

asyncio 事件循環可以在后台運行而不暫停 Python 解釋器嗎?

[英]Can an asyncio event loop run in the background without suspending the Python interpreter?

asyncio 的文檔給出了如何每兩秒打印一次“Hello World”的兩個示例: https: //docs.python.org/3/library/asyncio-eventloop.html#asyncio-hello-world-callback https://docs.python.org/3/library/asyncio-eventloop.html#asyncio-hello-world-callback docs.python.org/3/library/asyncio-task.html#asyncio-hello-world-coroutine

我可以從解釋器運行它們,但如果我這樣做,我將無法訪問解釋器。 是否可以在后台運行 asyncio 事件循環,以便我可以繼續在解釋器中輸入命令?

編輯:

如果使用 Python 3.8 或更高版本,則應使用asyncio repl,如zeronone 的回答中所述 如果使用 3.7 或更低版本,則可以使用此答案。


您可以在后台線程中運行事件循環:

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

請注意,您必須loop上調用asyncio.set_event_loop ,否則您將收到一條錯誤消息,指出當前線程沒有事件循環。

如果你想從主線程與事件循環交互,你需要堅持使用loop.call_soon_threadsafe調用。

雖然這種事情是在解釋器中進行實驗的好方法,但在實際程序中,您可能希望所有代碼在事件循環內運行,而不是引入線程。

在 Python 3.8 中,您可以使用新的 asyncio REPL。

$ python -m asyncio
>>> async def greet_every_two_seconds():
...     while True:
...         print('Hello World')
...         await asyncio.sleep(2)
...
>>> # run in main thread (Ctrl+C to cancel)
>>> await greet_every_two_seconds()
...
>>> # run in background
>>> asyncio.create_task(greet_every_two_seconds())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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