This is a Python class that will daemonize your Python script so it can continue running in the background. It works on Unix, Linux and OS X, creates a PID file and has standard commands (start, stop, restart) + a foreground mode.
Based on this original version from jejik.com.
Define a class which inherits from Daemon and has a run() method (which is what will be called once the daemonization is completed.
from daemon import Daemon, run_daemon
class Pantalaimon(Daemon):
def run(self):
# Do stuff
In main.py (main script that will be called) run daemon with run_daemon(daemon_class, path_to_pid), specifying where you want your PID file to exist:
if __name__ == "__main__":
run_daemon(Pantalaimon, '/path/to/pid.pid')
To start daemon:
./main.py start
To stop daemon:
./main.py stop
start()- starts the daemon (creates PID and daemonizes).stop()- stops the daemon (stops the child process and removes the PID).restart()- doesstop()thenstart().
This is useful for debugging because you can start the code without making it a daemon. The running script then depends on the open shell like any normal Python script.
To do this, just call the run() method directly.
pineMarten.run()
The run() method will be executed just once so if you want the daemon to be doing stuff continuously you may wish to use the sched module to execute code repeatedly (example).