簡體   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