0

I have a large Python program running on a Raspberry Pi, and every week or two it will get overloaded and throw an out of memory error. I want to trap those errors and call a shell script "kill-and-relaunch.sh" (code below) that will kill the running Python processes and re-launch the program...so it needs to run the shell command as an entirely separate process. Two questions: (1) what is the best method to call the shell that will survive killing the original Python process; and (2) where would I put the error trapping code in a Python program that is already running in multiple processes...do I need to have the error trapping in each process?

Here is the shell command I want to call:

kill $(ps aux | grep '[p]ython -u home_security.py' | awk '{print $2}')
cd ~/raspsecurity
source ~/.profile
workon py3cv34
nohup python -u home_security.py &

Thank you for any suggestions.

2 Answers2

0

You could fire your shell script in a cronjob and add the error (or all) output in an file (as described here https://stackoverflow.com/a/7526988/7727137).

Thom
  • 157
  • 7
0

Perhaps subprocess might help?

import subprocess

# do something

try:

    # trap the anticipated error zone

except:  # Best if you catch the specific error anticipated instead of catch-all.

    # log the error if you wish
    subprocess.run(my_ps_script)
r.ook
  • 13,466
  • 2
  • 22
  • 39