简体   繁体   English

在Jupyter Notebook中打印时如何在光标上存放信息

[英]How to repositon cursor while printing in Jupyter notebook

I'd like to run the following code in Jupyter notebook: 我想在Jupyter笔记本中运行以下代码:

from time import sleep

print("Something I won't update.")
for i in range(10):
    sleep(.5)
    print("a%d\nb%d" % (i, i+1), end="\033[A\r")

The targeted result is the following: it prints at time i=0 : 目标结果如下:它在时间i=0时打印:

Something I won't update.
a0
b1

Then at time i=1 , the three lines above are replaced by: 然后在时间i=1 ,以上三行被替换为:

Something I won't update.
a1
b2

And so forth and so on... 依此类推...

This works properly in a terminal but not in my notebook where the ANSI escape \\033[A is considered as an empty character '' . 这在终端中正常运行,但在我的笔记本电脑中却不能正常工作,其中ANSI转义\\033[A被视为空字符'' In other words, in Jupyter, I get at time i=0 : 换句话说,在Jupyter中,我的时间为i=0

Something I won't update.
a0
b1

And at time i=1 , the output is updated as follows: 在时间i=1 ,输出更新如下:

Something I won't update.
a0
a1
b2

__EDIT__ __编辑__

Similar questions have been raised on Stack Overflow: 关于堆栈溢出也提出了类似的问题:

Overwrite previous output in jupyter notebook Overwrite previous output in Jupyter Notebook 覆盖 Jupyter Notebook中的先前输出覆盖Jupyter Notebook中的先前输出

How to overwrite the previous print line in Jupyter / IPython How to overwrite the previous print line in Jupyter IPython 如何在Jupyter / IPython 中覆盖上一个打印行如何 在Jupyter IPython 中覆盖上一个打印行

However, they only cover the cases: 但是,它们仅涵盖以下情况:

  • How to rewrite a single line which can be handled by: 如何重写可以由以下方式处理的一行:
import sys
from time import sleep

print("Something I won't update.")
for i in range(10):
    sleep(.5)
    sys.stdout.write("\r%d" % i) 

This is not working with paragraphs (multiple lines). 这不适用于段落(多行)。 The behavior is the same than the one described above. 该行为与上述相同。

  • How to rewrite the whole cell: 如何重写整个单元格:
from IPython.display  import clear_output
from time import sleep

print("Something I won't update.")
for i in range(10):
    sleep(.5)
    clear_output(wait=True)
    print("a%d\nb%d" % (i, i+1))

Here the behavior is not the desired one as the line Something I won't update. 这里的行为不是所希望的,因为“ Something I won't update. will disappear. 会消失。 In a more practical usecase, I have other things to display like matplotlib figures that I don't want to remove. 在更实际的用例中,我还有其他东西要显示,例如我不想删除的matplotlib数字。

The purpose of this question is to be able to rewrite several specific lines . 这个问题的目的是为了能够重写几行 Is there anyway to get the desired behavior in Jupyter ? 无论如何,在Jupyter中可以获得所需的行为吗?

Try this in the jupyter notebook 在jupyter笔记本中尝试

from time import sleep
from IPython.display import clear_output
for i in range(10):
    sleep(.5)
    clear_output(wait=True)
    print("a%d\nb%d" % (i, i+1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM