python - 如何在 Jupyter 笔记本中打印时重新定位光标

标签 python jupyter-notebook carriage-return

我想在 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")

目标结果如下:它在时间 i=0 时打印:

Something I won't update.
a0
b1

然后在时间i=1,上面的三行被替换为:

Something I won't update.
a1
b2

等等等等......

这在终端中可以正常工作,但在我的笔记本中却不能,其中 ANSI 转义 \033[A 被视为空字符 ''。换句话说,在 Jupyter 中,我得到的时间 i=0:

Something I won't update.
a0
b1

在时间 i=1 时,输出更新如下:

Something I won't update.
a0
a1
b2

__编辑__

Stack Overflow 上也提出了类似的问题:

Overwrite previous output in jupyter notebook Overwrite previous output in Jupyter Notebook

How to overwrite the previous print line in Jupyter / IPython How to overwrite the previous print line in Jupyter IPython

但是,它们仅涵盖以下情况:

  • 如何重写可以通过以下方式处理的单行:
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) 

这不适用于段落(多行)。该行为与上述行为相同。

  • 如何重写整个单元格:
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))

此处的行为不是所需的行为,因为 Something I won't update. 行将消失。在更实际的用例中,我还有其他要显示的内容,例如我不想删除的 matplotlib 图形。

这道题的目的是能够重写几行特定的行。有没有办法在 Jupyter 中获得所需的行为?

最佳答案

在 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))

关于python - 如何在 Jupyter 笔记本中打印时重新定位光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57093743/

相关文章:

python - json.dump 时如何显式设置回车?

Python创建额外的文件夹

python - Sentry 与 Mongodb 兼容吗?

jupyter-notebook - 在 Jupyter 中安装 xeus-cling 后,C++14 不可见(Ubuntu 18.04 - Anaconda)

windows-10 - Jupyter notebook 无法从命令提示符打开

python-3.x - 将图片从 Google Drive 导入到 Google Colab

C语言 : How do I ignore carriage return and line feed when reading from text file?

windows - 为什么我在使用 Perl 下载的网页中出现额外的换行符?

python - c 下划线表达式 `c_` 究竟做了什么?

python - 扭曲的记录