Python回车不起作用 [英] Python carriage return not working
问题描述
我有一个长时间运行的脚本,它在数据库中的行上循环.我经常希望它打印它处理了多少行,但每次都不要创建一个新行.这基本上就是我所拥有的:
I have a long-running script that loops over rows in a database. Every so often I'd like it to print how many rows it's processed, but without creating a new line each time. This is essentially what I have:
import sys
mystr = "{} rows complete\r"
for i in range(0, 100):
if i % 10 == 0:
sys.stdout.write(mystr.format(i))
sys.stdout.flush()
当我运行它时(在 Python 2.7.5 64 位,Windows 上)我得到:
When I run this (on Python 2.7.5 64-bit, Windows) I get:
0 rows complete
10 rows complete
20 rows complete
...
100 rows complete
谁能想到为什么回车不起作用?我在这里看到了一些关于 Python 和 \r
的类似问题,但所有的答案都说包括我拥有的 sys.stdout.flush()
.
Can anyone think of why the carriage return isn't working? I've seen some similar questions here about Python and \r
, but all the answers say to include sys.stdout.flush()
, which I have.
推荐答案
使用 \r
可能是正确的方法,但行为在很大程度上取决于文本的输出方式.并非所有终端都会尊重回车:
Using \r
is probably the correct way to go here, but the behaviour depends very much on how the text is being output. Not all terminals will respect a bare carriage return:
cmd.exe
和 powershell.exe
都应该以您期望的方式输出文本(Powershell ISE 没有,但这是一个红鲱鱼).
cmd.exe
and powershell.exe
should both output the text the way you expect (Powershell ISE doesn't but that's a red herring here).
Python 自己的 idle
将忽略回车,所有输出都在一行中.
Python's own idle
will ignore the carriage return, all output comes on one long line.
正如您所指出的,您自己的编辑器的命令窗口也会忽略 \r
.
As you noted, your own editor's command window also ignores \r
.
此外,如果您从交互式窗口尝试,您还会在每一行的末尾得到一些数字输出:那是因为交互式窗口有助于输出对 sys.stdout.flush()
调用的结果代码>.
Also, if you try from an interactive window you also get some numbers output at the end of each line: that's because the interactive windows helpfully outputs the result of the call to sys.stdout.flush()
.
这篇关于Python回车不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!