Sal*_*ali 25 python jupyter jupyter-notebook
假设我有一部分代码运行了一段特定的时间,每1秒输出如下:iteration X, score Y.我将用我的黑盒函数替换这个函数:
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
Run Code Online (Sandbox Code Playgroud)
现在,当我在Jupyter笔记本中运行它时,它会在每秒后输出一个新行:
Iteration 1 Score: 0.664167449844
Iteration 2 Score: 0.514757592404
...
Run Code Online (Sandbox Code Playgroud)
是的,在输出变得太大之后,html变得可滚动,但问题是除了当前最后一行之外我不需要任何这些行.因此,我希望只显示一行(最后一行),而不是n在n几秒钟之后使用1行.
我没有在文档中找到这样的东西或者通过魔术找到它.一个几乎相同但无关紧要的问题.
Dan*_*ave 33
@cel是对的:代码中的ipython notebook clear cell输出
但是,使用clear_output()会使您的笔记本电脑产生抖动.我建议使用display()函数,如下所示(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(wait=True)
display('Iteration '+str(i)+' Score: '+str(uniform(0, 1)))
time.sleep(1)
i += 1
Run Code Online (Sandbox Code Playgroud)
cha*_*elo 15
通常(记录)的方式来执行您所描述的(仅适用于Python 3)是:
print('Iteration', i, 'Score:', uniform(0, 1), end='\r')
Run Code Online (Sandbox Code Playgroud)
在Python 2中,我们必须sys.stdout.flush()在打印之后,如下面的答案所示:
print('Iteration', i, 'Score:', uniform(0, 1), end='\r')
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
使用IPython笔记本我不得不连接字符串以使其工作:
print('Iteration ' + str(i) + ', Score: ' + str(uniform(0, 1)), end='\r')
Run Code Online (Sandbox Code Playgroud)
最后,为了使它与Jupyter一起工作,我使用了这个:
print('\r', 'Iteration', i, 'Score:', uniform(0, 1), end='')
Run Code Online (Sandbox Code Playgroud)
或者你可以print在time.sleep它之前和之后拆分它,如果它更有意义,或者你需要更明确:
print('Iteration', i, 'Score:', uniform(0, 1), end='')
time.sleep(1)
print('', end='\r') # or even print('\r', end='')
Run Code Online (Sandbox Code Playgroud)