Skip to content
Advertisement

KeyError: Python script executed by linux service unable to access environment var

So I have a simple service on my Raspberry Pi that runs a Python script on boot. I have also set the env variable by running export OPSESPORT=XXXX. This is the service file:

[Unit]
Description=My desc
After=multi-user.target

[Service]
Type=simple
User=pi
ExecStart=/usr/bin/python /home/pi/path/to/file/somefile.py
Restart=on-failure

[Install]
WantedBy=multi-user.target

And in somefile.py, I have:

import os
PORT = int(os.environ['OPSESPORT'])
#other code

Which leads to the following error when checking logs of the service:

Traceback (most recent call last):
   File  line 141, in <module>
     main()
   File  line 83, in main
     PORT = int(os.environ['OPSESPORT'])
   File  in __getitem__
    raise KeyError(key)
KeyError: 'OPSESPORT'

This is super weird since if I just run the script, python somefile.py, then it works fine, but if I start the service with sudo systemctl start name.service which then runs the script, it can’t access the key. For reference, I am using Python 2.7.13 on Raspbian GNU/Linux 9 (stretch).

Advertisement

Answer

When you use sudo it doesn’t use the same env variables. Can you run systemctl start name.service without super user privileges ?

Edit: Try adding
[Service] Enviroment="OPSESPORT=XXX"

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement