在控制台中正确打印 \r
当我编写一个更新打印行的脚本时,例如如下所示:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为无论您是否使用 \r ,“print”总是生成一个新行,请尝试使用 sys.stdout 代替:
This is because 'print' always generates a new line whenever you use \r or not, try sys.stdout instead:
这似乎是旧的 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.