Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my Python script run forever?

Tags:

python

I have a python script (excerpt shown below) that reads a sensor value. Unfortunately, it runs only for 5 - 60 minutes at a time and then suddenly stops. Is there a way I can efficiently make this run forever? Is there any reason why a python script like this couldn't run forever on a Raspberry Pi, or does python automatically limit the duration of a 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()
like image 847
Alligator Avatar asked Sep 27 '26 10:09

Alligator


1 Answers

It appears as though your loop lacks a delay and is constantly appending your "values" array, which will likely cause you to run out of memory in a fairly short period of time. I recommend adding a delay to avoid appending the values array every instant.

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)
like image 167
Cryo Avatar answered Sep 30 '26 02:09

Cryo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!