Python to print out status bar and percentage

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

To implement a status bar like below:

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

20条回答
  •  再見小時候
    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("")
    

提交回复
热议问题