Python popen命令。等待命令完成

112 投票
7 回答
247182 浏览
提问于 2025-04-15 22:43

我有一个脚本,它使用popen来启动一个命令行指令。问题是,这个脚本并不会等到这个popen命令执行完毕就继续往下走。

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

我该怎么告诉我的Python脚本,让它等到这个命令行指令执行完再继续呢?

7 个回答

24

要让 popen 在所有输出都被读取之前不继续执行,可以这样做:

os.popen(command).read()
45

你可以使用 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
139

根据你想要如何运行你的脚本,有两种选择。如果你希望命令在执行时阻塞,也就是说在执行期间不做其他事情,你可以直接使用 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 可能会导致死锁,所以建议使用 communicate

撰写回答