Python popen命令。等到命令完成

时间:2010-05-14 20:00:30

标签: python wait popen

我有一个脚本,我用popen shell命令启动。 问题是脚本不会等到popen命令完成后立即继续。

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

如何判断我的Python脚本要等到shell命令完成?

7 个答案:

答案 0 :(得分:89)

根据您希望如何处理脚本,您有两种选择。如果您希望命令在执行时阻止而不执行任何操作,则可以使用subprocess.call

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

如果您想在执行活动或将内容送入stdin时执行操作,则可以在communicate来电后使用popen

#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可能会死锁,因此建议进行通信。

答案 1 :(得分:14)

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

答案 2 :(得分:5)

您正在寻找的是wait方法。

答案 3 :(得分:1)

wait()对我来说很好。子过程p1,p2和p3同时执行。因此,所有过程都在3秒钟后完成。

import subprocess

processes = []

p1 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
p2 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
p3 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)

processes.append(p1)
processes.append(p2)
processes.append(p3)

for p in processes:
    if p.wait() != 0:
        print("There was an error")

print("all processed finished")

答案 4 :(得分:0)

让您尝试传递的命令为

os.system('x')

然后你将它转换为声明

t = os.system('x')

现在python将等待命令行的输出,以便可以将其分配给变量t

答案 5 :(得分:0)

强制popen在执行以下操作读取所有输出之前不继续:

os.popen(command).read()

答案 6 :(得分:0)

我认为process.communicate()将适合具有较小尺寸的输出。对于较大的输出,这不是最佳方法。