Running python at boot..problems


#1

Hi,

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.
MQTT_USERNAME  = "x"
MQTT_PASSWORD  = "x"
MQTT_CLIENT_ID = "x"

client = cayenne.client.CayenneMQTTClient()

client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)

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:
  client.loop()

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

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

All the help will be greatly appropriated.

Thanks


#2

Hi @rushtkb, do you get the same error if you just try to run motor.py 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 https://github.com/myDevicesIoT/Cayenne-MQTT-Python
cd Cayenne-MQTT-Python
python setup.py install

Then running motor.py again helps out at all.


#3

Hi @rsiegel,

No, I can run the command as “python /home/pi/motor.py” 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.


#4

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.


#5

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


#6

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.


#7

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