Python输出在最后一行打印之上

时间:2017-04-12 15:23:35

标签: python command-line printing format output

python中有没有办法在打印的最后一行上方的命令行中打印一些东西?或者,与我想要实现的类似,保持最后一行完整,即不覆盖它。

这样做的目的是让命令行中的最后一行成为状态/百分比栏。

输出示例:

File 1 processed
(0.1% Completed)

下次刷新:

File 1 processed
File 2 processed
(0.2% Completed)

下次刷新:

File 1 processed
File 2 processed
File 3 processed
(0.3% Completed)

2 个答案:

答案 0 :(得分:4)

from time import sleep
erase = '\x1b[1A\x1b[2K'

def download(number):
    print(erase + "File {} processed".format(number))

def completed(percent):
    print("({:1.1}% Completed)".format(percent))

for i in range(1,4):
    download(i)
    completed(i/10)
    sleep(1)

在我的python 3.4中工作,最终输出是:

File 1 processed
File 2 processed
File 3 processed
(0.3% Completed)

如果您想了解有关终端转义码的更多信息,请尝试:https://en.wikipedia.org/wiki/ANSI_escape_code

根据要求,带有空格的示例:

from time import sleep
erase = '\x1b[1A\x1b[2K'

def download(number):
    print(erase*2 + "File {} processed".format(number))

def completed(percent):
    print("\n({:1.1}% Completed)".format(percent))

print("\n(0.0% Completed)")
for i in range(1,5):
    download(i)
    completed(i/10)
    sleep(1)

最终输出是:

File 1 processed
File 2 processed
File 3 processed
File 4 processed

(0.4% Completed)

答案 1 :(得分:2)

查看\r命令。这可以解决问题。

for i in range(2):
    print '\rFile %s processed' % i
    print '(0.%s%% Completed)' % i,

输出是:

File 0 processed
File 1 processed
(0.1% Completed)