Jun-07-2018, 11:05 PM
There are many ways... each one with it's own problems.
To create something that looks like a dialog the best option is to use curses although it is a full library that can be hard to learn.
If you want something really easy (just move the cursor and rewrite a char, maybe some colours), you might go with the ANSI escape codes but take into account that not all of them work in all the terminals (i.e. windows) and that is really easy to finish with a terminal in funny colours and writing garbage (typing "reset" and hitting enter usually fix it)
Here I have done a small example that writes an spinning character until you press Control-C:
To create something that looks like a dialog the best option is to use curses although it is a full library that can be hard to learn.
If you want something really easy (just move the cursor and rewrite a char, maybe some colours), you might go with the ANSI escape codes but take into account that not all of them work in all the terminals (i.e. windows) and that is really easy to finish with a terminal in funny colours and writing garbage (typing "reset" and hitting enter usually fix it)
Here I have done a small example that writes an spinning character until you press Control-C:
#!/usr/bin/env python3 import time spin = "\-//|" print("Working...[ ]", end='') n = 0 while True: try: c = spin[n] n = (n + 1) % len(spin) # Move the cursor 2 position back and print the c # \033 is the Escape sequence print(f"\033[2D{c}]", end='', flush=True) time.sleep(0.2) except KeyboardInterrupt: break print("\nDone!")The main tricks are:
- Use the end='' to avoid print from adding a new line each time
- Use '\033' to write the ESC char. You can use also '\u001b'
- Force print to flush the stdout buffer or otherwise you might not see anything as it is waiting for a newline or to fill the buffer