繁体   English   中英

连续的Python脚本,如果结束则重新启动

[英]Continuous Python script and restart if ended

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

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

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

exit(0)

我还尝试用允许脚本运行一分钟并每分钟用cron重新启动脚本的语句替换始终为true的while语句,但这也导致脚本没有结束并且开始了新的过程。

是否有人对我如何使脚本稳定或能够重新启动没有任何想法。 即始终一直运行到无限! :-)

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()

使用linux屏幕运行python脚本,它将一直在后端运行,直到您停止脚本为止。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM