python - 将函数转换为异步函数
问题描述
我需要重写我的 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)
解决方案
推荐阅读
- android - 如何编写 Room Dao 查询以在 Android 中基于单表中的可选多列搜索唯一数据?
- flutter - 在 Flutter 中使用 awesome_notifications 显示通知的问题
- angular - 从角度模板多次调用方法
- java - Java:将 HEX 字节数组转换为 16 个固定长度的二进制字符串
- python - confluent-kafka python客户端版本适用于confluent-kafka 5.5.1版本
- amp-html - 从 amp 电子邮件提交表单时如何发送 amp-state?
- unity3d - 只有在另一个完成后才执行方法
- visual-studio-code - 无法使用 cmd 代码在 ubuntu 上的 WSL bash 中打开 vscode
- botframework - 如何从以前的聊天中隐藏/禁用自适应卡片按钮?
- python - 在 Python 类中使字典可迭代