Python As A Service

In Centos 7 I have been running screen on reboot (via cron) to start a script like this.

@reboot screen -d -m -S pir /opt/bin/myscustom.py

But wanted to be more modern and use systemd unit files and as of Rocky 8 (Recall I am moving things to Rocky 9) I can run a python script as a systemd service and output the contents to a file for tracking.

So I went off and created a system service (unit) file

vi /etc/systemd/system/mycustom.service

In it I placed

[Unit]
Description=Home Node PIR MQTT
After=network.target

[Service]
User=larry
Group=larry
Type=simple
StandardError=journal
StandardOutput=journal
StandardInput=null
StandardOutput=file:/var/log/myscustom/stdout.log
StandardError=file:/var/log/myscustom/stderr.log
ExecStart=/opt/bin/myscustom.py

[Install]
WantedBy=multi-user.target

Note instead of file I could have used append so the file just grows instead of getting replaced everytime things are restarted.

I did create the folder and chown it with larry:larry but it created the files on restart with owner root so I chowned the files themselves afterwards.

Another change is the python script itself

I need to add a -u to the first line like this

!/usr/bin/python -u

That tells python to not buffer standard out and send it immediately, that way systemd can see it.

On the personal front, son had his Senior day for cross country, where they celebrate the seniors. He did OK today, last year rocking something under 21 would be awesome but I guess I expect more.

Not getting my steps in, been super tired. I need to sleep earlier.

Weight: 344.2

This entry was posted in Fitbit, New Toys, Technical, Training, Virtualization, Weigh In. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.