Loading animation in python

2020-02-13 02:14发布

问题:

Im new to python and was wondering how to make a loading animation while my program runs. I need this because I don't want users thinking that the program is caught in a dead loop. I prefer a something like...

Loading...(with the dots disappearing and reappearing one by one)

Thanks!

回答1:

If your output window supports the carriage return character, you can print it to make the cursor return to the beginning of the current line (provided you end your print statement with a comma, so a newline character isn't automatically printed). Then subsequent prints will overwrite what was already printed. You can use this to do very simple one line animation. Example:

import time

print "Starting program."

print "Loading   ",
time.sleep(1) #do some work here...
print "\rLoading.  ",
time.sleep(1) #do some more work here...
print "\rLoading.. ",
time.sleep(1) #do even more work...
print "\rLoading...",
time.sleep(1) #gratuitious amounts of work...
print "\rLoading   ",

... Where time.sleep(1) is a placeholder representing the actual work you want to do.

Result:

Starting program.
Loading

Then, one second later:

Starting program.
Loading.

Then, one second later:

Starting program.
Loading..

Then, one second later:

Starting program.
Loading...

Then, one second later:

Starting program.
Loading

etc.

Compatibility note: in 3.X, print is no longer a statement, and the "end with a comma" trick no longer works. Instead, specify the end parameter:

print("\rLoading...", end="")


回答2:

The most proper way I can think of to do it would be using threading.

You would initiate a thread that starts displaying some indication that the program is doing something and then open a new thread that actually does the work.

When the thread doing the work finished then you can move on with whatever else the program does.

This looks ok when ran in windows command prompt, not sure how linux will like it:

import threading
import time
import os
import queue

q = queue.Queue()

q.put(False)

class counter(object):
    def __init__(self):

        wait_label = "Loading"

        self.stop_flag = q.get()

        while not self.stop_flag:
            try:
                self.stop_flag = q.get_nowait()
            except:
                pass
            os.system('cls') # might need to change this command for linux
            wait_label += "."
            print(wait_label)
            time.sleep(1)

class other(counter):
    def __init__(self):

        time.sleep(15)

        q.put(True)

counter_thread = threading.Thread(None, counter)
counter_thread.start()

other_thread = threading.Thread(None, other)
other_thread.start()