问题
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