Disable stderr from external library

走远了吗. 提交于 2021-01-28 06:08:46

问题


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

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

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) 

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


回答1:


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.

EDIT (the original answer is wrong):

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/

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'))


来源:https://stackoverflow.com/questions/45283185/disable-stderr-from-external-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!