简体   繁体   English

无论它们存在或崩溃的原因,如何重启python scrypt?

[英]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: 说我有这个sh脚本来监视我的python脚本,并在崩溃时重新启动它:

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. 虽然它可能会为这是应该做一些工作并退出 Python脚本工作的很好,它不会对我的情况,因为我需要我的Python脚本S(少数的,而不是只有一个)在后台总是全天候工作 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 . 这可以使用crontab完成。
Run crontab -e , which will bring up a text editor. 运行crontab -e ,它将打开一个文本编辑器。
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. 这将创建一个新的crontab,该crontab每5分钟运行一次,并启动每个脚本,除非该脚本已在运行。 (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) 显示的命令运行pgrep (基本上是查找以给定的字符串名称运行的进程)

The -f searches the entire command used to run the process- you'll want this because you're running multiple python scripts) -f搜索用于运行进程的整个命令-您将要执行此操作,因为您正在运行多个python脚本)

|| 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. 因此,当您的特定脚本未运行时,pgrep将失败,并将重新启动。

If you have root on the system. 如果您在系统上具有root用户。

If you have a distro with systemd. 如果您有systemd发行版。

then... 然后...

You can use systemd to restart a process as soon as it ends using "Restart=always". 您可以使用systemd使用“ 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/ http://supervisord.org/

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

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