我想打印到运行IPython Notebook的终端窗口中,而不是打印到单元格输出中。当我发出大量的print
调用时,打印到单元输出会消耗更多的内存并减慢系统速度。从本质上讲,我希望这种行为被设计出来。
我已经试过了:
- 我尝试了
print
和sys.stdout.write
呼叫的不同排列 - 我看了这里,这里和这里的IPython Notebook文档,没有帮助
- 我已经尝试过使用这个作为一个解决方案,但它似乎只在Python 2.7 上工作
必须将输出重定向到系统标准输出设备。这取决于你的操作系统。在Mac上是:
import sys
sys.stdout = open('/dev/stdout', 'w')
在ippython单元格中键入上述代码并对其求值。之后,所有输出将显示在终端中。
在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
的默认行为冲突(即在ippython单元格输出中打印错误消息)。