2016-07-23 88 views
5

假設我有代號的一部分,對於一定的時間具體數額和各1個第二輸出端是這樣運行的:iteration X, score Y。之後每一秒,當我在Jupyter notebook運行覆蓋以前的輸出jupyter筆記本

from random import uniform 
import time 

def black_box(): 
    i = 1 
    while True: 
     print 'Iteration', i, 'Score:', uniform(0, 1) 
     time.sleep(1) 
     i += 1 

現在,它輸出新行:我將取代這個功能我黑匣子功能

Iteration 1 Score: 0.664167449844 
Iteration 2 Score: 0.514757592404 
... 

是,當輸出過之後大的時候,html變成了可滾動的,但事實是,除了當前最後一行之外,我不需要這些行。因此不是n秒後n線,我想只有1線(最後一個)所示。

我沒有找到的文檔這樣的事,或通過魔術尋找。 A question與幾乎相同的標題,但無關緊要。

+0

這可能是一個解決方案:http://stackoverflow.com/questions/24816237/ipython-notebook-clear-cell-代碼輸出 – cel

回答

5

通常的(證明)的方式做你的描述(即只使用Python 3作品)是:

print('Iteration', i, 'Score:', uniform(0, 1), end='\r') 

在Python 2中,我們必須sys.stdout.flush()打印後,因爲它顯示了在這個answer

print('Iteration', i, 'Score:', uniform(0, 1), end='\r') 
sys.stdout.flush() 

使用IPython的筆記本,我不得不字符串連接在一起,使其工作:

print('Iteration ' + str(i) + ', Score: ' + str(uniform(0, 1)), end='\r') 

最後,使其與Jupyter工作,我用這個:

print('\r', 'Iteration', i, 'Score:', uniform(0, 1), end='') 

或者你也可以之前,如果它更有意義的time.sleep後分裂print S,或者你需要更加明確:

print('Iteration', i, 'Score:', uniform(0, 1), end='') 
time.sleep(1) 
print('', end='\r') # or even print('\r', end='') 
+0

在macOS上,這似乎不會在筆記本中產生任何輸出。 – cel

+0

@cel,安裝和使用jupyter努力後,它並沒有在Linux上工作的。這不是操作系統,必須由jupyter進行一些更改。 – chapelo

+1

@cel找到一個*黑客*,使其與Jupyter工作:) – chapelo

5

@cel是正確的:ipython notebook clear cell output in code

使用clear_output()給出使你的筆記本電腦心有餘悸,雖然。我建議使用顯示()函數,以及,這樣的(Python 2.7版):

from random import uniform 
import time 
from IPython.display import display, clear_output 

def black_box(): 
i = 1 
while True: 
    clear_output() 
    display('Iteration '+str(i)+' Score: '+str(uniform(0, 1))) 
    time.sleep(1) 
    i += 1 
+0

一個很好的答案!我想,模塊的名字應該是'IPython'。 – Cnly

+0

upvoted。感謝那。 – Cnly

+0

對於快速迭代循環,我建議使用clear_output(wait = True)。設置爲true時,等待會延遲清除,直到收到新的輸入。 –