prwiley
Posts: 11
Joined: Tue Jun 19, 2018 2:08 pm
Location: Pennsylvania USA

Python program throws error when starting as service. Why?

Sun May 19, 2019 3:04 pm

I have a program I have setup a Unit file for so that it will run as a service on startup.

The program runs fine from the command line, however it fails to run on startup.

When I check the status of the service, I see that has it failed to load. I see the failure is the result of:

import paho.mqtt.client as mqtt
ImportError: No module named 'paho'

And yet the the program does run from the command line, and also in IDLE, just fine and throws no import error.

Can someone explain what's going on?

Many thanks
Last edited by prwiley on Sun May 19, 2019 3:30 pm, edited 1 time in total.

Andyroo

Re: Python program throws error when starting as service. Why?

Sun May 19, 2019 3:12 pm

It could be the path.

Check the user the program is running under and it’s default path. I assume this user is root compared to Pi.

prwiley
Posts: 11
Joined: Tue Jun 19, 2018 2:08 pm
Location: Pennsylvania USA

Re: Python program throws error when starting as service. Why?

Sun May 19, 2019 3:28 pm

When I ps -ef | grep python the owner is pi

I note that a log file the program creates is put in /home/pi/ when run from the command line and in /home/pi/programDir/ when run from IDLE

Is the fix just providing the right path for the import statement? No sure I quite know how to find it.

prwiley
Posts: 11
Joined: Tue Jun 19, 2018 2:08 pm
Location: Pennsylvania USA

Re: Python program throws error when starting as service. Why?

Sun May 19, 2019 5:23 pm

After some more searching I found this thread at StackExchnage: https://stackoverflow.com/questions/356 ... tl-service

Per the advice there are updated my Unit file as follows:

Code: Select all

[Unit]
Description=my.service

[Service]
WorkingDirectory=/home/pi/
User=pi
ExecStart=/home/user/otherDir/program.py
Restart=always

[Install]
WantedBy=multi-user.target
This did the trick. Before doing this I also changed the default python from 2.7.x to 3.5.x

Andyroo

Re: Python program throws error when starting as service. Why?

Sun May 19, 2019 5:40 pm

prwiley wrote:
Sun May 19, 2019 5:23 pm
...
This did the trick. Before doing this I also changed the default python from 2.7.x to 3.5.x
Just a bit concerned about the change - that may break other things within the OS that are expecting that Python 2 is the default. It may be better to make the Python3 the executable program with your program and path the parameter...

Return to “Python”