How to create a spinning command line cursor?

Nathan picture Nathan · Feb 14, 2011 · Viewed 58.1k times · Source

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

Answer

nos picture nos · Feb 14, 2011

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')