16 March 2009

Overwriting lines in terminal output

For weeks I've been wondering, off and on, if there existed an easy way to write information to the terminal output and be able to change it later, to overwrite or overtype or erase or something. I'd seen how curl will update the fraction downloaded and download rate at the end of the line rather than print a new line for every status change; such a feature would be very nice my code, where I could just use one line of output to write information about the time step. I'd seen the "curses" library, but that looked ridiculously complex for what I was asking. (It creates a whole GUI in the terminal rather than allowing simple operations.)

Well, after finally hitting the right keywords in a google search, I came across Python with ANSI escape codes (more ANSI escape sequences here). This is just what I want. All you have to do is to send the '\r' carriage return sequence to move to the beginning of the line, and then another ANSI sequence can erase the line. That behavior is actually just what I would expect based on the descriptions of the escape sequences: '\n', the "new line" character, should create a new line; '\r', which is called the 'carriage return', actually *does* in this contact emulate the behavior of a typewriter carriage returning to the rightmost position. Mostly due to the cross-platform confusion of the "end-of-line" character business, I'd never really thought this was the way it would work. The long and short of it, in a few lines of python code:

from time import sleep
from sys import stdout
for i in range(10):
stdout.write('Time step %03d/%03d ' % (i+1, 10))

The '\r\x1b[K' moves the cursor to the beginning of the line the following ANSI escape sequence clears the line completely. The next line actually writes the code. The trailing spaces are in case some sort of output gets print during the time step: it will go at the end of the line, and assuming it has a newline of its own, the time step at which the output occurs will be preserved on the screen, and the next line will have the actual updating time step information.


Post a Comment