簡體   English   中英

使用 asyncio 同時執行兩個函數

[英]Execute two functions concurrently using asyncio

我現在有一個設置,其中我打開一個子,我要讀這兩個stdoutstderr在同一時間,所以調用子后,我催生一個新的線程stdout ,只是手柄stderr在主線程。

# imports
from subprocess import Popen, PIPE
from threading import Thread


def handle_stdout(stdout):
    # ... do something with stdout,
    # not relevant to the question
    pass


def my_fn():
    proc = Popen([...], stdout=PIPE, stderr=PIPE)
    Thread(target=lambda: handle_stdout(proc.stdout)).start()
    # ... handle stderr
    print(proc.stderr.read())
    proc.wait()
    proc.kill()

my_fn()

有沒有辦法使用 asyncio 實現同樣的目標?

代碼的無線asyncio版本可能如下所示:

import asyncio
import asyncio.subprocess

async def handle_stdout(stdout):
    while True:
        line = await stdout.readline()  # Possibly adding .decode() to get str
        if not line:
            break
    # In 3.8 four lines above can be replaced with just:
    # while line := await stdout.readline():  # Yay walrus operator!
        # ... do stuff with line ...

async def my_fn():
    # Note: No list wrapping on command line arguments; all positional arguments are part of the command
    proc = await asyncio.create_subprocess_exec(..., stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
    stdout_task = asyncio.create_task(handle_stdout(proc.stdout))
    # ... handle stderr
    print(await proc.stderr.read())
    await stdout_task
    await proc.wait()

if  __name__ == '__main__':
    asyncio.run(my_fn())

API 略有不同,異步函數實際上是在您從它們中創建任務時調用的(線程必須執行未調用的函數),並且您需要小心地await所有異步操作,但這並沒有什么不同。 主要問題是async的病毒性質; 由於您只能在async函數中await ,因此很難從非異步代碼調用異步代碼(反之亦然,只要非異步代碼不會因任何原因阻塞)。 它使異步代碼庫在很大程度上與非async內容不兼容,並使零碎的轉換幾乎不可能,但對於全新的代碼,它工作正常。

暫無
暫無

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

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