Python to print out status bar and percentage

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

To implement a status bar like below:

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

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

    Using @Mark-Rushakoff answer, I worked out a simpler approach, no need to call the sys library. It works with Python 3. Tested in 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)
    
    0 讨论(0)
  • 2020-11-28 01:04

    You can use \r (carriage return). Demo:

    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()
    
    0 讨论(0)
  • 2020-11-28 01:04

    As described in Mark Rushakoff's solution, you can output the carriage return character, sys.stdout.write('\r'), to reset the cursor to the beginning of the line. To generalize that solution, while also implementing Python 3's f-Strings, you could use

    from time import sleep
    import sys
    
    n_bar = 50
    iterable = range(33)  # for demo purposes
    n_iter = len(iterable)
    for i, item in enumerate(iterable):
        j = (i + 1) / n_iter
    
        sys.stdout.write('\r')
        sys.stdout.write(f"[{'=' * int(n_bar * j):{n_bar}s}] {int(100 * j)}%")
        sys.stdout.flush()
    
        sleep(0.05)  
        # do something with <item> here
    
    0 讨论(0)
  • 2020-11-28 01:04

    Here is something I have made using the solution by @Mark-Rushakoff. To adaptively adjust to the terminal width.

    from time import sleep
    import os
    import sys
    from math import ceil
    
    l = list(map(int,os.popen('stty size','r').read().split()))
    col = l[1]
    col = col - 6
    
    for i in range(col):
        sys.stdout.write('\r')
        getStr = "[%s " % ('='*i)
        sys.stdout.write(getStr.ljust(col)+"]"+"%d%%" % (ceil((100/col)*i)))
        sys.stdout.flush()
        sleep(0.25)
    print("")
    
    0 讨论(0)
  • 2020-11-28 01:04

    For Python 3.6 the following works for me to update the output inline:

    for current_epoch in range(10):
        for current_step) in range(100):
            print("Train epoch %s: Step %s" % (current_epoch, current_step), end="\r")
    print()
    
    0 讨论(0)
  • 2020-11-28 01:05

    based on the above answers and other similar questions about CLI progress bar, I think I got a general common answer to all of them. Check it at https://stackoverflow.com/a/15860757/2254146

    Here is a copy of the function, but modified to fit your style:

    import time, sys
    
    # update_progress() : Displays or updates a console progress bar
    ## Accepts a float between 0 and 1. Any int will be converted to a float.
    ## A value under 0 represents a 'halt'.
    ## A value at 1 or bigger represents 100%
    def update_progress(progress):
        barLength = 20 # Modify this to change the length of the progress bar
        status = ""
        if isinstance(progress, int):
            progress = float(progress)
        if not isinstance(progress, float):
            progress = 0
            status = "error: progress var must be float\r\n"
        if progress < 0:
            progress = 0
            status = "Halt...\r\n"
        if progress >= 1:
            progress = 1
            status = "Done...\r\n"
        block = int(round(barLength*progress))
        text = "\rPercent: [{0}] {1}% {2}".format( "="*block + " "*(barLength-block), progress*100, status)
        sys.stdout.write(text)
        sys.stdout.flush()
    

    Looks like

    Percent: [====================] 99.0%

    0 讨论(0)
提交回复
热议问题