'Waiting' animation in command prompt (Python)

前端 未结 4 1844
忘了有多久
忘了有多久 2020-12-30 05:11

I have a Python script which takes a long time to run. I\'d quite like to have the command line output to have a little \'waiting\' animation, much like the swirly circle we

相关标签:
4条回答
  • 2020-12-30 05:24

    Python's built-in curses package contains utilities for controlling what is printed to a terminal screen.

    0 讨论(0)
  • 2020-12-30 05:25

    A loading bar useful for if you're installing something.

    animation = [
    "[        ]",
    "[=       ]",
    "[===     ]",
    "[====    ]",
    "[=====   ]",
    "[======  ]",
    "[======= ]",
    "[========]",
    "[ =======]",
    "[  ======]",
    "[   =====]",
    "[    ====]",
    "[     ===]",
    "[      ==]",
    "[       =]",
    "[        ]",
    "[        ]"
    ]
    
    notcomplete = True
    
    i = 0
    
    while notcomplete:
        print(animation[i % len(animation)], end='\r')
        time.sleep(.1)
        i += 1
    

    if you want to make it last a couple seconds do

    if i == 17*10:
        break
    

    after the

    i += 1
    
    0 讨论(0)
  • 2020-12-30 05:40

    Just another pretty variant

    import time
    
    bar = [
        " [=     ]",
        " [ =    ]",
        " [  =   ]",
        " [   =  ]",
        " [    = ]",
        " [     =]",
        " [    = ]",
        " [   =  ]",
        " [  =   ]",
        " [ =    ]",
    ]
    i = 0
    
    while True:
        print(bar[i % len(bar)], end="\r")
        time.sleep(.2)
        i += 1
    
    0 讨论(0)
  • 2020-12-30 05:44

    Use \r and print-without-newline (that is, suffix with a comma):

    animation = "|/-\\"
    idx = 0
    while thing_not_complete():
        print(animation[idx % len(animation)], end="\r")
        idx += 1
        time.sleep(0.1)
    

    For Python 2, use this print syntax:

    print animation[idx % len(animation)] + "\r",
    
    0 讨论(0)
提交回复
热议问题