[英]How can I make my Python script run forever?
我有一個python腳本(下面的摘錄),它讀取傳感器值。 不幸的是,它一次只運行5-60分鍾,然后突然停止。 有沒有辦法可以有效地讓這個永遠運行? 有沒有什么理由為什么像這樣的python腳本無法在Raspberry Pi上永遠運行,或者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()
看起來好像你的循環沒有延遲並且不斷附加你的“值”數組,這可能會導致你在相當短的時間內耗盡內存。 我建議添加一個延遲,以避免每一瞬間附加值數組。
添加延遲:
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)
理論上,這應該永遠運行,Python不會自動限制腳本執行。 我猜你在readadc
或pac
feed掛起並鎖定腳本或執行中的異常時遇到了問題(但是你應該看到,如果從命令行執行腳本)。 腳本是掛起還是停止並退出?
如果你可以使用print()
輸出一些數據並在Pi上看到它,你可以添加一些簡單的調試行來查看它掛起的位置 - 你可能會或者可能無法使用超時參數輕松修復它。 另一種方法是將腳本線程化並將循環體作為線程運行,主線程充當監視程序,如果它們花費太長時間來處理它們,則終止處理線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.