Skip to content

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:

Description=My desc

ExecStart=/usr/bin/python /home/pi/path/to/file/


And in, 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>
   File  line 83, in main
     PORT = int(os.environ['OPSESPORT'])
   File  in __getitem__
    raise KeyError(key)

This is super weird since if I just run the script, python, 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).



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