Is There A Way To Redirect Stderr To File In Jupyter?
There was a redirect_output function in IPython.utils, and there was a %%capture magic function, but these are now gone, and this thread on the topic is now outdated. I'd like to d
Solution 1:
You could probably try replacing sys.stderr
with some other file descriptor the same way as suggested here.
import sys
oldstderr = sys.stderr
sys.stderr = open('log.txt', 'w')
# do something
sys.stderr = oldstderr
Update: starting form Python 3.4, you should consuder using contextlib.redirect_stdout()
instead, like this:
f = io.StringIO()
withredirect_stdout(f):
print('a')
s = f.getvalue()
Solution 2:
@Ben, just replacing sys.stderr
did not work, and the full flush logic suggested in the post was necessary. But thank you for the pointer as it finally gave me a working version:
import sys
oldstderr = sys.stderr
sys.stderr = open('log.txt', 'w')
classflushfile():
def__init__(self, f):
self.f = f
def__getattr__(self,name):
returnobject.__getattribute__(self.f, name)
defwrite(self, x):
self.f.write(x)
self.f.flush()
defflush(self):
self.f.flush()
sys.sterr = flushfile(sys.stderr)
from __future__ import print_function
# some long running function here, e.g. for i inrange(1000000):
print('hello!', file=sys.stderr)
sys.stderr = oldstderr
It would have been nice if Jupyter kept the redirect_output()
function and/or the %%capture
magic.
Post a Comment for "Is There A Way To Redirect Stderr To File In Jupyter?"