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’
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
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’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?
Thanks