从外部库禁用 stderr [英] Disable stderr from external library

查看:29
本文介绍了从外部库禁用 stderr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要禁用由某些 *.jar 文件生成的 sys.stderr 消息.

I need to disable sys.stderr messages, which produced by some *.jar file.

这个 *.jar 文件由 subprocess.check_call(cmd) 从外部库 (sklear2pmml 库).

This *.jar file is calling by subprocess.check_call(cmd) from sklear2pmml method __init__.py of external library (sklear2pmml library).

我知道,我可以通过将库代码更改为以下内容来禁用 stderr:

I know, that I can disable stderr by changing library code to something like this:

fnull = open(os.devnull,'w')
subprocess.check_call(cmd,stderr=fnull) 

但是这种尝试导致更改了我不想要的 python 库.如何在没有这种副作用的情况下修复 stderr 输出?

But this treak leads to changing python library, that I don't want. How can I fix stderr output without this side effect?

推荐答案

一种选择可能是像这样临时重定向 sys.stderr:

One option could be to temporarily redirect sys.stderr like this:

old_stderr = sys.stderr
sys.stderr = open(os.devnull, "w")
# put your library call here
sys.stderr = old_stderr

假设您不会多次调用图书馆——我认为这可能是一件非常昂贵的事情.

That's assuming you don't call the library too many times -- I think this could be quite an expensive thing to do.

编辑(原答案错误):

这实际上有点深——Python 的重定向不会影响进程的 STDERR 文件描述符.您需要关闭并重新打开进程的文件描述符.以下博客文章对此进行了描述,该文章还提供了一个实现(用于 STDOUT):

This is actually a bit deeper -- Python's redirection doesn't affect the STDERR file descriptor of the process. You need to close and reopen the file descriptor of your process. This is described in the following blog post, which also provides an implementation (for STDOUT):

http://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/

我不得不稍微更改博客中的代码以使其适用于我的 Python 版本,我正在添加受影响的行:

I had to change the code from the blog slightly to make it work with my version of Python, I'm adding the affected lines:

# Create a new sys.stdout that points to the redirected fd
import codecs
sys.stdout = codecs.getreader("utf-8")(os.fdopen(original_stdout_fd, 'wb'))

这篇关于从外部库禁用 stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆