IPython.utils中有一个redirect_output函数,还有一个%%capture魔法函数,但这些现在都消失了,并且这个线程 https://stackoverflow.com/questions/14571090/ipython-redirecting-output-of-a-python-script-to-a-file-like-bash关于这个话题现在已经过时了。
我想做类似以下的事情:
from IPython.utils import io
from __future__ import print_function
with io.redirect_output(stdout=False, stderr="stderr_test.txt"):
while True:
print('hello!', file=sys.stderr)
想法?为了获得更多上下文,我试图捕获一些运行数小时或数天的 ML 函数的输出,并每 5-10 秒向 stderr 输出一行。然后我想获取输出,对其进行处理并绘制数据。
你也许可以尝试更换sys.stderr
按照建议的方式使用其他一些文件描述符here https://stackoverflow.com/a/31153046/232371.
import sys
oldstderr = sys.stderr
sys.stderr = open('log.txt', 'w')
# do something
sys.stderr = oldstderr
Update:从Python 3.4开始,你应该考虑使用contextlib.redirect_stdout() https://docs.python.org/3.4/library/contextlib.html#contextlib.redirect_stdout相反,像这样:
f = io.StringIO()
with redirect_stdout(f):
print('a')
s = f.getvalue()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)