我有一个具有不同主文件的项目(用于不同的模拟)。
当我运行一个主文件时,它应该将种子设置为random(和numpy.random),并且项目中的所有模块都应使用该种子。
我找不到执行此操作的好方法。我有一个文件globals.py与此:
import random
myRandom=None
def initSeed(seed):
global myRandom
myRandom =random.Random(seed)
然后从主要我做:
if __name__ == "__main__":
seed=10
globals.initSeed(seed)
...
然后在主要调用的模块中,执行以下操作:
from globals import myRandom
但是myRandom在模块中的值为None(即使我在main中进行了修改!)。为什么,以及如何解决?有更好的方法吗?
最佳答案
我将使用一个文件来避免global
并稍微分离数据和逻辑。
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:
# change datatype accordingly (numpy.random.random() returns a float)
return int(f.read())
Simulation1.py
import random
import seed_handler
def sim1():
""" creates a new seed and prints a deterministic "random" number """
new_seed = int("DEADBEEF",16) # Replace with numpy.random.random() or whatever
print "New seed:", new_seed
# do the actual seeding of the pseudo-random number generator
random.seed(new_seed)
# the result
print "Random: ", random.random()
# save the seed value so other scripts can use it
seed_handler.save_seed(new_seed)
if __name__ == "__main__":
sim1()
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
# do the actual seeding of the pseudo-random number generator
random.seed(old_seed)
# the result
print "Random: ", random.random()
if __name__ == "__main__":
sim2()
输出:
user@box:~/$ python simulation1.py
New seed: 3735928559
Random: 0.0191336454935
user@box:~/$ python simulation2.py
Old seed: 3735928559
Random: 0.0191336454935
附录
我只是在评论中读到这是为了研究。目前,执行Simulation1.py会覆盖存储的种子值;这可能不是理想的。一个可以添加以下功能之一:
将会被覆盖,并且每个种子值都可以包含注释,时间戳和
与用户相关联的用户生成的标签。
现有值(value)。