简体   繁体   中英

Shell-Script to control if Python-Script is still running (not frozen)

i wrote a pythonscript which makes every minute a Snapshot from an RTSP-Stream. It works well, but after 24-30hours, it freezes.

So i wrote a Shell-Script to check if the number of pictures in the defined folder grow. But again, i use sleep. I guess thats not ideal, but i have no clue how to make it with crontab.

Does anybody have a better way to control my python script. Next week i have holidays, i need a way that my python-script won't freeze for a weej. Or if it freezes, that my Shellscript should kill and restart it.

watcher.sh

#!/bin/bash

cd /home/pi/Pictures/TimeLapse
clear
/usr/bin/python3 /home/pi/mu_code/RTSPCapture/captureIt.py > /dev/null 2>&1


while true
do
    before=$(ls -l | wc -l)
    sleep  60
    after=$(ls -l | wc -l)

    echo "Before: $before"
    echo "After : $after"

    if (("$before" < "$after"))
    then
        echo 'Ok'
    else
        echo 'Panic'
        kill -9 $(ps -aux | grep "captureIt.py" | grep -v grep | awk '{print $2}')
        /usr/bin/python3  /home/pi/mu_code/RTSPCapture/captureIt.py  > /dev/null 2>&1
    fi
done

captureIt.py

from timeit import default_timer as timer
import time, os, re, vlc


def waitXsec(second, executionTime, shiftTime):
    time.sleep(second - (executionTime + shiftTime))


def getPicture(imgDir):
    newName = ''
    for entry in os.scandir(imgDir):
        if entry.is_file():
            newName = entry.name
    output = re.search(r'(\d{5})\.\w*', str(newName))
    if output.group(1) is not None:
        val = int(output.group(1))
    else:
        val = 0
    return val + 1


def captureIt():
    shift = 0.0015
    interval = 60
    imgNr = getPicture('/home/pi/Pictures/TimeLapse')
    stream = 'rtsp://192.168.1.118/live/ch00_1'
    
    os.environ['VLC_VERBOSE'] = str('-1')
    player = vlc.MediaPlayer(stream)
    player.play()
    time.sleep(10)
    
    while True:
        start = timer()
        player.video_take_snapshot(0, '/home/pi/Pictures/TimeLapse/' + str(imgNr).zfill(5) + '.jpg', 0, 0)
        imgNr += 1
        end = timer()
        waitXsec(interval, (end - start), shift)


def main():
    captureIt()


if __name__ == '__main__':
    main()

You can flip the problem a bit and instead of creating a python script with infinite loop you create a cronjob that runs every minute and takes a snapshot. This way you will not have a long running process that could hang. First update your program to take only one snapshot and then run

crontab -e

In the opened editor just add:

* * * * * python /path/to/your/script.py

And crontab will run your script each minute which takes exactly one snapshot and then dies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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