How to make Python script run as service? How to make Python script run as service? python python

How to make Python script run as service?


I use this code to daemonize my applications. It allows you start/stop/restart the script using the following commands.

python myscript.py startpython myscript.py stoppython myscript.py restart

In addition to this I also have an init.d script for controlling my service. This allows you to automatically start the service when your operating system boots-up.

Here is a simple example to get your going. Simply move your code inside a class, and call it from the run function inside MyDeamon.

import sysimport timefrom daemon import Daemonclass YourCode(object):    def run(self):        while True:            time.sleep(1)class MyDaemon(Daemon):    def run(self):        # Or simply merge your code with MyDaemon.        your_code = YourCode()        your_code.run()if __name__ == "__main__":    daemon = MyDaemon('/tmp/daemon-example.pid')    if len(sys.argv) == 2:        if 'start' == sys.argv[1]:            daemon.start()        elif 'stop' == sys.argv[1]:            daemon.stop()        elif 'restart' == sys.argv[1]:            daemon.restart()        else:            print "Unknown command"            sys.exit(2)        sys.exit(0)    else:        print "usage: %s start|stop|restart" % sys.argv[0]        sys.exit(2)

Upstart

If you are running an operating system that is using Upstart (e.g. CentOS 6) - you can also use Upstart to manage the service. If you use Upstart you can keep your script as is, and simply add something like this under /etc/init/my-service.conf

start on started sshdstop on runlevel [!2345]exec /usr/bin/python /opt/my_service.pyrespawn

You can then use start/stop/restart to manage your service.

e.g.

start my-servicestop my-servicerestart my-service

A more detailed example of working with upstart is available here.

Systemd

If you are running an operating system that uses Systemd (e.g. CentOS 7) you can take a look at the following Stackoverflow answer.


I offer two recommendations:

supervisord

1) Install the supervisor package (more verbose instructions here):

sudo apt-get install supervisor

2) Create a config file for your daemon at /etc/supervisor/conf.d/flashpolicyd.conf:

[program:flashpolicyd]directory=/path/to/project/rootenvironment=ENV_VARIABLE=example,OTHER_ENV_VARIABLE=example2command=python flashpolicyd.pyautostart=trueautorestart=true

3) Restart supervisor to load your new .conf

supervisorctl updatesupervisorctl restart flashpolicyd

systemd (if currently used by your Linux distro)

[Unit]Description=My Python daemon[Service]Type=simpleExecStart=/usr/bin/python3 /opt/project/main.pyWorkingDirectory=/opt/project/Environment=API_KEY=123456789Environment=API_PASS=passwordRestart=alwaysRestartSec=2[Install]WantedBy=sysinit.target

Place this file into /etc/systemd/system/my_daemon.service and enable it using systemctl daemon-reload && systemctl enable my_daemon && systemctl start my_daemon --no-block.

To view logs:

systemctl status my_daemon


My non pythonic approach would be using & suffix. That is:

python flashpolicyd.py &

To stop the script

killall flashpolicyd.py

also piping & suffix with disown would put the process under superparent (upper):

python flashpolicyd.pi & disown