当前位置: 首页 > 面试题库 >

RPi python脚本无法从以下位置运行:/etc/rc.local、crontab、systemd

孔和畅
2023-03-14
问题内容

我试图使该python脚本从/etc/rc.local,crontab @reboot和通过systemctl的systemd运行,但没有成功。

python脚本以pi用户身份登录时从命令行运行,并正常退出后台而没有问题。用pi用户在提示符下运行它的方法与此相同:sh /etc/rc.local

任何指导将不胜感激,如下所示:

#!/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

这是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表现良好

     # 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的支持,该照片现在自动开始:

https://drive.google.com/file/d/19ribELmAnQFy4jfzi5D6I7fk91naS8J7/view?usp=drivesdk


问题答案:

通过/etc/rc.local以下命令运行python脚本:

1)使用编辑文件sudo /etc/rc.local

2)在文件之前添加以下内容exit 0

(sleep 10;python /home/pi/Cigar-Box/CigarBox.py)&

括号允许您在后台运行多个命令。这sleep 10将使脚本的运行延迟10秒,因为启动rc.local时脚本所依赖的某些服务可能尚不可用。

另外,您可以使用crontab @reboot来自动执行脚本。

使用crontab:

1)运行命令行sudo crontab -e

2)将命令添加到文件末尾:

@reboot /usr/bin/python /home/pi/Cigar-Box/CigarBox.py


 类似资料:
  • 我想在ubuntu 14.04LTS的引导上运行一个python脚本。 我的rc.local文件如下: sudo /首页/hduser/morey/动物园管理员-3.3.6/bin/zkServer.sh启动 回声“测试” sudo/home/HD user/Morey/Kafka/bin/Kafka-server-start . sh/home/HD user/Morey/Kafka/confi

  • 在 /etc/rc[06].d/ 目录中的程序启动之后,系统的启动就已经完成。不过,我们总有一些程序是需要在系统启动之后随着系统一起启动的。这时我们并不需要自己把需要启动的服务链接到 /etc/rc3.d/ 目录中,因为系统给我们准备了 /etc/rc.d/rc.local 配置文件。 这个配置文件会在用户登陆之前读取,这个文件中写入了什么命令,在每次系统启动时都会执行一次。也就是说,如果有任何需

  • 首先让我告诉你,我是新来的。我用Sikuli IDE开发了一些脚本,效果很好。 但是当我创建类并将测试作为方法添加到类中时..它不起作用。有人能告诉我我错过了什么吗?我的四库力剧本是这样的:

  • 当我试图登录本地postgres数据库并提交查询时,我的BASH脚本中的psql命令遇到了问题。我以以下方式使用该命令: 但是,我收到以下错误消息。 PSQL: FATAL:用户"postgres"的身份验证失败 在我将以下更改附加到 /var/lib/pgsql/data/pg_hba.conf后,从命令行运行非常好: 本地所有信任 托管所有127.0.0.1/32信任 另外,能否验证一下这一点

  • 问题内容: 我正在尝试使用Linux crontab执行python脚本。我想每10分钟运行一次此脚本。 我找到了很多解决方案,但都无济于事。例如:在/etc/cron.d中编辑anacron或使用。我将此行放在文件的末尾,但它没有任何改变。我需要重启任何服务吗? 我必须编辑哪个文件来配置它? 提前致谢 这是脚本。 问题答案: 只需使用并按照此处的教程操作即可。 请参阅第3点,以获取有关如何指定频

  • 问题内容: 我的python脚本未在crontab下运行。 我将其放在顶部的python脚本中: 我尝试这样做: 添加到我的: 我的/ var / log / cron文件说: 但是我的脚本没有运行,因为当我检查sql数据库时,什么都没有改变。如果我像这样直接在终端中运行它: 我得到正确的结果。 这是: 每条评论:是的,存在。我也可以使用just直接运行python脚本。作品。所以我不相信这是原因