实现如下所示的状态栏:

[==========                ]  45%
[================          ]  60%
[==========================] 100%

我想把这个打印到标准输出,并保持刷新,而不是打印到另一行。如何做到这一点?


当前回答

import progressbar
import time

# Function to create  
def animated_marker():
    widgets = ['Loading: ', progressbar.Bar('=', '[', ']', '-'), progressbar.Percentage()]
    bar = progressbar.ProgressBar(max_value=200,widgets=widgets).start() 
      
    for i in range(200): 
        time.sleep(0.1)
        bar.update(i+1)
    bar.finish()

# Driver's code 
animated_marker()

其他回答

使用@Mark-Rushakoff的答案,我想出了一个更简单的方法,不需要调用sys库。它适用于Python 3。Windows测试:

from time import sleep
for i in range(21):
    # the exact output you're looking for:
    print ("\r[%-20s] %d%%" % ('='*i, 5*i), end='')
    sleep(0.25)

最简单的还是

import sys
total_records = 1000
for i in range (total_records):
    sys.stdout.write('\rUpdated record: ' + str(i) + ' of ' + str(total_records))
    sys.stdout.flush()

关键是将整数类型转换为字符串。

你可以使用\r(回车)。演示:

import sys
total = 10000000
point = total / 100
increment = total / 20
for i in xrange(total):
    if(i % (5 * point) == 0):
        sys.stdout.write("\r[" + "=" * (i / increment) +  " " * ((total - i)/ increment) + "]" +  str(i / point) + "%")
        sys.stdout.flush()

要成为纯python并且不进行系统调用:

from time import sleep

for i in range(21):
    spaces = " " * (20 - i)
    percentage = 5*i
    print(f"\r[{'='*i}{spaces}]{percentage}%", flush=True, end="")
    sleep(0.25)

'\r'字符(回车)将光标重置到行首,并允许您重写该行之前的内容。

from time import sleep
import sys

for i in range(21):
    sys.stdout.write('\r')
    # the exact output you're looking for:
    sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i))
    sys.stdout.flush()
    sleep(0.25)

我不能100%确定这是否可以在所有系统上完全移植,但它至少可以在Linux和OSX上运行。