I would use a file to avoid global and separate data and logic a bit.
seed_handler.py
# file that stores the shared seed value seed_val_file = "seed_val.txt" def save_seed(val, filename=seed_val_file): """ saves val. Called once in simulation1.py """ with open(filename, "wb") as f: f.write(str(val)) def load_seed(filename=seed_val_file): """ loads val. Called by all scripts that need the shared seed value """ with open(filename, "rb") as f:
simulation1.py
import random import seed_handler def sim1(): """ creates a new seed and prints a deterministic "random" number """ new_seed = int("DEADBEEF",16)
simulation2.py
import random import seed_handler def sim2(): """ loads the old seed and prints a deterministic "random" number """ old_seed = seed_handler.load_seed() print "Old seed:", old_seed
Output:
user@box :~/$ python simulation1.py New seed: 3735928559 Random: 0.0191336454935 user@box :~/$ python simulation2.py Old seed: 3735928559 Random: 0.0191336454935
ADDITION
I just read in the comments that this is for research. Currently, the execution of the simulation1.py function overwrites the stored initial value; this may be undesirable. You can add one of the following functions:
- save as json and load into the dictionary; this way, nothing will be overwritten, and each initial value can have notes, a time stamp, and a userβs label associated with it.
- just ask the user about yes / no to overwrite the existing value.
source share