0

There is a code. I want to create a text animation. It prints a line of text then after some delay erases it and prints another. Here is the function that creates a text frame:

    def frame(data):
    clear = '\u001b[0m'

    for letter in data:
        rslt = colours['fg'][letter['color']]
        rslt += letter.get('bg', '')
        rslt += letter['letter']
        rslt += clear
        stdout.write(rslt)

Here is the animator function:

from time import sleep

def animate(data):
    clear = '\u001b[100D'
    #for i in range(len(data)):
    for i in range(5):
        #stdout.write(clear) #1
        ready = change(data, i)
        frame(ready)
        sleep(0.4)
    print()

What am I supposed to get? As I explained above, it should print a line of text, then wait for 0.4 and then on the next iteration cycle erase the previos text, then repeat the stuff.

But what do I get? I get nothing for (I didn't measure exactly, but probably the sum of delays of 0.4) some time and then the text repeated 5 times as it was not cleared, because the line #1 is commented. And when it's not, after again the sum of delays I get the last frame of the text.

You may play with my code at https://repl.it/repls/PunyGlassApplicationserver

  • This may not be the answer you are looking for, but have you considered [asciimatics](https://github.com/peterbrittain/asciimatics)? It's a library nicely designed specifically for these kind of things. – norok2 Jul 27 '19 at 09:33
  • may be it is worth attention. but my code is kinda written for an hour and the forgetten:) I am new to python, so I don't know yet all the possibilities – Юрий Стражнов Jul 27 '19 at 11:53

1 Answers1

0

Call stdout.flush() after writing:

def animate(data):
    clear = '\u001b[100D'
    #for i in range(len(data)):
    for i in range(5):
        #stdout.write(clear) #1
        ready = change(data, i)
        frame(ready)
        stdout.flush()
        sleep(0.4)
fiveelements
  • 3,649
  • 1
  • 17
  • 16