Search code examples
pythonprogress-barpython-3.6

How do I get my progress bar to iterate while a script is being executed?


I created a ui that runs a python script on a button click. I included a progress bar to confirm when the script has completed. I'm not sure I have the code correct because when I click the button to execute the script, the progress bar instantly shows 100%. However, the script that's executing the code is still running in the background and completes a few seconds later.

I setup the ui using qt designer. I'm running python 3.6 Below is a snippet of the progress bar code:

def progress(self):
        loop_count = 100
        self.progressBar.setValue(loop_count)
        
        while True:
            #the script that's executing based o the button click
            with open("Python-Test1.py") as f:
                 exec(f.read())
                 loop_count += 1
                 if loop_count >= 100:
                     break
                 time.sleep(1)

I've tried changing the time.sleep setting from 1 to 0.1, 0.00001. I've tried changing the code for the progress bar to the following:

def progress(self):
     count = 100
       for i in range(100):
             count += 1
             self.progressBar.setValue(count)
             #the script that's executing based o the button click
             subprocess.run(['python', 'Python-Test1.py'])
             time.sleep(0.1) 
             with open("Python-Test1.py") as f:
                 exec(f.read())

Solution

  • Why not try another module, like tqdm:

    pip install tqdm
    

    It is something really direct, like:

    from time import sleep
    from tqdm import tqdm
    for i in tqdm(range(10)):
        sleep(3)