如何让我的Python脚本一直运行?
我有一个Python脚本(下面有一部分代码),它用来读取传感器的数值。可惜的是,它只能运行5到60分钟,然后就会突然停止。有没有什么办法可以让它一直运行下去?是不是有某种原因导致这样的Python脚本在树莓派上不能一直运行,或者说Python会自动限制脚本的运行时间呢?
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()
2 个回答
0
理论上来说,这段代码应该可以一直运行下去,Python并不会自动限制脚本的执行时间。我猜测你可能遇到了readadc
或者pac
这部分的代码卡住了,导致整个脚本无法继续运行,或者在执行过程中出现了错误(如果你从命令行运行脚本的话,应该能看到这些错误)。那么,这个脚本是卡住了,还是直接停止退出了呢?
如果你能用print()
输出一些数据,并且在树莓派上能看到这些数据,你可以加一些简单的调试代码,看看程序卡在哪里。你可能可以通过设置一个超时参数来轻松解决这个问题。另一种方法是把脚本放到一个线程里运行,让主线程充当监视者,如果子线程运行时间太长,就把它们结束掉。
1
看起来你的循环没有设置延迟,导致它一直在往“values”数组里添加数据,这样很快就会耗尽内存。我建议你加一个延迟,这样就不会每一瞬间都往数组里添加数据了。
添加延迟的方法:
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)