Python popen命令.等待命令完成 [英] Python popen command. Wait until the command is finished
问题描述
我有一个脚本,可在其中使用popen shell命令启动. 问题在于脚本不会等到该popen命令完成后才继续运行.
I have a script where I launch with popen a shell command. The problem is that the script doesn't wait until that popen command is finished and go continues right away.
om_points = os.popen(command, "w")
.....
如何告诉我的Python脚本等待shell命令完成?
How can I tell to my Python script to wait until the shell command has finished?
推荐答案
根据脚本的工作方式,有两种选择.如果要阻止命令执行,而又不执行任何操作,则可以使用subprocess.call
.
Depending on how you want to work your script you have two options. If you want the commands to block and not do anything while it is executing, you can just use subprocess.call
.
#start and block until done
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])
如果要在执行过程中执行操作或将内容输入stdin
,则可以在popen
调用后使用communicate
.
If you want to do things while it is executing or feed things into stdin
, you can use communicate
after the popen
call.
#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
可能会死锁,因此建议进行通信.
As stated in the documentation, wait
can deadlock, so communicate is advisable.
这篇关于Python popen命令.等待命令完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!