Systemd service not recognizing python library

5,544

Systemd starts the processes with a minimal environment. In this case you are probably missing PYTHONPATH and maybe more. Try it yourself on the command line with env:

env -i /usr/bin/python3 /home/pi/discord/bug.py

You will probably get the same error. So now try it with

env -i PYTHONPATH=you-path /usr/bin/python3 /home/pi/discord/bug.py

If this works, add

Environment=PYTHONPATH=you-path

to your systemd unit.

If it doesn't work, you need to find out what else is needed.

Share:
5,544

Related videos on Youtube

Aeolus
Author by

Aeolus

My main language is python3, just got into game development with pygame. Have been using python for 1 or 2 years, programming for 4 or 5.

Updated on September 18, 2022

Comments

  • Aeolus
    Aeolus over 1 year

    I'm trying to run a python discord bot when my Raspberry Pi starts up. To do this, I've used a systemd service:

    [Unit]
    Description=Testing
    
    [Service]
    Type=idle
    WorkingDirectory=/home/pi
    ExecStart=/usr/bin/python3 /home/pi/discord/bug.py
    
    [Install]
    WantedBy=multi-user.target
    

    I have done several test using simpler python programs before, and it all works fine. When trying to run the discord bot, it throws an error at the import statement. For testing I run:

    sudo systemctl start bugstart
    sudo systemctl status bugstart
    

    The output of the status is the following:

    bugstart.service - Testing
       Loaded: loaded (/lib/systemd/system/bugstart.service; enabled; vendor preset: enabled)
       Active: failed (Result: exit-code) since Sun 2018-08-12 02:08:47 UTC; 1s ago
      Process: 1039 ExecStart=/usr/bin/python3 /home/pi/discord/bug.py (code=exited, status=1/FAILURE)
     Main PID: 1039 (code=exited, status=1/FAILURE)
    
    Aug 12 02:08:46 raspberrypi systemd[1]: Started Testing.
    Aug 12 02:08:47 raspberrypi python3[1039]: Traceback (most recent call last):
    Aug 12 02:08:47 raspberrypi python3[1039]:   File "/home/pi/discord/bug.py", line 1, in <module>
    Aug 12 02:08:47 raspberrypi python3[1039]:     import discord
    Aug 12 02:08:47 raspberrypi python3[1039]: ImportError: No module named 'discord'
    Aug 12 02:08:47 raspberrypi systemd[1]: bugstart.service: Main process exited, code=exited, status=1/FAILURE
    Aug 12 02:08:47 raspberrypi systemd[1]: bugstart.service: Unit entered failed state.
    Aug 12 02:08:47 raspberrypi systemd[1]: bugstart.service: Failed with result 'exit-code'.
    

    I found out that the commands are run as root, so I figured it might be that the library hand't been installed on root, but I tried importing discord in the command line shell and it worked fine.

  • Aeolus
    Aeolus over 5 years
    The first one worked, but that might be because of another solution I recently tried. Someone told me to install the discord library with sudo -H pip3 install discord.py and that solved my problem.