Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

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:

Python
#!/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:

Python
#!/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()

00:00 In the previous lesson, I gave a quick introduction to ANSI escape sequences. In this one, I’m going to be talking about how to use \r in \b to do simple animation, like progress bars.

00:11 You may recall from the first lesson \r and \b as escape characters. \r is carriage return, which returns the cursor to the beginning of the line without changing anything on the line, and \b is backspace—it backs over one character.

00:26 By using these together, you can create little flip-book style animations. Here’s a simple program that shows a busy spinner animation. It starts out by printing the message, 'Everybody look busy ', removes any newlines ('\n')—and don’t forget to flush the buffer, otherwise this won’t get printed to the screen. For the sake of demonstration, it’ll spin three times—hence the in range(3).

00:50 This string is our actual animation. Each character in it will get shown one at a time. When you do an in on a string in Python, it returns letter by letter out of that string, so frame will contain at any given time one of these characters.

01:07 The character gets printed using the backspace ('\b') over any previous character. No separator, no newline ('\n'), and don’t forget to flush the buffer.

01:16 The program then sleeps for 200 milliseconds and then loops back and shows the next frame in our little flip book. Finally, back up one more time and print a space (' ') to wipe out the spinner, and then newline this so that the exit prompt is on the next line.

01:35 Let’s see this in practice. Everybody look busy, the spinner runs, and the prompt returns. The spinner used '\b'. Now I’m going to show you a progress bar that uses '\r'. The main chunk of our program prints out a message and then the progress bar.

01:53 The progress bar is called continually with the ranges from 1 to a 100, and in between it sleeps for 100 milliseconds. The progress routine takes a parameter of percent to say what percent the progress bar is being displayed at, and a width, which is defaulting to 30.

02:11 First off, I calculate how many little hash marks to put inside of the progress bar. I do that by multiplying the width times the percentage being shown, with the double-slash (//) division—which is integer division—so a whole number will always be returned.

02:26 And of course, the blanks are just however wide it is minus the number of hashes that are being shown.

02:33 print() statement starts with a carriage return ('\r'), shows a left bracket ( [ ), prints out the number of hash symbols, prints out the number of blanks (' '), a right bracket ( ] ), and then uses a format string to show the value of the percent. Once again, because this is animation—no separator, no end, and flush the buffer. Let’s run the program.

02:57 This will take a moment, counting up to a hundred.

03:04 All the hashes keep showing up. And there you go—a nice little progress bar. Of course, in the real world, you’d be doing something to actually cause progress to happen rather than just sleeping, but you get the idea.

03:17 There are a lot of libraries available to help you create complicated text interfaces on your terminals. This includes simple things like progress bars, like I just showed you, and far more complicated windowing interfaces, or what’s sometimes referred to as TUIs (“tooeys”), or Text User Interfaces. progressbar2 is a library you can install with pip that has progress bar management inside of it.

03:38 curses and ncurses are terminal control programs that allow you to do complicated things, including creating full-on video games, complete control of your cursor, and how things are placed. Or urwid, which is one of my favorites for doing console interfaces, which is a full windowing system—fairly easy to put together and gives you strong control over things like dropdown and entry fields and all the things you would come to expect with a GUI.

04:02 Automating your tests is important, but it can be challenging to test code that uses print(). In the next lesson, I’ll show you how to get around this.

Become a Member to join the conversation.