Running python at boot..problems


I am trying to get a python script started at boot and I have tried many methods such as rc.local, .bashrc, systemd and crontab, but unfortunately I’ve not been successful. Here is my code:

#!/usr/bin/env python3
import cayenne.client #Cayenne MQTT Client
from time import sleep
from gpiozero import Button
button=Button(2) # Declaring button pin 2

# Cayenne authentication info. This should be obtained from the Cayenne Dashboard.

client = cayenne.client.CayenneMQTTClient()


def send_on():
  client.virtualWrite(3, 1, "digital_sensor", "d") #Publish "1" to Cayenne MQTT Broker Channel 3
  print("Button pressed\n")

def send_off():
  client.virtualWrite(3, 0, "digital_sensor", "d") #Publish "0" to Cayenne MQTT Broker Channel 3
  print("Button released\n")

button.when_pressed=send_on #When button pressed run send_on function
button.when_released=send_off #When button released run send_off function

while True:

After I log in through shh I get the following error:

Traceback (most recent call last):
File “/home/pi/my-files/”, line 2, in
import cayenne.client #Cayenne MQTT Client
ImportError: No module named ‘cayenne’

All the help will be greatly appropriated.


Hi @rushtkb, do you get the same error if you just try to run from the command line, ignoring the at boot stuff for a moment?

At first glance it looks like our library might not be installed (or at least seen, for whatever reason).

If you are seeing the same error from the command line, I’d be curious if

git clone
cd Cayenne-MQTT-Python
python install

Then running again helps out at all.

Hi @rsiegel,

No, I can run the command as “python /home/pi/” just fine. It triggers the program and runs just fine.

I’m thinking maybe I may have to embed my python code inside a shell and then run it. And put my import as PATH environment variable.

That’s definitely odd, I have done just that over here. crontab is my preferred way as it’s the easiest. Are you changing the crontab of the root user or pi user? You should not be using sudo crontab -e, just crontab -e.

Thanks for the help, I found out what the problem was. I had to put my script in a shell and assign environment variable for the imports. That did the trick. Thanks

1 Like

Glad you got this running and thanks for sharing how you did! I hadn’t experimented too much with running Python scripts at boot so I wasn’t aware it would require this additional step.

I think the best approach here is to be putted as @rsiegel says in the crontab job :slight_smile:

I’ve run into the same wall. e.g. Cron, rc.local, etc to no avail (it does run from the command line with no trouble). Could you post your shell script to help walk a newbie through the steps to get it to run via a shell script?

try to follow these instructions

1 Like