Run Python script forever, logging errors and restarting when crashes

Viewed 7826

I have a python script that continuously process new data and writes to a mongodb. In the script, its a while loop and a sleep that runs the code continuously.

What is the recommended way to run the Python script forever, logging errors when they occur, and restarting when it crashes?

Will node.js's forever be suitable? I'm also running node/meteor on the same Ubuntu server.

4 Answers

I don't know if this is still relevant to you, but I have been reading forever about how to do this and want to share somewhere what I did.

For me, the goal was to have a python script running always (on my Linux computer). The python script also has a "while True " loop in it which should theoretically run forever, but if it for any reason I cannot think of would crash, I want the script to restart. Also, when I restart the computer it should run the script.

I am not an expert but for me the best and most understandable was to use systemd (assuming you use Linux).

There are two nice examples of how to do this given here and here, showing how to write your .service files in either /etc/systemd/system or /lib/systemd/system. If you want to be completely correct you should take the former:

" /etc/systemd/system/: units installed by the system administrator" 1

The documentation of systemd here is actually nice to read, even if you are not an expert.

Hope this helps someone!

Related