[英]python asyncio run_forever or while True
我應該在我的代碼中替換while True
(沒有 asyncio)還是應該使用 asyncio 事件循環來完成相同的結果。
目前我在某種連接到 zeromq 的“工人”上工作,接收一些數據,然后對外部工具(服務器)執行一些請求(http)。 一切都寫在正常的阻塞 IO 中。 使用 asyncio 事件循環擺脫while True: ...
有意義嗎?
將來它可能會在 asyncio 中完全重寫,但現在我害怕從 asyncio 開始。
我是 asyncio 的新手,並不是這個庫的所有部分對我來說都很清楚:)
謝謝 :)
如果您想開始使用不支持它的庫編寫異步代碼,您可以使用BaseEventLoop.run_in_executor 。
這允許您將可調用對象提交給ThreadPoolExecutor或ProcessPoolExecutor並異步獲取結果。 默認執行器是 5 個線程的線程池。
例子:
# Python 3.4
@asyncio.coroutine
def some_coroutine(*some_args, loop=None):
while True:
[...]
result = yield from loop.run_in_executor(
None, # Use the default executor
some_blocking_io_call,
*some_args)
[...]
# Python 3.5
async def some_coroutine(*some_args, loop=None):
while True:
[...]
result = await loop.run_in_executor(
None, # Use the default executor
some_blocking_io_call,
*some_args)
[...]
loop = asyncio.get_event_loop()
coro = some_coroutine(*some_arguments, loop=loop)
loop.run_until_complete(coro)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.