My python code needs to save the state of one object while exiting, so that the run can be resumed later on using this object. I am doing this using pickle. Below is the pickle part of my code:
#At the begining of the file
pickle_file = '.state_pickle.obj'
#if pickle file is present load object, else create new
if os.path.exists(pickle_file):
with open(pickle_file, 'r') as fh:
state = pickle.load(fh)
else:
state = NewState() #NewState is a class
....
....
#At the end of the file
with open(pickle_file, 'w') as fh:
pickle.dump(state, fh)
# When -stop option is given, then the session is stopped
# The pickle file is deleted at that time
if args.stop:
if os.path.exists(pickle_file):
os.remove(pickle_file)
...
This works fine for me. However, my problem occurs when multiple sessions are opened from the same directory. The pickle_file ('.state_pickle.obj')
file is getting overwritten causing erroneous results. Is there a way to save the obj to a unique filename so that the file can be read when the session is resumed. Also, i need to get the state
object even before parsing the args. So, I cannot pass the filename through args.
Is there any other clean solution for this problem?