2010-05-14 391 views
44

我有一個腳本,我用popen啓動一個shell命令。 問題是,腳本不會等到popen命令完成並立即繼續。Python popen命令。等待命令完成

om_points = os.popen(command, "w") 
..... 

如何告訴我的Python腳本等待shell命令完成?

回答

65

根據你想如何工作你的腳本你有兩個選擇。如果您希望命令在執行時阻止並不執行任何操作,則可以使用subprocess.call

#start and block until done 
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"]) 

如果你想這樣做,在執行時的事情或飼料東西進入stdin,您可以在popen電話後使用communicate

#start and process things, then wait 
p = subprocess.Popen([data["om_points"], ">", diz['d']+"/points.xml"]) 
print "Happens while running" 
p.communicate() #now wait plus that you can send commands to process 

如文檔中表示,wait可以死鎖,所以溝通是明智的。

+0

查看[subprocess.call](http://docs.python.org/library/subprocess.html#convenience-functions)上的文檔 – thornomad 2010-05-14 23:29:02

5

你在找什麼是wait方法。

+0

但如果I型: om_points = os.popen(數據[ 「om_points」] + 「> 」+ DIZ [ 'd'] +「/ points.xml」, 「W」)等( ) 我收到此錯誤: 回溯(最近調用最後一次): 文件「./model_job.py」,第77行,在 om_points = os.popen(data [「om_points」] +「>」+ diz ['d'] +「/ points.xml」,「w」)等待() AttributeError: 再次感謝。 – michele 2010-05-14 20:24:49

+9

您沒有點擊我提供的鏈接。 'wait'是'subprocess'類的一個方法。 – 2010-05-16 18:13:11

+0

如果進程寫入標準輸出並且沒有人讀取它,等待可能會發生死鎖 – ansgri 2016-12-19 15:03:50

5

您可以使用subprocess來實現此目的。

import subprocess 

#This command could have multiple commands separated by a new line \n 
some_command = "export PATH=$PATH://server.sample.mo/app/bin \n customupload abc.txt" 

p = subprocess.Popen(some_command, stdout=subprocess.PIPE, shell=True) 

(output, err) = p.communicate() 

#This makes the wait possible 
p_status = p.wait() 

#This will give you the output of the command being executed 
print "Command output: " + output