2011-05-24 97 views
2

我使用外部库运行,像这样的节目的标准错误:如何重定向正在使用使用os.system由第三方Python库

from some_lib import runThatProgram 

infile = '/tmp/test' 
outfile = '/tmp/testout' 
runThatProgram(infile, outfile) 

而runThatProgram是:

def runThatProgram(infile, outfile): 
    os.system("%s %s > %s" % ('thatProgram', infile, outfile)) 

问题是'thatProgram'在STDERR上返回很多东西,我想将它重定向到一个文件,但我无法编辑runThatProgram代码,因为它在第三方lib!

+1

您应该避免使用那些为易碎的和不安全的东西库。 – 2011-05-24 14:13:23

+1

你为什么不使用子流程?在调用'subprocess.Popen()'参数'stderr'到你想要重定向到的文件描述符时,你可以设置子进程。 – mouad 2011-05-24 14:40:16

+0

Rosh,相信我,在这个库上独立于我的TODO列表上:-) – jan 2011-05-24 20:09:41

回答

2

为了说明什么犹太矛盾修饰法说,你可以破解这样的代码:

from some_lib import runThatProgram 

infile = '/tmp/test' 
outfile = '/tmp/testout 2>&1' 
runThatProgram(infile, outfile) 

这一点,它会调用

thatProgram /tmp/test > /tmp/testout 2>&1 

,将重定向标准错误(2)到stdout(1 ),并且所有内容都将记录在您的outfile中。

+0

这太棒了!我做了小修改'2>/dev/null',因为runThatProgram需要原始格式的标准输出,并且确实有效! – jan 2011-05-24 20:08:48

0

为了详细说明使用subprocess,你可以打开它,给它一个管道,然后从工作有这么

import subprocess 
program = "runthatprogram.py".split() 
process = subprocess.Popen(program, stdout = subprocess.PIPE, stderr = open('stderr','w')) #stderr to fileobj 
process.communicate()[0] #display stdout