[英]How do I hide the output from a subprocess and continue the script execution?
How do I start a subprocess or run a python file that has a continuous stream of output and simultaneously run the rest of the script? 如何启动子流程或运行具有连续输出流的python文件,并同时运行脚本的其余部分?
here is some example code: 这是一些示例代码:
import subprocess
p = subprocess.Popen('python myScript.py', shell=True, stdout=subprocess.PIPE)
#this program will have a stream of output and is designed to run for
#long periods of time
print 'the program is still running!'
doMoreStuff()
在示例代码中调用subprocess.Popen()之后,主进程将立即进入print()语句,然后执行doMoreStuff(),同时运行其余脚本。
If you want the program to be silent, you need to capture stderr
as well as stdout
. 如果您希望程序保持静音,则需要捕获stderr
和stdout
。 Two choices are stderr=subprocess.STDOUT
meaning you want to interleave stdout and err on the stdout pipe. 两个选择是stderr=subprocess.STDOUT
这意味着您要在stdout管道上交错stdout和err。 Or stderr=subprocess.PIPE
to keep stderr distinct. 或stderr=subprocess.PIPE
来保持stderr与众不同。
But you have a second problem. 但是你还有第二个问题。 Because you don't read stdout
, if the program outputs enough data to fill the pipe it will hang. 因为您不读stdout
,所以如果程序输出足够的数据来填充管道,它将挂起。 There is a potential third problem - somewhere along the line you need to call p.wait()
so that you don't end up with zombie processes. 存在潜在的第三个问题-可能需要调用p.wait()
以免最终p.wait()
僵尸进程。
You could send them to a file: 您可以将它们发送到文件中:
proc = subprocess.Popen('python myScript.py', shell=True,
stdout=open('stdout.txt', 'wb'), stderr=open('stderr.txt', 'wb'))
Or have background threads do the work: 或让后台线程完成工作:
def out_err_thread(out_err_list, proc):
out, err = proc.communicate()
proc = subprocess.Popen('python myScript.py', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_err = []
_t = threading.Thread(target=out_err_thread, args=(out_err, proc))
_t.start()
Or send them to the bit bucket 或将它们发送到位桶
proc = subprocess.Popen('python myScript.py', shell=True,
stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.