简体   繁体   中英

How to restart the python scrypts regardless of the reasons they've existed or crashed?

Say I have this sh script to monitor my python script and restart it if it crashes:

until myserver; do
    echo "Server 'myserver' crashed with exit code $?.  Respawning.." >&2
    sleep 1
done

While it might work well for a python script which is supposed to do some work and exit , it won't for my case because I need my python script s (a few ones, not only one) to always work 24/7 in background. And if one of them ever exists that means it's crashed and should be restarted.

How should I handle my case?

This can be accomplished with crontab .
Run crontab -e , which will bring up a text editor.
Add a new line to that file for each script,

*/5 * * * * pgrep -f yourPythonScript1.py || nohup python /fullpathtoyourfile/yourPythonScript1.py

Save that file and exit the editor.

This will make a new crontab which runs every 5 minutes and launches each script unless it is already running. (Feel free to edit the frequency to what you need)

The command shown runs pgrep (basically, a find a process running with a given string name)

The -f searches the entire command used to run the process- you'll want this because you're running multiple python scripts)

|| means if the previous command fails, do what follows. So the pgrep will fail when your specific script isn't running and it will be relaunched.

If you have root on the system.

If you have a distro with systemd.

then...

You can use systemd to restart a process as soon as it ends using "Restart=always". For example:

[Unit]
Description=My cool service
After=network.target

[Service]
ExecStart=/usr/local/sbin/myservice
User=<myuser>
Group=<mygroup>
Restart=always

[Install]
WantedBy=multi-user.target

Use supervisord to manage your scripts. It provides you with restarting utilities, logging and remote monitoring. Is not hard to setup.

http://supervisord.org/

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