2
所以我試圖重定向stdout
我的Jupyter筆記本電腦的一些單元格與this文件,然後取消它與this其餘的單元格。來自第一組單元格的輸出按照它的意圖着陸在文件中。取消命令sys.stdout = sys.__stdout__
後的第二組單元沒有輸出,似乎什麼都不做,但後來我意識到它正在登陸筆記本的終端。從Jupyter筆記本標準輸出重定向是登陸在終端
它完全在Python解釋器完全一樣的Python:
(miniconda3-latest) [email protected]:~/Documents/project1 $ python
Python 3.6.0 |Continuum Analytics, Inc.| (default, Dec 23 2016, 12:22:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout = open('stdout.txt', 'w')
>>> print("a")
>>> print("a")
>>> print("a")
>>> sys.stdout = sys.__stdout__
>>> print ("b")
b
>>> print ("b")
b
>>> print ("b")
b
>>> # lots of a's are in the file and no b's
在Jupyter筆記本類似的方法在終端給這個:
[W 22:05:34.192 NotebookApp] 404 GET /nbextensions/widgets/notebook/js/extension.js (127.0.0.1) 1.71ms referer=http://localhost:8889/notebooks/test_stdout.ipynb
b
b
b
這個代碼怎麼可能這樣在復位之後,我得到b出現在輸出通常在哪個單元下,而不是在終端中?
謝謝,這是有效的。從來沒有想過這是你可以備份的東西,但是當我在筆記本上查看'old_stdout'的對象時,它看起來像這樣:'' –
cardamom
我必須承認,我甚至沒有注意到「sys .__ stdout__」甚至存在。我總是使用我的答案中描述的方法(必須使用像C這樣的語言,其中的一切都必須用手完成:))。請注意,您不是在進行備份,它只是存儲_reference_而不是丟失它。 –