在一个项目中需要获取随机数,谁知道遇到点问题:随机数不随机。所以我写了个简单原型。看下到底是啥问题。
import os,random,sys,time while True: father = os.fork() if father: time.sleep(2) rd = 7 else: #random.seed() rd = random.choice([2,3,4,5]) print rd time.sleep(2) sys.exit(0)
代码基本就这样。谁知道在子进程里面打印的 random 不起作用。每次随机数都是一样的。
测试发现。是 while 出现问题,因为while 一直循环,而随机种子,是在第一次 import random 的时候就已经种下了。所以导致随机数一直都不会变化~~~ 汗。幼稚问题导致浪费很多时间
看random.seed手册解释:
If x is omitted or None, current system time is used; current system time is also used to initialize the generator when the module is first imported.
明白了。最后用 random.seed() 来改变随机种子。。