Python to print out status bar and percentage

后端 未结 20 1037
野的像风
野的像风 2020-11-28 01:01

To implement a status bar like below:

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

相关标签:
20条回答
  • 2020-11-28 01:06

    The '\r' character (carriage return) resets the cursor to the beginning of the line and allows you to write over what was previously on the line.

    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)
    

    I'm not 100% sure if this is completely portable across all systems, but it works on Linux and OSX at the least.

    0 讨论(0)
  • 2020-11-28 01:07

    Further improving, using a function as :

    import sys
    
    def printProgressBar(i,max,postText):
        n_bar =10 #size of progress bar
        j= i/max
        sys.stdout.write('\r')
        sys.stdout.write(f"[{'=' * int(n_bar * j):{n_bar}s}] {int(100 * j)}%  {postText}")
        sys.stdout.flush()
    

    calling example:

    total=33
    for i in range(total):
        printProgressBar(i,total,"blah")
        sleep(0.05)  
    

    output:

    [================================================  ] 96%  blah  
    
    0 讨论(0)
  • 2020-11-28 01:08

    There's a Python module that you can get from PyPI called progressbar that implements such functionality. If you don't mind adding a dependency, it's a good solution. Otherwise, go with one of the other answers.

    A simple example of how to use it:

    import progressbar
    from time import sleep
    bar = progressbar.ProgressBar(maxval=20, \
        widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
    bar.start()
    for i in xrange(20):
        bar.update(i+1)
        sleep(0.1)
    bar.finish()
    

    To install it, you can use easy_install progressbar, or pip install progressbar if you prefer pip.

    0 讨论(0)
  • 2020-11-28 01:10

    Here you can use following code as a function:

    def drawProgressBar(percent, barLen = 20):
        sys.stdout.write("\r")
        progress = ""
        for i in range(barLen):
            if i < int(barLen * percent):
                progress += "="
            else:
                progress += " "
        sys.stdout.write("[ %s ] %.2f%%" % (progress, percent * 100))
        sys.stdout.flush()
    

    With use of .format:

    def drawProgressBar(percent, barLen = 20):
        # percent float from 0 to 1. 
        sys.stdout.write("\r")
        sys.stdout.write("[{:<{}}] {:.0f}%".format("=" * int(barLen * percent), barLen, percent * 100))
        sys.stdout.flush()
    
    0 讨论(0)
  • 2020-11-28 01:10

    Easiest is still

    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()
    

    Key is to convert the integer type to string.

    0 讨论(0)
  • 2020-11-28 01:11

    Building on some of the answers here and elsewhere, I've written this simple function which displays a progress bar and elapsed/estimated remaining time. Should work on most unix-based machines.

    import time
    import sys
    
    percent = 50.0
    start = time.time()
    draw_progress_bar(percent, start)
    
    
    def draw_progress_bar(percent, start, barLen=20):
    sys.stdout.write("\r")
    progress = ""
    for i in range(barLen):
        if i < int(barLen * percent):
            progress += "="
        else:
            progress += " "
    
    elapsedTime = time.time() - start;
    estimatedRemaining = int(elapsedTime * (1.0/percent) - elapsedTime)
    
    if (percent == 1.0):
        sys.stdout.write("[ %s ] %.1f%% Elapsed: %im %02is ETA: Done!\n" % 
            (progress, percent * 100, int(elapsedTime)/60, int(elapsedTime)%60))
        sys.stdout.flush()
        return
    else:
        sys.stdout.write("[ %s ] %.1f%% Elapsed: %im %02is ETA: %im%02is " % 
            (progress, percent * 100, int(elapsedTime)/60, int(elapsedTime)%60,
             estimatedRemaining/60, estimatedRemaining%60))
        sys.stdout.flush()
        return
    
    0 讨论(0)
提交回复
热议问题