Skip to content

Instantly share code, notes, and snippets.

@mikkkee
Created November 12, 2015 07:48
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikkkee/73cf05969a97e806dea6 to your computer and use it in GitHub Desktop.
Save mikkkee/73cf05969a97e806dea6 to your computer and use it in GitHub Desktop.
Spinning cursor and progress bar in console (Python)
"""
Create a spinning cursor or progress bar in terminal can be useful
for some scripts.
1. Use '\r' to move cursor back to the line beginning. Or use '\b'
to erase the last character.
2. The standard out of Python is buffered, which means it will
collect some data written to standard out before it actually
writes to the terminal.
The code snippet
for i in range(5):
time.sleep(1)
print i
will wait for 5 seconds before printing '01234' into the
terminal.
Use sys.stdout.flush() to force printing to terminal.
"""
import time
import sys
# Spinning cursor
def spinning_cursor():
while True:
for cursor in '\\|/-':
time.sleep(0.1)
# Use '\r' to move cursor back to line beginning
# Or use '\b' to erase the last character
sys.stdout.write('\r{}'.format(cursor))
# Force Python to write data into terminal.
sys.stdout.flush()
# Progress bar
def progress_bar():
for i in range(100):
time.sleep(0.1)
sys.stdout.write('\r{:02d}: {}'.format(i, '#' * (i / 2)))
sys.stdout.flush()
@z0nk3r
Copy link

z0nk3r commented Feb 16, 2023

For anyone else showing up here from google:

python 3.8+ has new string formatting that has the same functionality as sys without needing to import it:

import time

def spinning_cursor():
  while True:
    for cursor in '\\|/-':
      time.sleep(0.1)
      print(f"\r{cursor}", end="", flush=True)

def progress_bar():
  for i in range(101):
    time.sleep(0.1)
    print(f"\r{i:02d}: {'#'*(i//2)}", end="", flush=True)
    # print(f"\r{i:02d}: [{'#'*(i//2)}{'='*(50-(i//2))}>]", end="", flush=True) #fancier pbar

@jcope11
Copy link

jcope11 commented Mar 28, 2023

Nice spinning cursor. Thank you.

@ChaseStruse
Copy link

This is awesome, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment