9

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:

File 1 processed
(0.1% Completed)

Next refresh:

File 1 processed
File 2 processed
(0.2% Completed)

Next refresh:

File 1 processed
File 2 processed
File 3 processed
(0.3% Completed)
martineau
  • 119,623
  • 25
  • 170
  • 301
PyCV
  • 315
  • 2
  • 11

2 Answers2

9
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 in my python 3.4, final output is:

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

If you want read more about terminal escape codes see: Wikipedia's ANSI escape codes article.

As requested, 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)

The final output is:

File 1 processed
File 2 processed
File 3 processed
File 4 processed

(0.4% Completed)
martineau
  • 119,623
  • 25
  • 170
  • 301
mucka
  • 1,286
  • 3
  • 20
  • 36
  • And what if I wanted to leave a blank line in between the block of files processed and the percentage? I think that would be quite tricky – PyCV Apr 12 '17 at 16:20
  • If I understand correctly, not at all, I have added example to an answer. – mucka Apr 12 '17 at 16:29
2

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

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

Output is:

File 0 processed
File 1 processed
(0.1% Completed)
Nuageux
  • 1,668
  • 1
  • 17
  • 29
  • This works but just for this specific case. Image I've got several outputs from different processes (multiprocessing module) and I want to keep a track of percentage advanced. – PyCV Apr 12 '17 at 15:46
  • @PyCV If you have multiple processes and you want to coordinate display, they should all send their output to one place to do it. If you were doing a multiprocessing pool, `imap_unordered` would be a good way. – tdelaney Apr 12 '17 at 16:07