2015-02-24 67 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