连续Python脚本并在结束时重启

时间:2015-12-04 18:10:45

标签: python cron arduino raspberry-pi

我正在创建一个脚本,通过Arduino上的i2c读取433 MHz接收器的输出到Raspberry Pi。我试图从rc.local运行启动它,但似乎在几天之后脚本结束/停止/中断/暂停/被杀死(?)。

我试图从cron运行以下脚本来确定是否运行,如果已停止则启动Python脚本。但它似乎没有检测到正在运行的脚本并且每次运行时都会启动一个新脚本,因此最终导致系统崩溃。

#!/bin/bash
until <path to Python script>; do
    sleep 1
done

exit(0)

我还尝试用一个语句替换always true while语句,该语句允许脚本运行一分钟并且每分钟用cron重新启动脚本,但这也导致脚本没有结束并且新进程是启动。

有没有人知道如何让脚本稳定或能够重启。即一直运行到无限! : - )

Python脚本:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#Run in correct folder
import os
os.system("<path to script-folder>")

import sys

import MySQLdb as mdb

from smbus import SMBus
import RPi.GPIO as GPIO

import datetime
import time

addr = 0x10
intPin = 4

bus = SMBus(1)

def readData():

    val = bus.read_byte(addr)
    raw = val << 24

    val = bus.read_byte(addr)
    raw = raw | (val << 16)

    val = bus.read_byte(addr)
    raw = raw | (val << 8)

    val = bus.read_byte(addr)
    raw = raw | val

    # Tidstämpel
    ts = time.time()
    date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

    try:
        con = mdb.connect('<server>', '<User>', '<password>', '<DB>')
        con.autocommit(True)

        cur = con.cursor()

        cur.execute("INSERT INTO <DB statement>") # Data is stored as integers

    except mdb.Error, e:
        errorLog = open('<path to log>', 'a')
        errorlog.write("Error %d: %s" % (e.args[0],e.args[1]) + "\n")
        errorlog.close()
        sys.exit(1)

    finally:  
        if con: 
            cur.close()  
            con.close()

while True:
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(intPin,GPIO.IN)

    GPIO.wait_for_edge(intPin, GPIO.RISING)
    readData()

2 个答案:

答案 0 :(得分:1)

使用linux屏幕运行python脚本,它将始终在后端运行,直到你停止脚本。

http://www.tecmint.com/screen-command-examples-to-manage-linux-terminals/

答案 1 :(得分:0)

考虑使用daemontools。它很小,将确保您的代码永远运行。

相关问题