【问题标题】:Print into console terminal not into cell output of IPython Notebook打印到控制台终端而不是 IPython Notebook 的单元格输出
【发布时间】:2015-06-09 10:22:25
【问题描述】:

我想打印到运行 IPython Notebook 的终端窗口,而不是单元格输出。当我发出大量print 调用时,打印到单元格输出会消耗更多内存并减慢我的系统速度。从本质上讲,我希望this 行为是设计的。

我尝试了以下方法:

  1. 我尝试了print 和sys.stdout.write 调用的不同排列
  2. 我在没有帮助的情况下查看了 IPython Notebook 文档 here、here 和 here
  3. 我曾尝试使用 this 作为解决方法,但它似乎只适用于 Python 2.7

【问题讨论】:

    标签: python windows ipython ipython-notebook python-3.4


    【解决方案1】:

    您必须将输出重定向到系统标准输出设备。这取决于您的操作系统。在 Mac 上是:

    import sys
    sys.stdout = open('/dev/stdout', 'w')
    

    在 IPython 单元格中键入上述代码并对其进行评估。之后所有的输出都会显示在终端中。

    【讨论】:

    • 有没有办法扭转这种局面?并恢复 ipython 标准输出
    • 你可以例如在重定向之前安全地引用笔记本的stdout:nb_stdout = sys.stdout。现在,您将重定向输出。要返回笔记本输出,只需写:sys.stdout = nb_stdout。更简洁的解决方案是使用 contextlib.redirect_stdout(new_target) 上下文管理器。
    • @MaxPowers 你知道在 Windows 中应该写什么吗?
    • @MaxPowers:请注意contextlib.redirect_stdout 仅适用于 python 3.4 及更高版本。
    • 谢谢你,我可以sys.stderr = open('/dev/stderr', 'w');但是我如何使它适用于 Windows?
    【解决方案2】:

    在 Windows 上,这可以工作:

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

    【讨论】:

    • 嘿,你被复制了@MaxPowers 的答案并发帖
    • sys.stderr 呢?
    【解决方案3】:

    为了能够轻松地从一种形式切换到另一种形式:

    terminal_output = open('/dev/stdout', 'w')
    
    print('this will show up in the IPython cell output')
    print('this will show up in the terminal', file=terminal_output)
    

    同样,terminal_error = open('/dev/stderr', 'w') 可用于发送到终端 stderr,与 sys.stderr 的默认行为(即在 IPython 单元格输出中打印错误消息)没有任何冲突。

    【讨论】:

      猜你喜欢
      • 2015-10-24
      • 1970-01-01
      • 2019-08-31
      • 2016-03-27
      • 2018-01-31
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      相关资源
      最近更新 更多