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)