我有一个脚本,其中我需要的功能已经超出了 bash 的范围(或者至少超出了我在 bash 中维护它的愿望),所以我正在研究如何在 python 中执行此操作。
我已经浏览了多处理文档以了解它的能力,但我仍然不完全确定我需要使用 map-ping、starmap-ping、async-ing 和其他 python 魔法的哪种组合。该块的起点将在 bash 中表示如下:
command1 argument1a arg1b > output1 < /dev/null &
command2 argument2a arg2b > output2 < /dev/null &
command3 argument3a arg3b > output3 < /dev/null &
wait
do_something_else
构建命令和参数列表很容易,我在作业控制等效项和让脚本在正确的位置等待时遇到了麻烦。
我正在努力完成的一些相关事情:
command
可能不同,或者是同一命令的另一个实例,但每个都与唯一的 output
文件关联,因此我不必担心锁定/覆盖。由于您没有手动解析
stdout
或 stderr
我只需将 shell=True
传递给 subprocess.Popen 并让终端完成所有管道操作。
from subprocess import Popen
proc_text =["echo hello", "echo world", "echo idk > val.txt"]
processes = []
for text in proc_text:
proc = Popen(text,shell=True)
processes.append(proc)
for proc in processes:
proc.communicate()