如何重定向由第三方python库使用os.system运行的程序的stderr

时间:2011-05-24 13:55:45

标签: python io

我使用外部库,如下所示:

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 代码因为它在第三方库中!

2 个答案:

答案 0 :(得分:2)

为了说明Rosh Oxymoron所说的,你可以破解这样的代码:

from some_lib import runThatProgram

infile = '/tmp/test'
outfile = '/tmp/testout 2>&1'
runThatProgram(infile, outfile)
用这个,它会调用

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

将stderr(2)重定向到stdout(1),所有内容都将记录在你的outfile中。

答案 1 :(得分: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