subprocess.Popen()IO重定向 [英] subprocess.Popen() IO redirect
问题描述
尝试将子流程的输出重定向到文件.
Trying to redirect a subprocess' output to a file.
server.py:
server.py:
while 1:
print "Count " + str(count)
sys.stdout.flush()
count = count + 1
time.sleep(1)
Laucher:
cmd = './server.py >temp.txt'
args = shlex.split(cmd)
server = subprocess.Popen( args )
输出出现在屏幕上,temp.txt
保持空白.
我在做什么错了?
The output appear on screen, temp.txt
remains empty.
What am I doing wrong?
作为背景,我试图捕获已经编写的程序的输出.
As background I am trying to capture the output of a program that has already been written.
我不能使用:
server = subprocess.Popen(
[exe_name],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
,因为程序可能无法刷新.
相反,我打算通过fifo重定向输出.如果我手动启动server.py,则此方法工作正常,但如果我Popen()
导致重定向不起作用,则显然不可行.
ps -aux
显示server.py
已正确启动.
as the program may not flush.
Instead I was going to redirect output through a fifo. This works fine if I manually launch server.py but obviously not if I Popen()
cause redirect doesnt work.
ps -aux
shows that server.py
was launched correctly.
推荐答案
或者,您可以将stdout
参数与文件对象一起使用:
Altenatively, you can use the stdout
parameter with a file object:
with open('temp.txt', 'w') as output:
server = subprocess.Popen('./server.py', stdout=output)
server.communicate()
如文档中所述:
stdin,stdout和stderr分别指定执行程序的标准输入,标准输出和标准错误文件句柄.有效值为PIPE,现有文件描述符(正整数),现有文件对象和无.
stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None.
这篇关于subprocess.Popen()IO重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!