Python 多重处理相当于大量 bash &符号和重定向?

问题描述 投票:0回答:1

我有一个脚本,其中我需要的功能已经超出了 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
    文件关联,因此我不必担心锁定/覆盖。
  • 所有进程都不需要接受任何输入。
  • stderr 应该打印到终端,尽管如果由于某种原因将其放入单独的文件中会更容易,也可以。
  • 我希望所有进程或多或少同时启动(精确的顺序/时间在这里并不重要)
python bash multiprocessing job-control
1个回答
0
投票

由于您没有手动解析

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()
© www.soinside.com 2019 - 2024. All rights reserved.