2010-05-14 182 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