打印到控制台终端而不是 IPython 笔记本的单元格输出

Print into console terminal not into cell output of IPython Notebook

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

我试过以下方法:

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

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

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

在 IPython 单元格中键入以上代码并对其进行计算。之后所有输出将显示在终端中。

在 Windows 上,这可以工作:

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

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

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 中打印错误消息)没有任何冲突细胞输出)。