skip to Main Content

I have a python3.9 script I want to have running 24/7. In it, I use python-daemon to keep it running like so:

import daemon

with daemon.DaemonContext():
   %%script%%

And it works fine but after a few hours or days, it just crashes randomly. I always start it with sudo but I can’t seem to figure out where to find the log file of the daemon process for debugging. What can I do to ensure logging? How can I keep the script running or auto-restart it after crashing?

You can find the full code here.

2

Answers


  1. I would start with familiarizing myself with those two questions:

    Looks like you need a supervisor that will make sure that your script/daemon is still running. You can take a look at supervisord.

    Login or Signup to reply.
  2. If you really want to run a script 24/7 in background, the cleanest and easiest way to do it would surely be to create a systemd service.

    There are already many descriptions of how to do that, for example here.

    One of the advantages of systemd, in addition to being able to launch a service at startup, is to be able to restart it after failure.

    Restart=on-failure
    

    If all you want to do is automatically restart the program after a crash, the easiest method would probably be to use a bash script.

    You can use the until loop, which is used to execute a given set of commands as long as the given condition evaluates to false.

    #!/bin/bash
    
    until python /path/to/script.py; do
        echo "The program crashed at `date +%H:%M:%S`. Restarting the script..."
    done
    

    If the command returns a non zero exit-status, then the script is restarted.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search