The simplest way, if you only ever need to update a single line (for instance, creating a progress bar), is to use '
'
(carriage return) and sys.stdout
:
import sys
import time
for i in range(10):
sys.stdout.write("
{0}>".format("="*i))
sys.stdout.flush()
time.sleep(0.5)
If you need a proper console UI that support moving the pointer etc., use the curses
module from the standard library:
import time
import curses
def pbar(window):
for i in range(10):
window.addstr(10, 10, "[" + ("=" * i) + ">" + (" " * (10 - i )) + "]")
window.refresh()
time.sleep(0.5)
curses.wrapper(pbar)
It's highly advisable to use the curses.wrapper
function to call your main function, it will take care of cleaning up the terminal in case of an error, so it won't be in an unusable state afterwards.
If you create a more complex UI, you can create multiple windows for different parts of the screen, text input boxes and mouse support.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…