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

PyC*_*yCV 8 python printing format command-line output

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

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

输出示例:

File 1 processed
(0.1% Completed)
Run Code Online (Sandbox Code Playgroud)

下次刷新:

File 1 processed
File 2 processed
(0.2% Completed)
Run Code Online (Sandbox Code Playgroud)

下次刷新:

File 1 processed
File 2 processed
File 3 processed
(0.3% Completed)
Run Code Online (Sandbox Code Playgroud)

muc*_*cka 6

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)
Run Code Online (Sandbox Code Playgroud)

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

File 1 processed
File 2 processed
File 3 processed
(0.3% Completed)
Run Code Online (Sandbox Code Playgroud)

如果您想了解有关终端转义码的更多信息,请尝试: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)
Run Code Online (Sandbox Code Playgroud)

最终输出为:

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

(0.4% Completed)
Run Code Online (Sandbox Code Playgroud)