Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exit a while loop only after the current loop has completed in Python?

I’m trying to set up my Python script to allow the user to end the program, however the program needs to finish what it’s doing first. I have the following code set up:

import sys
import keyboard
import time

prepareToStop = 0;
try:
    while prepareToStop == 0:
        #Program code here
        print(prepareToStop)
        time.sleep(0.1)
except KeyboardInterrupt:
    prepareToStop = 1
    print("\nProgram will shut down after current operation is complete.\n")

print("Program shutting down...")
sys.exit()

However, the program still exits the loop as soon as the KeyboardInterrupt is received. I’ve seen advice that this could be fixed by placing the ‘try, except’ inside the while loop, however this causes the program to fail to detect the KeyboardInterrupt at all.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If I understand your problem correctly, maybe threading can help you. Note how end do something appears even after KeyboardInterrupt.

EDIT : I placed t.join() in the try

import sys
import time
import threading

def do_something(prepareToStop):
    print(prepareToStop)
    time.sleep(1)
    print('end do something')

prepareToStop = 0
while prepareToStop == 0:
    t = threading.Thread(target=do_something, args=[prepareToStop])
    try:
        t.start()
        t.join() # wait for the threading task to end
    except KeyboardInterrupt:
        prepareToStop = 1
        print("\nProgram will shut down after current operation is complete.\n")
    print('will not appear for last run')

print("Program shutting down...")
sys.exit()

Example of output :

0
end do something
will not appear for last run
0
^C
Program will shut down after current operation is complete.

will not appear for last run
Program shutting down...

end do something
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading