【问题标题】:Log results in Jupyter notebook and shell at the same time同时在 Jupyter notebook 和 shell 中记录结果
【发布时间】:2021-10-12 03:39:44
【问题描述】:

我在~/.ipython/profile_default/startup 放置了一个代码片段,它将在 Jupyter 笔记本上执行的打印语句的输出重定向到单元格,基本上如下。

sys.stdout = open(1,'w')

这样做的问题是 Jupyter notebook 中的打印结果不再显示,它只被重定向到shell 并且没有显示在notebook 中。

如何将结果发送到 shell,同时又将结果显示在 Jupyter 笔记本中?

非常感谢您的帮助。

【问题讨论】:

    标签: python jupyter-notebook ipython jupyter-lab


    【解决方案1】:

    我能够做到。这是解决方案。

    import sys
    import logging
    
    class Logger(object):
        def __init__(self, filename = 1):
            self.terminal = sys.stdout
            self.log = open(filename, "a")
        def __getattr__(self, attr):
            return getattr(self.terminal, attr)
        def write(self, message):
            self.log.write(message)
            
        def flush(self):
            self.log.flush()
    

    通过将此文件放在启动文件夹中,它会将打印记录到 shell 和笔记本中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-27
      • 2019-09-05
      • 1970-01-01
      • 2022-11-15
      • 2018-06-30
      • 2015-07-05
      • 1970-01-01
      • 2020-11-09
      相关资源
      最近更新 更多