1

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.

leonheess
  • 16,068
  • 14
  • 77
  • 112

2 Answers2

7

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.

Cubix48
  • 2,607
  • 2
  • 5
  • 17
  • 1
    Another feature of `systemd` is that it can prepare everything needed for a daemon process so the program itself does not have to. – VPfB Mar 02 '22 at 09:25
5

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.

piotr.gradzinski
  • 873
  • 1
  • 10
  • 22