GOSUB 200 - Another Interruption - Daemons and Python
Plunking "instructions to myself" in a blog is useful, so here it comes again. This time it's about Python, Daemons and "systemd".
For code that I want to run all of the time and have it managed by the operating system there are a handful of approaches: write it as a daemon, write it as a executable and work up some cron scripts to keep it going, and now there's systemd. Like it, revile it -- it looks like systemd is here to stay.
So, briefly, here's what I did to make my Python code managed by the systemd service.
It starts with a 'unit' file. Bear in mind I have precious little information on what all of the options are, what the ones I've used actually do and the ramifications of the choices made.
But here's what's working for me.
Step 1 - Create <useful-name>.service
$ more garagedoorcontroller.service
[Unit]
Description=Garage
Door Controller Service
After=syslog.target
[Service]
Type=simple
User=myname
Group=mygroup
WorkingDirectory=/complete/path/GarageDoorController
ExecStart=/usr/bin/python
/complete/path/GarageDoorController/GDController.py
StandardOutput=syslog
StandardError=syslog
Restart=always
RestartSec=60
Restart=always
RestartSec=60
[Install]
WantedBy=default.target
#
#
After this the steps are:
#
Create the unit file in /etc/systemd/system (the file name
#
before .service will be the name you call to start/stop/restart the
service)
#
Set file permissions to 644
#
Tell systemd that there is a new unit file: systemctl daemon-reload
#
Start service: systemctl start <service>
#
Check the service status: systemctl status <service>
Steps 2 and 3 - Copy it to the right spot
foo: $ sudo cp garagedoorcontroller.service /etc/systemd/system/.
foo:
$ sudo chmod 644 /etc/systemd/system/garagedoorcontroller.service
Step 4 - Tell systemd that there's a new (or altered file)
foo:
$ sudo systemctl daemon-reload
Step 5 and 6 - Start it, check the status
foo:
$ sudo systemctl start garagedoorcontroller
foo:
$ sudo systemctl status garagedoorcontroller
● garagedoorcontroller.service - Garage Door Controller Service
Loaded: loaded (/etc/systemd/system/garagedoorcontroller.service; disabled)
Active: active (running) since Wed 2017-08-09 09:35:17 MDT; 18min ago
Main PID: 12961 (python)
CGroup: /system.slice/garagedoorcontroller.service
└─12961 /usr/bin/python /complete/path/GarageDoorController/GDController.py
Aug 09 09:35:17 rpi4 systemd[1]: Started Garage Door Controller Service.
Tail /var/log/syslog if you have problems. The error messages are descriptive.
The BSD daemon, also called Beastie (a near homophone of the letters B-S-D pronounced slurred together), as drawn by John Lasseter. His widely known and popular take on the BSD mascot first showed up on a book cover in 1988.
[ From the Wikipedia entry on BSD Daemon. ]
No comments :
Post a Comment