Search code examples
serverrestart

How do I make my Python script that is running on the server, to automatically restart after the connection is broken?


I am running my Python script on the server. It connects to the database and appends the results to the file. So that the new row with the result is always written at the end of the file. However, if the connection with the server is broken, I will have to run it again from where it finished last time. Is it possible to make the Python script automatically ssh to the server and run the Python script again without a human interaction?


Solution

  • Run the script like this

    ssh user@host "nohup python -u" - < script.py &
    

    nohup stops the program terminating on the server if the connection is lost

    & at the end means to run this command in the background, so your local terminal can do other stuff without waiting for the ssh to complete.

    Test it by

    • running that command
    • putting your machine in aeroplane mode (force a disconnect somehow)
    • come out of aeroplane mode and ssh into the remote server again
    • Use a tool like htop and look for you python script that should (hopefully) be running still!