How to show animation in Python while function is working?
<p>I have a loading-function:</p>

<pre><code>def animation(loadingtext):
    word = list(loadingtext)
    for i in range(0,len(word)):
        os.system('cls')
        lower=word[i-1].lower()
        word[i-1]=lower

        caps=word[i].upper()    
        word[i]=caps

        wordstr=''.join(word)
        print(wordstr)
        time.sleep(0.3)
</code></pre>

<p>And i want to display that function while some work is done (for example fetcha big SQL-Query).
Or how can I make some other Loading animations? </p>

<p>Thanks in advance, Patrick!</p>

<p>First I would not use <code>system("cls")</code> at all: it clears the screen when it might be interesting to still see what was written. I would just prepend a <code>\r</code> to <code>wordstr</code>.</p>

<p>Then to have <code>animation</code> to do its display while some other work is done, you could just repeatedly call them in a second thread waiting for some event, and set that event when the job is done.</p>

<p>Here is what is could look like:</p>

<pre><code>def animation(loadingtext):
    word = list(loadingtext)
    for i in range(0,len(word)):
        #os.system('cls')
        lower=word[i-1].lower()
        word[i-1]=lower
        caps=word[i].upper()
        word[i]=caps
        wordstr=''.join(word)
        sys.stdout.write('\r' + wordstr)
        time.sleep(0.3)

def start_anim(txt):
    ev = threading.Event()
    def _loop(ev, txt):
        while not ev.is_set():
            animation(txt)
    threading.Thread(target=_loop, args=(ev, txt)).start()
    return ev
</code></pre>

<p>You could then use it that way:</p>

<pre><code>ev = start_anim(loadingtext)
# heavy work - loadingtext is animated on screen
ev.set()   # stop the animation
</code></pre>

python function animation loading