简体   繁体   English

如果停止,如何在远程服务器上重新启动python脚本?

[英]How do I restart a python script on a remote server if it stops?

I have a python script running on a remote server which I start using nohup python myscript.py & . 我有一个在远程服务器上运行的python脚本,该服务器开始使用nohup python myscript.py & I want to restart the script if it stops. 如果脚本停止,我想重新启动它。 I checked this answer but I am not sure if this starts the script. 我检查了这个答案,但不确定是否启动脚本。 I believe it checks if the script is stopped and starts it if the script is stopped. 我相信它会检查脚本是否停止并在脚本停止时启动它。 Also, it requires the pid of the script which would be different every time I restart the script. 另外,它需要脚本的pid ,每次重新启动脚本时, pid都会不同。

I also checked this answer but I'm not sure if the nohup command can be given the until.. do loop. 我也检查了这个答案,但是我不确定nohup命令是否可以使用until.. do循环。 Also wouldn't it just restart my script after every 1 second? 难道不是每隔1秒就重新启动一次脚本吗? Can anyone specify how do I write a script to restart the script in case it stops? 谁能指定我该如何编写脚本以在脚本停止的情况下重新启动该脚本?

instead of writing your own script you can use the very mature, battle tested, supervisord to daemonize any script for you. 无需编写自己的脚本,您可以使用非常成熟,经过战斗测试, 监督的守护程序为您守护任何脚本。

in addition to automatically restarting there is lots of other functionality it provides, including logging out of the box, it is very widely used to daemonize python scripts 除了自动重启外,它还提供了许多其他功能,包括即开即用的注销功能,它非常广泛地用于守护python脚本

If you want your own solution, just use a bash script: 如果您想要自己的解决方案,只需使用bash脚本即可:

#!/bin/bash
while :
do
    python myscript.py
    echo "crashed" >> log
end

Make it executable (chmod +x), then run it like nohup ./thisscript.sh & . 使它可执行(chmod + x),然后像nohup ./thisscript.sh &一样运行它。

Or let other software to do it for you (like dm03514 suggested). 或者让其他软件为您完成此操作(建议使用dm03514)。

If you want to restart it from within itself you could try: 如果要从自身内部重新启动它,则可以尝试:

import os, sys

os.execv(__file__, sys.argv) #__file__ for current file or one of your choice

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

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