World of Cheese

cs 09 április 2020

Services

Posted by Andy in Tech   

This isn't an exciting post about organising church in the midst of a pandemic. However, it is a simple post about how easy it is to create a python service on a rpi which use Inotify to monitor a change in the file system.

Disclaimer - I've read a bit about this online and I can't remember my sources! I know this isn't great but I'm sure you can find the original if needed by searching for the code

I've used this for a simple file sorter in a shared folder but the concepts are quite simple. At the heart of the code is a connection to inotify. The main python code is

import inotify.adapters

notifier = inotify.adapters.Inotify()
notifier.add_watch('<folder-path>')

for event in notifier.event_gen():
  print(event)

This code will spit out every event and then you can tailor your response according to your needs

Installing the service was surprisingly simple using systemd. I know this a hot potato in Linux as some love it and other hate it so much that they fork oses! . For me, I wasn't an old school expert (start, restart,stop only) so there wasn't a real learning curve to re/unlearn.

I've started using pyenv on every machine i use. TBH, I break things regularly, install random packages which may work and I can't face my whole python ecosystem dying. Pyenv with virtualenv gives me a nice way to create seperate updated versions of python which I can use. Also, it removes me from being dependant on my os for package updates. I can install updates in my standard os's version of python but I've found that this can lead to dependency hell and lots of mess.

So using pyenv in "real systems" is quite easy. (This was based on this blog post ). For systemd services you just use the fully qualified path for the python executable you want.

Writing the systemd service was really simple. This file template was modified in the /etc/systemd/service folder as <file>.service.

[Unit]
Description=Dummy Service
After=multi-user.target
Conflicts=getty@tty1.service

[Service]
Type=simple
ExecStart={full path to pyenv bin folder}/python3 /usr/bin/dummy_service.py
StandardInput=tty-force

[Install]
WantedBy=multi-user.target

The systemd magic was just

sudo systemctl daemon-reload
sudo systemctl enable dummy.service
sudo systemctl start dummy.service

and it works!!


    
 
 

Comments