我有一个很长的工作,运行几分钟,然后重新启动.该任务输出我捕获的各种信息:
output = subprocess.Popen(cmd,stdout=subprocess.PIPE).communicate()
Run Code Online (Sandbox Code Playgroud)
问题是,我一次只能得到整个输出.我想显示输出,因为程序将它发送到stdout,同时仍然将其推回缓冲区(我需要检查输出是否存在某些字符串).在Ruby中,我会这样做:
IO.popen(cmd) do |io|
io.each_line do |line|
puts line
buffer << line
end
end
Run Code Online (Sandbox Code Playgroud)
你可以尝试这样的事情:
cmd = ["./my_program.sh"]
p = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE) # launch the process
while p.poll() is None: # check if the process is still alive
out = p.stdout.readline() # if it is still alive, grab the output
do_something_with(out) # do what you want with it
Run Code Online (Sandbox Code Playgroud)