简体   繁体   中英

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 & . 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.

I also checked this answer but I'm not sure if the nohup command can be given the until.. do loop. Also wouldn't it just restart my script after every 1 second? 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

If you want your own solution, just use a bash script:

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

Make it executable (chmod +x), then run it like nohup ./thisscript.sh & .

Or let other software to do it for you (like dm03514 suggested).

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

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