Python 覆盖jupyter笔记本中以前的输出

Python 覆盖jupyter笔记本中以前的输出,python,jupyter,jupyter-notebook,Python,Jupyter,Jupyter Notebook,假设我有一部分代码在特定时间内运行,每1秒输出如下:迭代X,得分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 现在,当我运行它时,它会在每秒钟后输出一行: It

假设我有一部分代码在特定时间内运行,每1秒输出如下:
迭代X,得分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
现在,当我运行它时,它会在每秒钟后输出一行:

Iteration 1 Score: 0.664167449844
Iteration 2 Score: 0.514757592404
...
是的,当输出变得太大时,html会变成可滚动的,但问题是除了当前的最后一行之外,我不需要这些行中的任何一行。因此,我希望只显示
1
行(最后一行),而不是在
n
秒后显示
n

我还没有在文档中找到类似的东西,也没有通过magic查找。标题几乎相同,但不相关。

完成您描述的(仅适用于Python 3)的通常(有文档记录的)方式是:

在Python 2中,我们必须在打印后
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='')
或者,您可以在
时间之前和之后拆分
打印
s。如果更合理,或者您需要更明确,请执行以下操作:

print('Iteration', i, 'Score:', uniform(0, 1), end='')
time.sleep(1)
print('', end='\r') # or even print('\r', end='')
@cel是对的:

不过,使用clear_output()会让你的笔记本电脑感到不安。我建议也使用display()函数,如下所示(Python 2.7):


这可能是一个解决方案:在macOS上,这似乎不会在笔记本中产生任何输出。@cel,在安装并尝试使用jupyter后,它在Linux上也不起作用。“这不是操作系统,必须是朱彼得做的一些改动。”查佩罗:对不起,我忘了回复你。很遗憾,你的解决方案对我不起作用。Python抱怨此语法
print('\r','something',end='')无效(end='')。您使用的是Python 2.x吗?您是否尝试过从“未来”导入“打印”语句中导入
?print“function”应该接受一个
end
参数。我可以在Python2.x中使用
print“\rsomething”
来完成它,对我来说,这似乎是我的Python版本最简单的解决方案。一个好答案!我认为模块的名称应该是
IPython
。对于快速迭代循环,我建议清除输出(wait=True)。当设置为true时,等待会导致清除延迟,直到收到新的输入。
print('\r', 'Iteration', i, 'Score:', uniform(0, 1), end='')
print('Iteration', i, 'Score:', uniform(0, 1), end='')
time.sleep(1)
print('', end='\r') # or even print('\r', end='')
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