Skip to main content
 首页 » 编程设计

python之有没有办法将 stderr 重定向到 Jupyter 中的文件

2024年10月24日1252php

IPython.utils 中有一个 redirect_output 函数,还有一个 %%capture 魔法函数,但现在都没有了,this thread关于这个话题现在已经过时了。

我想做如下的事情:

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 输出一行。然后我想获取输出,munge 它并绘制数据。

请您参考如下方法:

您可以尝试用与建议相同的方式将 sys.stderr 替换为其他文件描述符 here .

import sys 
oldstderr = sys.stderr 
sys.stderr = open('log.txt', 'w') 
# do something 
sys.stderr = oldstderr 

更新:从 Python 3.4 开始,您应该考虑使用 contextlib.redirect_stdout()相反,像这样:

f = io.StringIO() 
with redirect_stdout(f): 
    print('a') 
s = f.getvalue()