Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Animation

By using the \r and \b escape sequences to control the position of the cursor, you can create flip-book style animations with your text. Here’s how to make a spinner to indicate busy status:

#!/usr/bin/env python
from time import sleep

# Show the spinning animation 3 times
print('Everybody look busy  ', end='', flush=True)
for x in range(3):
    for frame in r'-\|/-\|/':
        # Back up one character then print our next frame in the animation
        print('\b', frame, sep='', end='', flush=True)
        sleep(0.2)

# Back up one character, print a space to erase the spinner, then a newline
# so that the prompt after the program exits isn't on the same line as our
# message
print('\b ')

Here’s how you could make a progress bar:

#!/usr/bin/env python
from time import sleep

def progress(percent=0, width=30):
    # The number of hashes to show is based on the percent passed in. The
    # number of blanks is whatever space is left after.
    hashes = width * percent // 100
    blanks = width - hashes

    print('\r[', hashes*'#', blanks*' ', ']', f' {percent:.0f}%', sep='',
        end='', flush=True)

print('This will take a moment')
for i in range(101):
    progress(i)
    sleep(0.1)

# Newline so command prompt isn't on the same line
print()

Comments & Discussion

Become a Member to join the conversation.