Bash or Python, When print characters to terminal, how to CHANGE a character at a FIXED position?
bash, python
Solution
I'm going to answer in Python, since it's easier.
You can print a backspace to the terminal to move the cursor to the left, and then write another character to overwrite the current position. You can also use a carriage return to go to the beginning of the line.
import time
import sys
for x in range(101):
sys.stdout.write('\r%d%%' % x)
sys.stdout.flush()
time.sleep(0.2)
sys.stdout.write('\n')
Using a carriage return and rewriting the whole line is the easiest, since you don't have to be careful about how many backspaces to print.
Note that if the new line is shorter than the old line, the old line will still show through.
import sys
sys.stdout.write('this is a very long line')
sys.stdout.write('\rshort line')
sys.stdout.write('\n')
Output:
short linevery long line
A typical solution is to write spaces over the long line.
Problem
The thing I want to know here should be really 'basic', but it is a question in my mind for long time and no idea where the trick is. Let's say in a time-consuming program(either `bash` or `Python`), I have to print out the percentage of the progress when it's running, and basically I want to print `1%`, and after a certain time, I print `2%`, etc.. I want `'2%'` to be displayed exactly at the same position where `'1%'` was displayed, rather than they're like "1% 2%" or whatever. You know `wget`, what I want is exactly what wget does, to show the progress of the downloading progress. Do I need to clear the previously printed character, but how? How does it work basically... Thanks,