Ali Ali - 6 months ago 11
Python Question

Abort python script after a special function finished running

I have a python script, that has a long runtime.
Sometimes I need to abort it and run it later. It dumps the current results in a pickle file, but while aborting (CTLR + C) at the wrong time that file gets corrupted.

Is there a way to let the script finish that task and abort it afterwards?
I don't know where to look for.

Thank you

Edit: My program looks somewhat like this:

import pickle


for key in keylist:
do_smth(mydict)
with open('myfile.p','w+b') as f:
pickle.dump(mydict,f)


Edit2: Thank you guys, try: ... except: ... works like a charm.
Since I am the only user of the script I won't need the "save" version. However I will definitely look into it (right now I am not familiar with threading).

I also changed my loop, that I will only pickle my file, in case of an exception or after the loop finished.

import pickle

for key in keylist:
try:
do_smth(mydict)
except KeyboardInterrupt:
print("Saving data ...")
with open('myfile.p','w+b') as f:
pickle.dump(mydict,f)

with open('myfile.p','w+b') as f:
pickle.dump(mydict,f)

Answer

Ctrl+C actually throws a special type of exception called KeyboardInterrupt. So, if your way of aborting the script to run it later is sending that exception, you can save your data before exiting. This can be done by wrapping your code in a try-except block and catch the KeyboardInterrupt exception.
An example would look like this:

try:
    # your main code here
except KeyboardInterrupt:
    # do the saving here
    exit(-1)   # exit the program with the return code -1

About the comment: make sure that you send this exception once.
It's because if you send it, the code will go to the saving part, that does not have the exception-catching block. So if you send it multiple times, your data may be saved improperly.