Loading animation in python

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

Loading ... (with dots disappearing and reappearing)

Thank!

+3


source to share


2 answers


If your output window supports a carriage return character, you can print it to return the cursor to the beginning of the current line (assuming you end the statement with a print

comma, so the newline character will not be automatically printed). Subsequent prints will then overwrite what has already been printed. You can use this to make a 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, after a second:



Starting program.
Loading.

      

Then, after a second:



Starting program.
Loading..

      

Then, after a second:



Starting program.
Loading...

      

Then, after a second:



Starting program.
Loading

      

and etc.

Compatibility note: in 3.X, it is print

no longer an instruction, and the end-semicolon trick no longer works. Specify the parameter instead end

:

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

      

+3


source


The most correct way I can think of is using streams.

You initiate a thread that starts to display some indication that the program is doing something, and then opens a new thread that actually does the job.

When the thread doing the work is finished, you can move on, no matter what the program is doing.



This looks fine when run from the Windows command line, but 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()

      

enter image description here

0


source







All Articles