首页 > 解决方案 > 将函数转换为异步函数

问题描述

我需要重写我的 python 函数,以便它可以async执行。

此函数作为示例给出:

import asyncio
from sse_starlette.sse import EventSourceResponse

async def run_command():
    command = "echo test1 && sleep 2 && echo test2 && sleep 2 && echo test3 && echo done"

    proc = await asyncio.create_subprocess_shell(
        command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
    )

    while True:
        output = await proc.stdout.readline()
        if not output:
            return
        yield output.decode().strip()

async def predict():
        return EventSourceResponse(run_command())

现在我正在尝试将以下函数转换为上面的异步函数:

import subprocess
def run_command():
      command = "echo test1 && sleep 2 && echo test2 && sleep 2 && echo test3 && echo done"
      with subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=-1) as p: 
        char = p.stdout.read(1)
        while char != b'':  
            print(char.decode('UTF-8','ignore'), end='', flush=True)
            char = p.stdout.read(1)

此函数与示例中的函数类似,但它打印出每个字符而不是每一行,并使用subprocess代替asyncio. 如何将基于子流程的函数转换为异步函数?

我试过这个,但我得到一个错误:

async def run_command():

    proc = await asyncio.create_subprocess_shell(
        command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
    )

    while True:
        output = await proc.stdout.read(1)
        if not output:
            return
        while output != b'':  
            print(output.decode('UTF-8','ignore'), end='', flush=True)
            yield output.decode('UTF-8','ignore')
            output = p.stdout.read(1)

标签: pythonasynchronousasync-awaitsubprocesspython-asyncio

解决方案


推荐阅读