Pierre
Pierre

Reputation: 422

Show progress bar as well as additional output on the screen

I'm coding a Python command line script that processes files.

I would like to have a progress bar showing the amount of work already done, but I would also like to see some additional output on the screen.

I found this script which helps greatly with the progress bar, but I didn't find how to add additional output.

What I would like is an output such as:

[======              ] 30%
Error: File 'test.png' could not be processed.
Error: File 'yet_another_test.jpg' could not be processed.

With the progress bar being updated as the processing occurs...

Thanks in advance!

Upvotes: 1

Views: 337

Answers (2)

user2963623
user2963623

Reputation: 2295

What you want, cannot be achieved perfectly, since the moment you print something to a new line, '\r' will not return cursor to the previous line. What you can however is output whatever additional info you want at the end of the progress bar, although admittedly it would look weird!

Upvotes: 0

Stephen Lin
Stephen Lin

Reputation: 4912

I don't know if this is what you want. Hope it helps.

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys
import time
import math

# Output example: [=======   ] 75%

# width defines bar width
# percent defines current percentage
def progress(width, percent):
    marks = math.floor(width * (percent / 100.0))
    spaces = math.floor(width - marks)

    loader = '[' + ('=' * int(marks)) + (' ' * int(spaces)) + ']'

    sys.stdout.write("%s %d%%\r" % (loader, percent))
    if percent >= 100:
        sys.stdout.write("\n")
    sys.stdout.flush()

def func():    
    try:
        # you can do your things here
        assert 0, 'hahahah'
    except Exception as e:
        sys.stdout.write(repr(e)+'\r')
        sys.stdout.flush()    


# Simulate doing something...
for i in xrange(100):
    progress(50, (i + 1)) # +1 because xrange is only 99
    if i == 6:
        func()
    time.sleep(0.1) # Slow it down for demo

Upvotes: 1

Related Questions