最后输出行上方的Python输出 [英] Python output above the last printed line
本文介绍了最后输出行上方的Python输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在python中,有没有一种方法可以在命令行的最后一行上方打印某些内容?或者,与我要实现的目标类似,保持最后一行不变,即不要覆盖它.
Is there a way in python to print something in the command line above the last line printed? Or, similarly to what I want to achieve, remain the last line intact, that is, not overwrite it.
这样做的目的是让命令行的最后一行成为状态/百分比栏.
The goal of this is to let the last line in the command line a status/precentage bar.
输出示例:
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)
推荐答案
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中工作,最终输出是:
Works in my python 3.4, final output is:
File 1 processed
File 2 processed
File 3 processed
(0.3% Completed)
如果您想了解有关终端转义码的更多信息,请尝试: https://en.wikipedia.org/wiki/ANSI_escape_code
If you want read more about terminal escape codes try: https://en.wikipedia.org/wiki/ANSI_escape_code
根据要求,带有空格的示例:
As requested, example with a space:
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)
这篇关于最后输出行上方的Python输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文