RPi python脚本无法从:/etc/rc.local、crontab、systemd运行
我试图通过systemctl从/etc/rc.local、crontab@reboot和systemd运行这个python脚本,但没有成功 python脚本在以用户pi身份登录时从命令行运行,并优雅地退出到后台,不会出现问题。同样,在提示下运行它时,用户pi使用:sh/etc/rc.localRPi python脚本无法从:/etc/rc.local、crontab、systemd运行,python,json,amazon-web-services,raspberry-pi,iot,Python,Json,Amazon Web Services,Raspberry Pi,Iot,我试图通过systemctl从/etc/rc.local、crontab@reboot和systemd运行这个python脚本,但没有成功 python脚本在以用户pi身份登录时从命令行运行,并优雅地退出到后台,不会出现问题。同样,在提示下运行它时,用户pi使用:sh/etc/rc.local #!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make su
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
# Print the IP address
#_IP=$(hostname -I) || true
#if [ "$_IP" ]; then
# printf "My IP address is %s\n" "$_IP" > /home/pi/cigarbox.log
#fi
(python /home/pi/Cigar-Box/CigarBox.py)&
#/usr/bin/python /home/pi/Cigar-Box/CigarBox.py > /home/pi/cigarbox.log 2>&1 &
exit 0
请提供以下指导:
#!/usr/bin/python
#required libraries
import sys
import ssl
import paho.mqtt.client as mqtt
import json
from pprint import pprint
import Adafruit_CharLCD as LCD
from textwrap import fill
#Configuration
rootCAPath = "/home/pi/Cigar-Box/certs/rootCA.pem"
certFilePath = "/home/pi/Cigar-Box/certs/xxxxxxxxxx-certificate.pem.crt"
keyFilePath = "/home/pi/Cigar-Box/certs/xxxxxxxxxx-private.pem.key"
iotThing = "Zorua"
clientID = "Zorua"
#Device JSON initialization
device = {'state': {'reported': {'HP':100} } }
device['state']['reported']['color'] = {'r':0, 'g':0, 'b':0}
#Create LCD
lcd = LCD.Adafruit_CharLCDPlate()
#LCD wrapper
def set_lcd_color(R,G,B):
global lcd
device['state']['reported']['color']['r'] = R
device['state']['reported']['color']['g'] = G
device['state']['reported']['color']['b'] = B
lcd.set_color(R, G, B)
def set_lcd_message(message):
global lcd
device['state']['reported']['msg'] = message
lcd.clear()
#Word wrap to fit 16-char wide display and add capitalization
lcd_message = fill(message.capitalize(),16)
lcd.message(lcd_message)
# Initialize the LCD using the pins
set_lcd_message('Initializing...')
set_lcd_color(0, 0, 1)
#called while client tries to establish connection with the server
def on_connect(mqttc, obj, flags, rc):
print "Connecting..."
if rc==0:
print ("Subscriber Connection status code: "+str(rc)+" | Connectionstatus: successful")
#We only want to be notified about things we need to change to stay in sync with AWS
mqttc.subscribe("$aws/things/" + iotThing + "/shadow/update/delta", qos=1)
elif rc==1:
print ("Subscriber Connection status code: "+str(rc)+" | Connection status: Connection refused")
print ("Subscriber Connection status code: "+str(rc))
#called when a topic is successfully subscribed to
def on_subscribe(mqttc, obj, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos)+"data"+str(obj))
set_lcd_color(0,1,0)
set_lcd_message('Connected!\nReady for input')
#Let AWS know about the current state of the plate so we can tell us what's out of sync
mqttc.publish("$aws/things/" + iotThing + "/shadow/update", json.dumps(device))
#called when a message is received by a topic
#Messages are formatted in JSON
#When working with /update, we might not find all keys all the time, so we need to handle that
def on_message(mqttc, obj, msg):
try:
data = json.loads(msg.payload)
update = data['state']
except:
return
#Look for a message in the update. If it's there, we need to update the display
if 'msg' in update.keys():
try:
set_lcd_message(update['msg'])
except:
print("Could not enact message from topic: "+msg.topic+" | QoS: "+str(msg.qos)+" | Data Received: "+str(msg.payload))
#Look to see if the status of R, G, or B has changed for the display
if 'color' in update.keys():
try: lcd_r = update['color']['r']
except: lcd_r = device['state']['reported']['color']['r']
try: lcd_g = update['color']['g']
except: lcd_g = device['state']['reported']['color']['g']
try: lcd_b = update['color']['b']
except: lcd_b = device['state']['reported']['color']['b']
set_lcd_color(lcd_r,
lcd_g,
lcd_b)
#Let AWS know we've updated the display
mqttc.publish("$aws/things/Zorua/shadow/update", json.dumps(device))
#creating a client with client-id=Zorua
mqttc = mqtt.Client(client_id=clientID)
mqttc.on_connect = on_connect
mqttc.on_reconnect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message
#Configure network encryption and authentication options. Enables SSL/TLS support.
#adding client-side certificates and enabling tlsv1.2 support as required by aws-iot service
mqttc.tls_set(rootCAPath,
certfile=certFilePath,
keyfile=keyFilePath,
tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
#connecting to aws-account-specific-iot-endpoint
print ("About to connect")
mqttc.connect("lettersandnumbers.iot.us-west-2.amazonaws.com", port=8883) #AWS IoT service hostname and portno
#automatically handles reconnecting
mqttc.loop_forever()
位于/etc/rc.local中的代码后面是一个简单的重定向测试,以查看rc.local是否正常工作
# Default code located inside /etc/rc.local
# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP" > /home/pi/cigarbox.log
fi
exit 0
######################################################################
# After rebooting RPi = no output to log
pi@cigarbox:~ $ cat cigarbox.log
# Running /etc/rc.local from the command line
pi@cigarbox:~ $ sh /etc/rc.local
# After running /etc/rc.local locally = output to log
pi@cigarbox:~ $ cat cigarbox.log
My IP address is 192.168.0.21
# Cat and pipe of boot.log
root@cigarbox:~# cat /var/log/boot.log | grep rc.local
Starting /etc/rc.local Compatibility...
[ OK ] Started /etc/rc.local Compatibility.
下面是pi和root的路径
# Running as pi
pi@cigarbox:~ $ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games
# Running s root
pi@cigarbox:~ $ su - root
Password:
root@cigarbox:~# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
很好。看起来rc.local正在运行
# Default code located inside /etc/rc.local
# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP" > /home/pi/cigarbox.log
fi
exit 0
######################################################################
# After rebooting RPi = no output to log
pi@cigarbox:~ $ cat cigarbox.log
# Running /etc/rc.local from the command line
pi@cigarbox:~ $ sh /etc/rc.local
# After running /etc/rc.local locally = output to log
pi@cigarbox:~ $ cat cigarbox.log
My IP address is 192.168.0.21
# Cat and pipe of boot.log
root@cigarbox:~# cat /var/log/boot.log | grep rc.local
Starting /etc/rc.local Compatibility...
[ OK ] Started /etc/rc.local Compatibility.
不过,我过去也试过。根据建议,请参见python命令下面注释掉的行和括号中的路径。因此,脚本仍然不会用完/etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
# Print the IP address
#_IP=$(hostname -I) || true
#if [ "$_IP" ]; then
# printf "My IP address is %s\n" "$_IP" > /home/pi/cigarbox.log
#fi
(python /home/pi/Cigar-Box/CigarBox.py)&
#/usr/bin/python /home/pi/Cigar-Box/CigarBox.py > /home/pi/cigarbox.log 2>&1 &
exit 0
嗯,看来我需要10个好男孩点数来上传图片。我将不得不发布这个团队最感激的帮助的成功完成。谢谢大家..照片URL和后续解决方案
好的,这里有一个链接到我的语音识别项目的照片,由于stackoverflow的新朋友的支持,该项目现在自动启动:
要通过/etc/rc.local
运行python脚本:
1) 使用sudo/etc/rc.local
编辑文件
2) 在退出0之前将以下内容添加到文件中:
(sleep 10;python /home/pi/Cigar-Box/CigarBox.py)&
括号允许您在后台运行多个命令。sleep 10
会将脚本的运行延迟10秒,因为您的脚本所依赖的某些服务在引导rc.local时可能还不可用
或者,您可以使用crontab@reboot自动执行脚本
使用crontab:
1) 运行命令行sudocrontab-e
2) 将命令添加到文件末尾:
@reboot /usr/bin/python /home/pi/Cigar-Box/CigarBox.py
你在问一个关于是否可以提问的问题?如果你能把它归结为一个简单的例子,那也没关系,但从你的帖子上看,它听起来可能相当宽泛。好了,伙计们,这里是细节。你能用一个“hello world”类的程序来替换这个脚本,并试着通过任何这样的方法来运行它吗?让我们先排除剧本的问题。-那是个好的开始。今晚就可以了,但是my/home/pi/cigarbox.log捕获了脚本中的最后一条注释,“即将连接”,当我删除作业命令将其置于后台时,例如&。所以,我认为它运行时,MQTT返回的内容会出现问题。是否有一种方法可以使用/etc/rc.local执行脚本,然后等待10秒,然后将其放入后台,从而避开rc.local中的最后一行,该行执行退出0…这可能会阻止MQTT返回?不管怎样,今晚回到基本点。谢谢如果可以在命令行中运行脚本,但不能以其他方式运行,则可能与设置脚本的方式、文件权限或运行路径问题有关。您没有提供有关如何设置通过/etc/rc.local或crontab运行的信息。我尝试从/etc/rc运行此python脚本。我尝试通过systemctl从/etc/rc.local、crontab和systemd运行此python脚本,但没有成功。ocal、crontab@reboot和systemd通过systemctl运行,但没有成功。我也考虑过使用延迟,但我认为脚本需要启动,然后在将其放到后台之前进行延迟。你知道怎么做吗?同时,我会尝试睡眠10分钟,然后再联系你。谢谢。成功!!!你对问题的分析很准确。非常感谢您的指导和耐心。我最深切的感谢。请花一点时间看看我的语音识别项目:很高兴它能为你工作。如果这个答案能帮助你解决问题。请投票表决。顺便说一句,这看起来像一台很酷的机器……几乎忘记了,解决方案是在/etc/rc.local中为您的一行代码使用sleep 10:(sleep 10;python/home/pi/CigarBox/CigarBox.py)&单击本文左上角的“向上”箭头或“勾号”。