mic*_*ele 65 python subprocess popen wait
我有一个脚本,我用popen启动一个shell命令.问题是脚本不会等到popen命令完成后立即继续.
om_points = os.popen(command, "w")
.....
Run Code Online (Sandbox Code Playgroud)
如何判断我的Python脚本要等到shell命令完成?
unh*_*ler 97
根据您希望如何使用脚本,您有两种选择.如果您希望命令在执行时阻止而不执行任何操作,则可以使用subprocess.call.
#start and block until done
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])
Run Code Online (Sandbox Code Playgroud)
如果您想在执行或进行操作时执行操作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
Run Code Online (Sandbox Code Playgroud)
如文档中所述,wait可能会死锁,因此建议进行通信.
Tou*_*one 18
你可以用它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
Run Code Online (Sandbox Code Playgroud)
小智 18
popen通过执行以下操作强制在读取所有输出之前不继续:
os.popen(command).read()
Run Code Online (Sandbox Code Playgroud)
Chi*_*NRM 10
让您尝试传递的命令成为
os.system('x')
Run Code Online (Sandbox Code Playgroud)
然后你把它转换成一个声明
t = os.system('x')
Run Code Online (Sandbox Code Playgroud)
现在,python 将等待命令行的输出,以便将其分配给变量t。
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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
127756 次 |
| 最近记录: |