简体   繁体   中英

display multi-line python console ascii animation

I'm playing with console animations. I see it's easy to make a single line but I started playing with the idea of animating GIFs as ASCII in the console.

import time

def main():

    counter = 0

    while True:
        with open(ascii_path + 'dog-' + str(counter) + '.txt', 'r', encoding="utf8") as f:

            print('\b', f.read(), sep='', end='', flush=True)

            time.sleep(0.5)

            if counter == len(filenames):
                counter = 0
            else:
                counter += 1

if __name__ == "__main__":
    main()

What ends up happening is it will just print every text file in succession instead of replacing the contents like the following animation does.

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)

Even when I attempt to clear the console after every print, it doesn't seem to do anything.

os.system('cls')

Is there a library that does this?

You can actually solve this without any external library as long as your terminal (emulator) supports ANSI escape sequences . These can be printed to the console as if they are text but instead of printing they can move the cursor, change the colour of the text and even scroll portions of the terminal. Below is a small example that does what you want as long as the printed lines do not cause the terminal to scroll but if you are clearing the console anyway it should work.

import time

nlines = 2
# scroll up to make room for output
print(f"\033[{nlines}S", end="")

# move cursor back up
print(f"\033[{nlines}A", end="")

# save current cursor position
print("\033[s", end="")

for t in range(10):
    # restore saved cursor position
    print("\033[u", end="")
    print(f"Line one @ {t}")
    print(f"Line two @ {t}")
    t += 1
    time.sleep(.5)

Hi the problem with using '\b' is that it only clears a single character.

The following code with system('cls') function works for me on the cmd console of a windows system. If you are on a mac or linux system use system('clear')

I tried with two sample files:

counter = 1
while True:
    with open('myfile{}.txt'.format(counter), 'r', encoding="utf8") as f:
        print(f.read(), sep='', end='', flush=True)
        time.sleep(0.5)
        if counter == 2:
            counter = 1
        else:
            counter += 1
        system('cls')

Content of one file is printed then the screen is cleared and contents of the next file is printed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM