Is there a way in python to print something in the command line above the last line printed? Or, similarly to what I want to achieve, remain the last line intact, that is, not overwrite it.
The goal of this is to let the last line in the command line a status/precentage bar.
Output example:
JavaScript
x
3
1
File 1 processed
2
(0.1% Completed)
3
Next refresh:
JavaScript
1
4
1
File 1 processed
2
File 2 processed
3
(0.2% Completed)
4
Next refresh:
JavaScript
1
5
1
File 1 processed
2
File 2 processed
3
File 3 processed
4
(0.3% Completed)
5
Advertisement
Answer
JavaScript
1
14
14
1
from time import sleep
2
erase = 'x1b[1Ax1b[2K'
3
4
def download(number):
5
print(erase + "File {} processed".format(number))
6
7
def completed(percent):
8
print("({:1.1}% Completed)".format(percent))
9
10
for i in range(1,4):
11
download(i)
12
completed(i/10)
13
sleep(1)
14
Works in my python 3.4, final output is:
JavaScript
1
5
1
File 1 processed
2
File 2 processed
3
File 3 processed
4
(0.3% Completed)
5
If you want read more about terminal escape codes see: Wikipedia’s ANSI escape codes article.
As requested, example with a space:
JavaScript
1
15
15
1
from time import sleep
2
erase = 'x1b[1Ax1b[2K'
3
4
def download(number):
5
print(erase*2 + "File {} processed".format(number))
6
7
def completed(percent):
8
print("n({:1.1}% Completed)".format(percent))
9
10
print("n(0.0% Completed)")
11
for i in range(1,5):
12
download(i)
13
completed(i/10)
14
sleep(1)
15
The final output is:
JavaScript
1
7
1
File 1 processed
2
File 2 processed
3
File 3 processed
4
File 4 processed
5
6
(0.4% Completed)
7