在控制台中正确打印 \r

发布于 2024-11-09 22:57:20 字数 308 浏览 5 评论 0原文

当我编写一个更新打印行的脚本时,例如如下所示:

for i in range(101):
    print(str(i) + "% \r", end="")

并使用终端(Ubuntu)运行此脚本,我得到正确的输出,更新了该行:

100%

但是,在 Eclipse 中使用 Pydev,Eclipse 控制台会执行此操作:

0%
1%
2%
...
100%

有谁知道怎么解决这个问题吗?提前致谢!

When I write a script that updates a printed line, for example like this:

for i in range(101):
    print(str(i) + "% \r", end="")

and run this script using the terminal (Ubuntu), I get the correct output, that updated the line:

100%

However, using Pydev in Eclipse, the Eclipse console does this:

0%
1%
2%
...
100%

Anyone know how to fix this? Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

去了角落 2024-11-16 22:57:21

这是因为无论您是否使用 \r ,“print”总是生成一个新行,请尝试使用 sys.stdout 代替:

import time, sys

for i in range(101):
    sys.stdout.write(str(i) + "% \r")
    sys.stdout.flush()
    time.sleep(.3)

This is because 'print' always generates a new line whenever you use \r or not, try sys.stdout instead:

import time, sys

for i in range(101):
    sys.stdout.write(str(i) + "% \r")
    sys.stdout.flush()
    time.sleep(.3)
z祗昰~ 2024-11-16 22:57:21

这似乎是旧的 CR LF 问题。根据您使用的操作系统和控制台,CR 和 LF 作为线路终止符会有不同的解释。

有些系统需要 CRLF 作为行尾。
有些系统只需要 LF,但隐式执行 CR。
有些系统(例如您的系统)在每个 CR 之前隐式执行 LF,尽管这是我第一次看到这种情况。

也许有一种方法可以编辑 PyDev 控制台的换行符设置。

编辑:或者您可以使用 ANSI 转义码来移动光标。类似于 CSInD 表示左侧 n 个字符,CSInC 表示右侧 n 个字符。

This seems to be the old CR LF problem. Depending on the OS and the console you are using, CR and LF as a line termination will be interpreted differently.

Some systems require a CRLF as an end of line.
Some systems only require LF but do the CR implicitly.
Some systems (like yours) do a LF before each CR implicitly, although this is the first time I see this.

Maybe there is a way to edit the newline settings for your PyDev console.

EDIT: Or you might use ANSI escape codes for moving the cursor around. Like CSInD for n characters to the left or CSInC for n characters to the right.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文