繁体   English   中英

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

[英]Print into console terminal not into cell output of IPython Notebook

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

我尝试了以下方法:

  1. 我尝试了printsys.stdout.write调用的不同排列
  2. 我在没有帮助的情况下查看了 IPython Notebook 文档hereherehere
  3. 我曾尝试将用作解决方法,但它似乎仅适用于 Python 2.7

您必须将输出重定向到系统标准输出设备。 这取决于您的操作系统。 在 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 单元格中打印错误消息)发生任何冲突输出)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM