Python to print out status bar and percentage

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

To implement a status bar like below:

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

20条回答
  •  长情又很酷
    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()
    

提交回复
热议问题