Created
November 12, 2015 07:48
-
-
Save mikkkee/73cf05969a97e806dea6 to your computer and use it in GitHub Desktop.
Spinning cursor and progress bar in console (Python)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is awesome, thank you!