cursor positioning

Danny Milosavljevic danny_milo at nospam.yahoo.com
Mon Jul 11 15:03:23 EDT 2005


Hi,

On Mon, 11 Jul 2005 15:29:41 +0200, Mage wrote:

>          Dear All,
> 
> I am writing a database import script in python and I would like to
> print the percentage of the process to the last line. I would like to
> update the last line at every percent. You know what I mean.
> 
> How can the cursor be positioned to the last line or somewhere else on
> the screen? Curses starts with clearing the whole screen and it is
> overkill. Many modules are on the net but I would like to resolve this
> simply task with native python.
> 
> I tried:
> 
> for something:
>     print chr(8)*20+mystring,
> 
> but it is nasty and didn't work well.
> 
>           Mage

If you only want to support ansi terminals (which is questionable, but
possible), then there are escape codes that are very helpful (searching
for ansi escape codes or something in google should help you find the
remainder):

the general syntax is 

ESC[<parameter><action>

action usually is the first letter in the sequence, hence parameters are
usually numbers (duh :))

ESC is chr(27) (ascii 27, octal \033)

actions are
  H    cursor go home (top left corner usually)
  C    go right <parameter> times
  D    go left  <parameter> times
  A    go up <parameter> times
  B    go down <parameter> times
  K    clear to end of line
  2J   clear screen (yes, to every rule there are exceptions :), note that
this does not make the cursor go home)
  m    set color/highlight/formatting flags

Examples
  ESC[2JESC[H		same as "clear", clear screen, go home
  \rESC[Kprogress %d    probably what you want :)

The downside of this is that determining the size of the screen is pretty
hard to do right.

Process is usually, read TERM environment variable, read /etc/termcap
(deprecated) "co" attribute (columns), "li" attribute (rows). That has
been deprecated because of all those resizeable terminals out there. 

Now its something like outputting some magical stuff to make the terminal
emulator send back the current sizes immediately once, and whenever they
change. 
I'm not totally clear how that works since I'm too lazy to care :)

What you want is probably

prc = 0
for prc in range(100):
        sys.stderr.write("\r\033[KProgress %d%% ... " % prc) 
        sys.stderr.flush()
        time.sleep(0.5)

though :)

Note that this can wreck havoc onscreen if the terminal is smaller than what is
needed to print that horizontally, so technically its not totally clean code.

Hope that helps

cheers,
   Danny

  




More information about the Python-list mailing list