2015-02-24 42 views
1

我想用python并行生成一些文件。 Python将生成命令作为新的子进程调用。到目前为止,这些子过程与文件一样得到了创建。从子进程调用返回

我注意到,在最后一道工序结束时,预计会有回车。按Enter键完成最后一道工序。

如果我用os.system(commandString)同步(即按顺序)运行文件生成,则不需要CR。最后的过程是否以某种方式等待某件事?

谢谢你的帮助!

米哈伊

import subprocess 
for trace in traces: 
    ... # build commandString containing the in- and output filename 
    from subprocess import Popen 
    p = Popen(commandString) 
+1

'check_call'将等待并确保您获得0退出状态 – 2015-02-24 16:14:21

回答

0

我想我忘记等待结束进程?

我修改了代码,现在就开始工作! :

所有的
processList = [] 
for trace in traces: 
... # build commandString containing the in- and output filename 
    from subprocess import Popen 
    p = Popen(commandString) 
    processList.append(p) 

for pr in processList: 
    pr.wait() 
+1

确实,您忘记了等待。如果可行,这意味着你的子进程不希望通过stdin输入。在这种情况下,您可以通过其中一个helper方法取得快捷方式,如'call()',而不指定任何stdout/err/in参数。但是,这样你会失去对子进程的细粒度控制。看到我的答案。 – 2015-02-24 16:14:00

0

首先,只有你知道这些子过程,以及他们是否在某一时刻期待通过stdin或不发送输入。如果他们这样做,你可以发送给他们。

然后,有an important note in the Python docs更换os.system()

status = subprocess.call("mycmd" + " myarg", shell=True) 

所以,没有必要去Popen()路线,也有有用的辅助方法的子模块,如call()。但是,如果您使用Popen(),则需要照顾之后返回的对象。

为了更好地控制,在你的情况下,我可能会使用sp = subprocess.Popen(...)结合out, err = sp.communicate(b"\n")

请注意,sp.communicate(b"\n")通过标准输入显式发送换行符到子进程。

+0

感谢您的建议Jan-Philip。事实上,这些子进程不期望一个CR,因为它们在使用os.system()调用它们时会按预期工作。我在我原来的帖子中添加了评论。我需要调用pid.wait(),它现在可以工作。谢谢! – 2015-02-24 16:17:03