Python to print out status bar and percentage

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

To implement a status bar like below:

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

20条回答
  •  心在旅途
    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  here
    

提交回复
热议问题