【发布时间】:2020-09-07 18:56:13
【问题描述】:
我的 Python 脚本包含一个循环,该循环使用 subprocess 在脚本之外运行命令。每个子进程都是独立的。如果出现错误,我会监听返回的消息;我不能忽略子流程的结果。这是没有 asyncio 的脚本(我已经用 sleep 替换了计算量很大的调用):
from subprocess import PIPE # https://docs.python.org/3/library/subprocess.html
import subprocess
def go_do_something(index: int) -> None:
"""
This function takes a long time
Nothing is returned
Each instance is independent
"""
process = subprocess.run(["sleep","2"],stdout=PIPE,stderr=PIPE,timeout=20)
stdout = process.stdout.decode("utf-8")
stderr = process.stderr.decode("utf-8")
if "error" in stderr:
print("error for "+str(index))
return
def my_long_func(val: int) -> None:
"""
This function contains a loop
Each iteration of the loop calls a function
Nothing is returned
"""
for index in range(val):
print("index = "+str(index))
go_do_something(index)
# run the script
my_long_func(3) # launch three tasks
我想我可以使用asyncio 来加快此活动,因为 Python 脚本正在等待外部 subprocess 完成。我认为threading 或multiprocessing 不是必需的,尽管它们也可以加快执行速度。使用任务队列(例如 Celery)是另一种选择。
我尝试实现 asyncio 方法,但由于以下尝试不会改变整体执行时间,因此遗漏了一些东西:
import asyncio
from subprocess import PIPE # https://docs.python.org/3/library/subprocess.html
import subprocess
async def go_do_something(index: int) -> None:
"""
This function takes a long time
Nothing is returned
Each instance is independent
"""
process = subprocess.run(["sleep","2"],stdout=PIPE,stderr=PIPE,timeout=20)
stdout = process.stdout.decode("utf-8")
stderr = process.stderr.decode("utf-8")
if "error" in stderr:
print("error for "+str(index))
return
def my_long_func(val: int) -> None:
"""
This function contains a loop
Each iteration of the loop calls a function
Nothing is returned
"""
# https://docs.python.org/3/library/asyncio-eventloop.html
loop = asyncio.get_event_loop()
tasks = []
for index in range(val):
task = go_do_something(index)
tasks.append(task)
# https://docs.python.org/3/library/asyncio-task.html
tasks = asyncio.gather(*tasks)
loop.run_until_complete(tasks)
loop.close()
return
my_long_func(3) # launch three tasks
如果我想监控每个subprocess 的输出,但不等待每个subprocess 运行,我可以从asyncio 中受益吗?还是这种情况需要multiprocessing 或 Celery 之类的东西?
【问题讨论】:
标签: python-3.x concurrency subprocess python-asyncio