Python exit over last print line

Is there a way in python to print something on the command line above the last line? Or, like what I want to achieve, stay on the last line, that is, do not overwrite it.

The goal is to have the status line / pre-stream displayed on the last line of the command line.

Output Example:

File 1 processed (0.1% Completed) 

Next update:

 File 1 processed File 2 processed (0.2% Completed) 

Next update:

 File 1 processed File 2 processed File 3 processed (0.3% Completed) 
+5
source share
2 answers
 from time import sleep erase = '\x1b[1A\x1b[2K' def download(number): print(erase + "File {} processed".format(number)) def completed(percent): print("({:1.1}% Completed)".format(percent)) for i in range(1,4): download(i) completed(i/10) sleep(1) 

Works on my python 3.4, final output:

 File 1 processed File 2 processed File 3 processed (0.3% Completed) 

If you want to know more about terminal escape codes, try: https://en.wikipedia.org/wiki/ANSI_escape_code

As requested, an example with a space:

 from time import sleep erase = '\x1b[1A\x1b[2K' def download(number): print(erase*2 + "File {} processed".format(number)) def completed(percent): print("\n({:1.1}% Completed)".format(percent)) print("\n(0.0% Completed)") for i in range(1,5): download(i) completed(i/10) sleep(1) 

Final result:

 File 1 processed File 2 processed File 3 processed File 4 processed (0.4% Completed) 
+4
source

Take a look at the \r command. This can do the trick.

 for i in range(2): print '\rFile %s processed' % i print '(0.%s%% Completed)' % i, 

Output:

 File 0 processed File 1 processed (0.1% Completed) 
+1
source

Source: https://habr.com/ru/post/1266652/


All Articles