Ajwad Ibrahim
Ajwad Ibrahim

Reputation: 127

Python: simple progress bar on subprocess call

i have a simple write to file code, (one.py)

one.py

from time import sleep
f = open("test.txt","w") #opens file with name of "test.txt"
sleep(1)
f.write("I am a test file.")
sleep (2)
f.write("Maybe someday, he will promote me to a real file.")
sleep (1)
f.write("Man, I long to be a real file")
sleep (1)
f.write("and hang out with all my new real file friends.")
f.close()

subpro.py

import subprocess

def oneCall():
    subprocess.call(['python','one.py'])



if __name__ == '__main__':
    print "Writing Data"
    oneCall()

when i run subpro.py, the indicator will show like it hang, is there any way i can change it in to progress bar? so that the user will know that there are actually progress in the background?

Upvotes: 1

Views: 8335

Answers (2)

Ajwad Ibrahim
Ajwad Ibrahim

Reputation: 127

hi below are my solution. but unfortunately the loading only says done after one.py and two.py is completed.

how to make it

done (one.py)

done (two.py)

import subprocess
import time, sys
import threading
def oneCall():
    subprocess.call(['python','one.py'])

def twoCall():
    subprocess.call(['python','two.py'])


class progress_bar_loading(threading.Thread):

    def run(self):
            global stop
            global kill
            print 'Loading....  ',
            sys.stdout.flush()
            i = 0
            while stop != True:
                    if (i%4) == 0: 
                        sys.stdout.write('\b/')
                    elif (i%4) == 1: 
                        sys.stdout.write('\b-')
                    elif (i%4) == 2: 
                        sys.stdout.write('\b\\')
                    elif (i%4) == 3: 
                        sys.stdout.write('\b|')

                    sys.stdout.flush()
                    time.sleep(0.2)
                    i+=1

            if kill == True: 
                print '\b\b\b\b ABORT!',
            else: 
                print '\b\b\b done!',


kill = False      
stop = False
p = progress_bar_loading()
p.start()

try:
    #anything you want to run.
    oneCall()
    twoCall()
    time.sleep(1)
    stop = True
except KeyboardInterrupt or EOFError:
         kill = True
         stop = True

Upvotes: 1

adrianus
adrianus

Reputation: 3199

There already exist Python libraries which do exactly that like progress or progressbar.

You can also implement it yourself, see this SO post.

Basically the idea is to write and flush the command line, so that a progress bar will appear to be moving.

Processing |###########                     | 30%

Upvotes: 0

Related Questions