Python to print out status bar and percentage

后端 未结 20 1090
野的像风
野的像风 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.

提交回复
热议问题