【问题标题】:Overwrite previous output in jupyter notebook覆盖 jupyter notebook 中的先前输出
【发布时间】:2016-11-27 04:20:22
【问题描述】:

假设我有一部分代码运行了特定的时间,并且每 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

现在当我在Jupyter notebook 中运行它时,它每秒输出一个新行:

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

是的,当输出变得太大时,html 变得可滚动,但问题是我不需要这些行中的任何一行,除了当前的最后一行。因此,我不想在n 秒后显示n 行,而是只显示1 行(最后一行)。

我没有在文档中或通过魔法找到类似的东西。 A question 的标题几乎相同,但无关紧要。

【问题讨论】:

标签: python jupyter jupyter-notebook


【解决方案1】:

执行您描述的操作(仅适用于 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之前和之后拆分prints,如果它更有意义的话,或者你需要更明确:

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

【讨论】:

  • 在 macOS 上,这似乎不会在笔记本中产生任何输出。
  • @cel,在安装并尝试使用 jupyter 后,它也无法在 Linux 上运行。这不是操作系统,必须由 jupyter 进行一些更改。
  • @chapelo 抱歉,我忘记回复你了。可悲的是,您的解决方案对我不起作用。 Python 抱怨这个语法 print('\r', 'something', end='') 无效(end ='')。
  • 您使用的是 Python 2.x 吗?你试过from __future__ import print_statement吗?打印“函数”应该接受 end 参数。
  • 我可以在 Python2.x 中使用 print "\rsomething", 完成此操作,对我来说,这似乎是我的 Python 版本最简单的解决方案。
【解决方案2】:

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

不过,使用 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

【讨论】:

  • 一个很好的答案!模块的名字应该是IPython,我想。
  • 对于快速迭代循环,我建议 clear_output(wait=True)。当设置为 true 时,wait 会延迟清除,直到收到新的输入。
猜你喜欢
  • 2018-11-25
  • 1970-01-01
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多