替换 Python 中的控制台输出 [英] Replace console output in Python
问题描述
我想知道如何像在某些 C/C++ 程序中那样在 Python 中创建那些漂亮的控制台计数器之一.
I'm wondering how I could create one of those nifty console counters in Python as in certain C/C++-programs.
我有一个循环做事,当前的输出是这样的:
I've got a loop doing things and the current output is along the lines of:
Doing thing 0
Doing thing 1
Doing thing 2
...
只更新最后一行会更整洁;
what would be neater would be to just have the last line update;
X things done.
我已经在许多控制台程序中看到过这种情况,我想知道我是否/如何在 Python 中做到这一点.
I've seen this in a number of console programs and am wondering if/how I'd do this in Python.
推荐答案
一个简单的解决方案是在字符串前写"\r"
而不是添加换行符;如果字符串永远不会变短,这就足够了...
An easy solution is just writing "\r"
before the string and not adding a newline; if the string never gets shorter this is sufficient...
sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()
稍微复杂一点的是进度条......这是我正在使用的东西:
Slightly more sophisticated is a progress bar... this is something I am using:
def startProgress(title):
global progress_x
sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
sys.stdout.flush()
progress_x = 0
def progress(x):
global progress_x
x = int(x * 40 // 100)
sys.stdout.write("#" * (x - progress_x))
sys.stdout.flush()
progress_x = x
def endProgress():
sys.stdout.write("#" * (40 - progress_x) + "]\n")
sys.stdout.flush()
你调用 startProgress
传递操作的描述,然后 progress(x)
其中 x
是百分比,最后 endProgress()
You call startProgress
passing the description of the operation, then progress(x)
where x
is the percentage and finally endProgress()
这篇关于替换 Python 中的控制台输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!