Sunday, March 29, 2009

BASH & PYTHON: escape sequence for printing output in the same line

The escape sequence for printing in the same line is '\r' in BASH and \033[A in python.
Include that in any code in BASH shell X11 environment to print in the same line instead of jumping to the next line.

For example, the bash code

for ((i=1;i<10;i++))
do
echo -e "i = " $i
done


prints output as:
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9


But the same code with the escape sequence '\r'

for ((i=1;i<10;i++))
do
echo -en "i = \r" $i
# (or) printf "i= %d \r" $i
sleep 1s
done


prints the output in a single line as:

i = 1

and finally the line goes off.

This can be very useful when following the progress of a code.
I haven't tried it in C, but it might work in C and C++ as well.


In python the following works:

#!/usr/bin/python

import time

for i in range(0,10):
print "i= %d \033[A" %i
time.sleep(1)

No comments: