dimanche 25 octobre 2015

Generation of random numbers and the use of random.seed()

I have a script, which should generate a random number, which represents a sensor temperature between 25 and 28°C inclusive, and perform a POST request with some xml in the body. The code is structured like this:

def randomTemperature():
    random.seed()
    return str(random.randint(25,28))

create_DATA_contentInstance_xml_body = '''<obj>
                                         <str name="appId" val="''' +        new_senzor_name + '''"/>
                                         <str name="category" val="temperature "/>
                                         <int name="data" val="''' + randomTemperature() + '''"/>
                                         <int name="unit" val="celsius"/>
                                    </obj>'''

create_DATA_contentInstance = urllib2.Request(url=create_DATA_contentInstance_url , 
                                  data=create_DATA_contentInstance_xml_body, 
                                  headers={'Authorization': 'Basic abcaW46YabcaW4='})   

def createDATAcontentInstance():
    urllib2.urlopen(create_DATA_contentInstance)                
    print "\n=== Created a DATA contentInstance ==="

def createSensorAndDataInstances():
    while True:
        #generate a random delay
        randomDelay = random.randint(1,5)
        time.sleep(randomDelay)
        createDATAcontentInstance()

createSensorAndDataInstances()

If I run createSensorAndDataInstances(), the same simulated temperature is always returned and posted.

My current understanding is that the random.seed() method uses the system's current time as the method's parameter and therefore the method should return a random number, which it does, if I run the following code, which is a stripped version of my script code:

import random
import time

def randomTemperature():
    random.seed()
    return str(random.randint(25,28))

def createSensorAndDataInstances():
    while True:
        #generate a random delay
        randomDelay = random.randint(1,5)
        time.sleep(randomDelay)
        print randomTemperature()

createSensorAndDataInstances()

Does anybody know why it keeps returning the same number in the first case?




Aucun commentaire:

Enregistrer un commentaire