分别运行2个或更多子进程调用

时间:2015-09-26 12:32:51

标签: python subprocess

我有两个不同的可执行文件(run1run2)。我想同时运行它们。它们共享一个只读输入文件,但除此之外,它们是不同的进程。 是否可以同时拨打call? 目前,正如我已编码,cmd2的来电等待cmd1来电完成。

with open(dosout, "w") as dout, open(jijout, "w") as jout:
    cmd1 = ["mpirun", "-np", "8", "~/WORK/run1", dosinp]
    cmd2 = ["mpirun", "-np", "8", "~/WORK/run2", jijinp]
    call(cmd1, stdout=dout)
    call(cmd2, stdout=jout)
dout.close()
jout.close()

是否可以使用call?或来自thisPopen回答是唯一的(或更好的)出路?

2 个答案:

答案 0 :(得分:1)

您需要使用Popen,如您所链接的答案中所述(以及其他一些地方,因为Popen是一个稍微低级的界面,通常需要)。

答案 1 :(得分:0)

同时运行两个子进程:

from subprocess import Popen

# start processes
with open(dosout, "wb", 0) as dout, open(jijout, "wb", 0) as jout:
    processes = [Popen(["mpirun", "-np", "8", "...WORK/run1", cmd], stdout=file)
                 for cmd, file in [(dosinp, dout), (jijinp, jout)]]

# wait for them to finish
statuses = [p.wait() for p in processes]

注意:该文件在退出with - 语句后关闭,不要手动调用.close()