我想知道如何像在某些 C/C++ 程序中一样在 Python 中创建那些漂亮的控制台计数器之一。
我有一个循环在做事,当前的输出如下:
Doing thing 0
Doing thing 1
Doing thing 2
...
只有最后一行更新会更整洁;
X things done.
我在许多控制台程序中都看到了这一点,我想知道我是否/如何在 Python 中做到这一点。
最佳答案
一个简单的解决方案是在字符串之前写 "\r"
而不添加换行符;如果字符串永远不会变短,这就足够了......
sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()
稍微复杂一点的是进度条......这是我正在使用的东西:
def start_progress(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 end_progress():
sys.stdout.write("#" * (40 - progress_x) + "]\n")
sys.stdout.flush()
你调用 start_progress
传递操作的描述,然后 progress(x)
其中 x
是百分比,最后是 end_progress ()
关于python - 在 Python 中替换控制台输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6169217/