How can I run a Python script forever?

I have a python script (excerpt shown below) that reads in a sensor value. Unfortunately, it only runs for 5-60 minutes at a time and then suddenly stops. Is there a way that I can effectively make this run forever? Is there a reason why a python script like this cannot run forever on a Raspberry Pi, or does python automatically limit the duration of the script?

 while True:
    current_reading = readadc(current_sensor, SPICLK, SPIMOSI, SPIMISO, SPICS)
    current_sensed = (1000.0 * (0.0252 * (current_reading - 492.0))) - correction_factor

    values.append(current_sensed)
    if len(values) > 40:
           values.pop(0)

    if reading_number > 500:
           reading_number = 0

    reading_number = reading_number + 1

    if ( reading_number == 500 ):
           actual_current = round((sum(values)/len(values)), 1)

           # open up a cosm feed
           pac = eeml.datastream.Cosm(API_URL, API_KEY)

           #send data
           pac.update([eeml.Data(0, actual_current)])

           # send data to cosm
           pac.put()

      

+3


source to share


2 answers


Your loop seems to be lacking in latency and is continually adding your array of values, which will most likely result in out of memory in a fairly short period of time. I recommend adding a delay to avoid adding an array of values ​​every moment.

Adding a delay:



import time
while True:
    current_reading = readadc(current_sensor, SPICLK, SPIMOSI, SPIMISO, SPICS)
    current_sensed = (1000.0 * (0.0252 * (current_reading - 492.0))) - correction_factor

    values.append(current_sensed)
    if len(values) > 40:
           values.pop(0)

    if reading_number > 500:
           reading_number = 0

    reading_number = reading_number + 1

    if ( reading_number == 500 ):
           actual_current = round((sum(values)/len(values)), 1)

           # open up a cosm feed
           pac = eeml.datastream.Cosm(API_URL, API_KEY)

           #send data
           pac.update([eeml.Data(0, actual_current)])

           # send data to cosm
           pac.put()
    time.sleep(1)

      

+1


source


This should, in theory, run forever, and Python does not limit the script to be executed automatically. I am assuming that you are facing a root feed readadc

or pac

blocking issue with the script up or with an exception in execution (but you should see that when you execute the script command from the command line). Does the script come up or does it stop and exit?



If you can dump some data with print()

and see it on the Pi, you can just add some simple debug lines to see where they hang - you may or may not easily fix it with a timeout argument.An alternative would also be to stream script and run the body of the loop as a thread with the main thread acting as a watchdog and killing the processing threads if they take too long to do their job.

0


source







All Articles