如何启动子进程或运行具有连续输出流并同时运行脚本其余部分的python文件?
这是一些示例代码:
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()
答案 0 :(得分:0)
在示例代码中调用subprocess.Popen()之后,主进程将立即进入print()语句,然后执行doMoreStuff(),同时运行其余的脚本。
答案 1 :(得分:0)
如果您希望程序保持沉默,则需要捕获stderr
以及stdout
。两个选项是stderr=subprocess.STDOUT
,这意味着您想要在stdout管道上交错stdout和err。或者stderr=subprocess.PIPE
保持stderr不同。
但是你有第二个问题。因为您没有阅读stdout
,如果程序输出足够的数据来填充管道,它将会挂起。有一个潜在的第三个问题 - 您需要拨打p.wait()
的某个地方,这样您就不会以僵尸进程结束。
您可以将它们发送到文件:
proc = subprocess.Popen('python myScript.py', shell=True,
stdout=open('stdout.txt', 'wb'), stderr=open('stderr.txt', 'wb'))
或者让后台线程完成工作:
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()
或将它们发送到位桶
proc = subprocess.Popen('python myScript.py', shell=True,
stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT)