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

发布于 2024-11-09 06:50:48 字数 494 浏览 0 评论 0原文

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

from some_lib import runThatProgram

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

while runThatProgram is:

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

问题是 'thatProgram' 在 STDERR 上返回很多内容,我想将其重定向到一个文件,但我无法编辑< /strong> runThatProgram code 因为它位于第三方库中!

I use external library, like this:

from some_lib import runThatProgram

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

while runThatProgram is:

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

The problem is that 'thatProgram' returns lots of stuff on STDERR, I want to redirect it to a file, but I cannot edit runThatProgram code because it is in third party lib!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

优雅的叶子 2024-11-16 06:50:48

为了说明 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),并且所有内容都将记录在您的输出文件中。

To illustrate what Rosh Oxymoron said, you can hack the code like this :

from some_lib import runThatProgram

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

with this, it will call

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

that will redirected stderr (2) to stdout (1), and everything will be logged in your outfile.

很酷又爱笑 2024-11-16 06:50:48

要详细说明如何使用 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

To elaborate on using subprocess, you can open it, give it a pipe and then work from there so

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文