pythoncommand-line-interfaceprogress

How to create a spinning command line cursor?


Is there a way to print a spinning cursor in a terminal using Python?


Solution

  • Something like this, assuming your terminal handles \b

    import sys
    import time
    
    def spinning_cursor():
        while True:
            for cursor in '|/-\\':
                yield cursor
    
    spinner = spinning_cursor()
    for _ in range(50):
        sys.stdout.write(next(spinner))
        sys.stdout.flush()
        time.sleep(0.1)
        sys.stdout.write('\b')