如何在命令行应用程序中打印当前行?

在Unix上,我可以使用\ r(回车)或\ b(退格)来打印shell中已经可见的文本(即再次覆盖当前行)。

我可以通过Python脚本在Windows命令行中实现相同的效果吗?

我尝试了curses模块,但似乎没有在Windows上可用。

是:

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() 
 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. 

如果在IPython笔记本上,就像这样:

 import time from IPython.display import clear_output for i in range(10): time.sleep(0.25) print(i) clear_output(wait=True) 

http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/notebooks/Animations%20Using%20clear_output.ipynb

我刚刚有这个问题。 即使在Windows命令提示符下,您仍然可以使用\r ,但是它只会将您带回到以前的换行符( \n )。

如果你做这样的事情:

 cnt = 0 print str(cnt) while True: cnt += 1 print "\r" + str(cnt) 

你会得到:

 0 1 2 3 4 5 ... 

那是因为\r只能回到最后一行。 由于您已经使用最后一个打印语句编写了一个换行符,因此您的光标将从新空行的开始处移动到同一个新空行的开始处。

为了说明,在打印第一个0之后,你的光标将会在这里:

 0 | # <-- Cursor 

当你\r ,你去行的开始。 但是你已经在线的开始。

修正是为了避免打印一个\n字符,所以你的光标在同一行, \r正确覆盖文本。 你可以用print 'text',来做到这一点。 逗号防止打印换行符。

 cnt = 0 print str(cnt), while True: cnt += 1 print "\r" + str(cnt), 

现在它会正确地重写行。

请注意,这是Python 2.7,因此是print语句。

简单的方法:)

 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) 

我知道这是旧的,但我想告诉我的版本(它可以在我的电脑中的cmd,但不是在闲置)重写Python 3中的一行:

 >>> from time import sleep >>> for i in range(400): >>> print("\r" + str(i), end="") >>> sleep(0.5) 

编辑:它适用于Windows和Ubuntu

简单的方法,如果你只是想更新上一​​行:

 import time for i in range(20): print str(i) + '\r', time.sleep(1) 

在Windows(Python 3),它似乎工作(不直接使用标准输出):

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

每次调用打印函数时都会更新相同的行。

这个算法可以被改进,但它被张贴来显示你可以做什么。 您可以根据您的需要修改方法。

最简单的方法是在开头和结尾处使用两个\ r – one

 for i in range(10000): print('\r'+str(round(i*100/10000))+'% Complete\r'), 

它会很快

感谢所有在这里的人有用的答案。 我需要这个:)

我发现nosklo的答案特别有用,但是我希望通过将所需的输出作为参数传递给函数。 另外,我并不需要计时器,因为我想在特定事件之后进行打印)。

这是对我来说是什么,我希望别人觉得它有用:

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