On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).
在Unix上,我可以使用\ r(回车)或\ b(退格)来打印在shell中已经可见的文本(即再次覆盖当前行)。
Can I achieve the same effect in a Windows command line from a Python script?
我可以从Python脚本在Windows命令行中实现相同的效果吗?
I tried the curses module but it doesn't seem to be available on Windows.
我尝试了curses模块,但它似乎在Windows上不可用。
9 个解决方案
#1
yes:
import sys
import time
def restart_line():
sys.stdout.write('\r')
sys.stdout.flush()
sys.stdout.write('some data')
sys.stdout.flush()
time.sleep(2) # wait 2 seconds...
restart_line()
sys.stdout.write('other different data')
sys.stdout.flush()
#2
import sys
import time
for i in range(10):
print '\r', # print is Ok, and comma is needed.
time.sleep(0.3)
print i,
sys.stdout.flush() # flush is needed.
And if on the IPython-notebook, just like this:
如果在IPython-notebook上,就像这样:
import time
from IPython.display import clear_output
for i in range(10):
time.sleep(0.25)
print(i)
clear_output(wait=True)
#3
I know this is old, but i wanted to tell my version (it works on my PC in the cmd, but not in the idle) to override a line in Python 3:
我知道这是旧的,但我想告诉我的版本(它在我的PC上的cmd,但不是在空闲状态下)来覆盖Python 3中的一行:
>>> from time import sleep
>>> for i in range(400):
>>> print("\r" + str(i), end="")
>>> sleep(0.5)
EDIT: It works on Windows and on Ubuntu
编辑:它适用于Windows和Ubuntu
#4
I just had this problem. You can still use \r
, even in Windows Command Prompt, however, it only takes you back to the previous linebreak (\n
).
我刚遇到这个问题。即使在Windows命令提示符下,您仍然可以使用\ r \ n,但它只会将您带回到上一个换行符(\ n)。
If you do something like this:
如果您这样做:
cnt = 0
print str(cnt)
while True:
cnt += 1
print "\r" + str(cnt)
You'll get:
0
1
2
3
4
5
...
That's because \r
only goes back to the last line. Since you already wrote a newline character with the last print statement, your cursor goes from the beginning of a new empty line to the beginning of the same new empty line.
那是因为\ r只会回到最后一行。由于您已使用最后一个print语句编写了换行符,因此光标从新的空行开始到同一个新空行的开头。
To illustrate, after you print the first 0, your cursor would be here:
为了说明,在打印第一个0后,您的光标将在此处:
0
| # <-- Cursor
When you \r
, you go to the beginning of the line. But you're already on the beginning of the line.
当你\ r,你去了行的开头。但是你已经开始了。
The fix is to avoid printing a \n
character, so your cursor is on the same line and \r
overwrites the text properly. You can do that with print 'text',
. The comma prevents the printing of a newline character.
修复是为了避免打印\ n字符,因此光标位于同一行并且\ r \ n会正确覆盖文本。你可以用print'text'来做到这一点。逗号可防止打印换行符。
cnt = 0
print str(cnt),
while True:
cnt += 1
print "\r" + str(cnt),
Now it will properly rewrite lines.
现在它将正确地重写行。
Note that this is Python 2.7, hence the print
statements.
请注意,这是Python 2.7,因此是print语句。
#5
easy method :)
简单的方法:)
import sys
from time import sleep
import os
#print("\033[y coordinate;[x coordinateH Hello")
os.system('cls')
sleep(0.2)
print("\033[1;1H[]")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H[]")
sleep(0.2)
#6
Simple way if you're just wanting to update the previous line:
如果您只想更新上一行,那么简单方法:
import time
for i in range(20):
print str(i) + '\r',
time.sleep(1)
#7
On Windows (python 3), it seems to work (not using stdout directly):
在Windows(python 3)上,它似乎工作(不直接使用stdout):
import sys
for i in reversed(range(0,20)):
time.sleep(0.1)
if(i == 19):
print(str(i), end='', file=sys.stdout)
else:
print("\r{0:{width}".format(str(i), width = w, fill = ' ', align = 'right'), end='', file=sys.stdout)
sys.stdout.flush()
w = len(str(i))
The same line is updated everytime print function is called.
每次调用打印函数时都会更新相同的行。
This algorithm can be improved, but it is posted to show what you can do. You can modify the method according to your needs.
此算法可以进行改进,但会发布以显示您可以执行的操作。您可以根据需要修改方法。
#8
Easiest way is to use two \r - one at the beginning and one at the end
最简单的方法是在开头使用两个\ r - 一个,在结尾使用一个
for i in range(10000):
print('\r'+str(round(i*100/10000))+'% Complete\r'),
It will go pretty quickly
它会很快
#9
Thanks for all the useful answers in here guys. I needed this :)
感谢这里的所有有用的答案。我需要这个:)
I found nosklo's answer particularly useful, but I wanted something fully contained within a function by passing the desired output as a parameter. Also, I didn't really need the timer, since I wanted the printing to take place after a specific event).
我发现nosklo的答案特别有用,但我希望通过将所需的输出作为参数传递,完全包含在函数中。此外,我并不真正需要计时器,因为我希望在特定事件之后进行打印)。
This is what did the trick for me, I hope someone else finds it useful:
这就是我的诀窍,我希望其他人觉得它很有用:
import sys
def replace_cmd_line(output):
"""Replace the last command line output with the given output."""
sys.stdout.write(output)
sys.stdout.flush()
sys.stdout.write('\r')
sys.stdout.flush()
#1
yes:
import sys
import time
def restart_line():
sys.stdout.write('\r')
sys.stdout.flush()
sys.stdout.write('some data')
sys.stdout.flush()
time.sleep(2) # wait 2 seconds...
restart_line()
sys.stdout.write('other different data')
sys.stdout.flush()
#2
import sys
import time
for i in range(10):
print '\r', # print is Ok, and comma is needed.
time.sleep(0.3)
print i,
sys.stdout.flush() # flush is needed.
And if on the IPython-notebook, just like this:
如果在IPython-notebook上,就像这样:
import time
from IPython.display import clear_output
for i in range(10):
time.sleep(0.25)
print(i)
clear_output(wait=True)
#3
I know this is old, but i wanted to tell my version (it works on my PC in the cmd, but not in the idle) to override a line in Python 3:
我知道这是旧的,但我想告诉我的版本(它在我的PC上的cmd,但不是在空闲状态下)来覆盖Python 3中的一行:
>>> from time import sleep
>>> for i in range(400):
>>> print("\r" + str(i), end="")
>>> sleep(0.5)
EDIT: It works on Windows and on Ubuntu
编辑:它适用于Windows和Ubuntu
#4
I just had this problem. You can still use \r
, even in Windows Command Prompt, however, it only takes you back to the previous linebreak (\n
).
我刚遇到这个问题。即使在Windows命令提示符下,您仍然可以使用\ r \ n,但它只会将您带回到上一个换行符(\ n)。
If you do something like this:
如果您这样做:
cnt = 0
print str(cnt)
while True:
cnt += 1
print "\r" + str(cnt)
You'll get:
0
1
2
3
4
5
...
That's because \r
only goes back to the last line. Since you already wrote a newline character with the last print statement, your cursor goes from the beginning of a new empty line to the beginning of the same new empty line.
那是因为\ r只会回到最后一行。由于您已使用最后一个print语句编写了换行符,因此光标从新的空行开始到同一个新空行的开头。
To illustrate, after you print the first 0, your cursor would be here:
为了说明,在打印第一个0后,您的光标将在此处:
0
| # <-- Cursor
When you \r
, you go to the beginning of the line. But you're already on the beginning of the line.
当你\ r,你去了行的开头。但是你已经开始了。
The fix is to avoid printing a \n
character, so your cursor is on the same line and \r
overwrites the text properly. You can do that with print 'text',
. The comma prevents the printing of a newline character.
修复是为了避免打印\ n字符,因此光标位于同一行并且\ r \ n会正确覆盖文本。你可以用print'text'来做到这一点。逗号可防止打印换行符。
cnt = 0
print str(cnt),
while True:
cnt += 1
print "\r" + str(cnt),
Now it will properly rewrite lines.
现在它将正确地重写行。
Note that this is Python 2.7, hence the print
statements.
请注意,这是Python 2.7,因此是print语句。
#5
easy method :)
简单的方法:)
import sys
from time import sleep
import os
#print("\033[y coordinate;[x coordinateH Hello")
os.system('cls')
sleep(0.2)
print("\033[1;1H[]")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H[]")
sleep(0.2)
#6
Simple way if you're just wanting to update the previous line:
如果您只想更新上一行,那么简单方法:
import time
for i in range(20):
print str(i) + '\r',
time.sleep(1)
#7
On Windows (python 3), it seems to work (not using stdout directly):
在Windows(python 3)上,它似乎工作(不直接使用stdout):
import sys
for i in reversed(range(0,20)):
time.sleep(0.1)
if(i == 19):
print(str(i), end='', file=sys.stdout)
else:
print("\r{0:{width}".format(str(i), width = w, fill = ' ', align = 'right'), end='', file=sys.stdout)
sys.stdout.flush()
w = len(str(i))
The same line is updated everytime print function is called.
每次调用打印函数时都会更新相同的行。
This algorithm can be improved, but it is posted to show what you can do. You can modify the method according to your needs.
此算法可以进行改进,但会发布以显示您可以执行的操作。您可以根据需要修改方法。
#8
Easiest way is to use two \r - one at the beginning and one at the end
最简单的方法是在开头使用两个\ r - 一个,在结尾使用一个
for i in range(10000):
print('\r'+str(round(i*100/10000))+'% Complete\r'),
It will go pretty quickly
它会很快
#9
Thanks for all the useful answers in here guys. I needed this :)
感谢这里的所有有用的答案。我需要这个:)
I found nosklo's answer particularly useful, but I wanted something fully contained within a function by passing the desired output as a parameter. Also, I didn't really need the timer, since I wanted the printing to take place after a specific event).
我发现nosklo的答案特别有用,但我希望通过将所需的输出作为参数传递,完全包含在函数中。此外,我并不真正需要计时器,因为我希望在特定事件之后进行打印)。
This is what did the trick for me, I hope someone else finds it useful:
这就是我的诀窍,我希望其他人觉得它很有用:
import sys
def replace_cmd_line(output):
"""Replace the last command line output with the given output."""
sys.stdout.write(output)
sys.stdout.flush()
sys.stdout.write('\r')
sys.stdout.flush()