I want to run a python script periodically with a variable persisted each repetition. How can I do this?
Question: I have a python script which moves a robot based on a bearing. The bearing
calculated is relative to another robot. I want to calculate a corrective
factor based on the magnetic bearing the robot is moving along + the change in
distance from other points in the network. this corrective factor could then
be applied to the bearing calculated relative to another bot to make the
bearing closer to a true magnetic bearing ( I have worked out the maths behind
this but don't think there is a need to go into the details here).

the way my script runs is by calling other scripts and passing values to and
reading them from them. A light piece of pseduo code looks like:

    
    
    find a bearing relative to another bot to the point to be reached
    move towards it along this bearing
    test accuracy of the bearing
    calculate a correction factor
    

I then want to repeat the script and correct the bearing initially calculated
with the correction factor (simple add or subtract x degrees)

How can I persist the variable each time the script repeats so that the
correction factor can be added or subtracted from the next time instead of
having to be recalculated from scratch?


Answer: Store it in a file like that:

    
    
    import json
    json.dump(data, open(filename, 'wb'))
    

and red it next time with

    
    
    f = open(filename)
    data = json.load(f)
    f.close()
    

