Почему не использовать curses? Он работает в Linux, OSX и теперь есть Windows implementation (как сообщается here).
Следующий пример будет надежным на большинстве платформ:
from curses import wrapper
import time
def print_over(scr, s):
scr.clear()
scr.addstr(5, 0, s)
scr.refresh()
def main(scr):
for i in range(10, 110, 10):
print_over(scr,'Progress: %d %%'%i)
time.sleep(1)
wrapper(main)
EDIT:
Вот еще один пример, который не очищает весь экран:
from curses import tparm, tigetstr, setupterm
import time
def tput(cmd, *args):
print (tparm(tigetstr(cmd), *args), end='') # Emulates Unix tput
class window():
def __init__(s, x, y, w, h):
s.x, s.y, s.w, s.h = x, y, w, h # store window coordinates and size
def __enter__(s):
tput('sc') # saves current cursor position
s.clear() # clears the window
return s
def __exit__(s, exc_type, exc_val, exc_tb):
tput('rc') # restores cursor position
def clear(s, fill=' '):
for i in range(s.h):
tput('cup', s.y+i, s.x) # moves cursor to the leftmost column
print (fill*s.w, end='')
def print_over(s, msg, x, y):
tput('cup', s.y+y, s.x+x)
print (msg, end='')
setupterm()
with window(x=5, y=10, w=80, h=5) as w:
for i in range(10, 110, 10):
w.clear()
w.print_over('Progress: %d %%'%i, 5, 2)
time.sleep(1)
А вот другой один, который переписывает только последнюю строку:
from curses import tparm, tigetstr, setupterm
import time
def tput(cmd, *args):
print (tparm(tigetstr(cmd), *args), end='') # Emulates Unix tput
setupterm()
for i in range(10, 110, 10):
tput('el') # clear to end of line
print (' Progress: %d %%'%i, end='\r')
time.sleep(1)
В принципе, принцип всегда заключается в использовании curses
с tput commands, чтобы избежать явных escape-символов.
Обратите внимание, что вам может потребоваться сброс stdout или просто запуск сценария с помощью python -u
.
Он не будет работать в Windows. –
@MarkRansom: Есть что-нибудь, что может заставить что-то подобное работать в Windows? – orome
http://stackoverflow.com/a/517207/4023997 – ZN13