【发布时间】:2015-06-09 10:22:25
【问题描述】:
我想打印到运行 IPython Notebook 的终端窗口,而不是单元格输出。当我发出大量print 调用时,打印到单元格输出会消耗更多内存并减慢我的系统速度。从本质上讲,我希望this 行为是设计的。
我尝试了以下方法:
【问题讨论】:
标签: python windows ipython ipython-notebook python-3.4
我想打印到运行 IPython Notebook 的终端窗口,而不是单元格输出。当我发出大量print 调用时,打印到单元格输出会消耗更多内存并减慢我的系统速度。从本质上讲,我希望this 行为是设计的。
我尝试了以下方法:
【问题讨论】:
标签: python windows ipython ipython-notebook python-3.4
您必须将输出重定向到系统标准输出设备。这取决于您的操作系统。在 Mac 上是:
import sys
sys.stdout = open('/dev/stdout', 'w')
在 IPython 单元格中键入上述代码并对其进行评估。之后所有的输出都会显示在终端中。
【讨论】:
stdout:nb_stdout = sys.stdout。现在,您将重定向输出。要返回笔记本输出,只需写:sys.stdout = nb_stdout。更简洁的解决方案是使用 contextlib.redirect_stdout(new_target) 上下文管理器。
contextlib.redirect_stdout 仅适用于 python 3.4 及更高版本。
sys.stderr = open('/dev/stderr', 'w');但是我如何使它适用于 Windows?
在 Windows 上,这可以工作:
import sys
sys.stdout = open(1, 'w')
【讨论】:
sys.stderr 呢?
为了能够轻松地从一种形式切换到另一种形式:
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 单元格输出中打印错误消息)没有任何冲突。
【讨论】: