尝试将子流程的输出重定向到文件。
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
保持为空。我做错了什么?
作为背景,我试图捕捉已经编写的程序的输出。
我不能使用:
server = subprocess.Popen(
[exe_name],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
因为程序可能不会刷新。相反,我打算通过fifo重定向输出。如果我手动启动server.py,这很好,但如果我Popen()
导致重定向不起作用,显然就不行了。CCD_ 3表明CCD_。
另外,您可以将stdout
参数与文件对象一起使用:
with open('temp.txt', 'w') as output:
server = subprocess.Popen('./server.py', stdout=output)
server.communicate()
如文件中所述:
stdin、stdout和stderr分别指定执行程序的标准输入、标准输出和标准错误文件句柄。有效值为PIPE、现有文件描述符(正整数)、现有文件对象和None。
使用">"的输出重定向是shell的一个特性——默认情况下,subprocess.Popen
不会实例化一个。这应该有效:
server = subprocess.Popen(args, shell=True)