使用asyncio同时执行两个功能

时间:2020-01-30 13:26:50

标签: python python-3.x async-await python-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实现相同的目的?

1 个答案:

答案 0 :(得分:2)

代码的无线程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的病毒性质;由于您只能在await函数中使用async,因此很难从非异步代码中调用异步代码(相反,只要非异步代码不会阻止任何原因)。它使异步代码库在很大程度上与非async的东西不兼容,并且使得零碎转换几乎是不可能的,但是对于全新的代码,它可以正常工作。

相关问题