2012-01-17 56 views
8

尝试将子进程的输出重定向到文件。subprocess.Popen()IO重定向

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()导致重定向不起作用。 ps -aux显示server.py已正确启动。

回答

7

Altenatively,您可以使用stdout参数与文件对象:

with open('temp.txt', 'w') as output: 
    server = subprocess.Popen('./server.py', stdout=output) 
    server.communicate() 

正如documentation解释说:

标准输入,输出和错误指定执行程序的标准输入,标准输出和标准错误文件句柄。有效值是PIPE,现有文件描述符(正整数),现有文件对象和None。

+0

这是有效的。沟通会阻止阅读器,直到服务器终止,但现在我可以重定向,我可以发送服务器输出到FIFO。 – 2012-01-17 23:37:09

+1

这里不需要调用'.communicate()'。 'subprocess.check_call('command',stdout = file)'工作。 – jfs 2015-11-06 23:21:29

4

使用“>”输出重定向是shell的一项功能 - 默认情况下,subprocess.Popen未实例化一个。这应该工作:

server = subprocess.Popen(args, shell=True) 
+0

使用'shell = True'不是首选的方式,除非有必要(并且它不是) – wim 2012-01-17 23:20:29