在Raspberry pi上启动python脚本有困难

2024-05-16 04:15:34 发布

您现在位置:Python中文网/ 问答频道 /正文

希望有人能帮忙。我是python新手,正在尝试在raspbian上启动一个脚本。我尝试的一切似乎都不管用,只是看到我错过了什么。一个非常基本的脚本,用于在接收到UDP命令时播放音频文件。你知道吗

到目前为止我已经试过了-从rc.本地,在.bashrc中启动它(当我通过ssh启动一个新终端时,从init.d开始,下面是init.d脚本,.py标准脚本是相同的,减去init info。。。。你知道吗

#! /usr/bin/python3

# /etc/init.d/UDP_Python_Omxplayer.py
### BEGIN INIT INFO
# Provides:          UDP_Python_Omxplayer.py
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start daemon at boot time
# Description:       Enable service provided by daemon.
### END INIT INFO

import socket
import os

UDP_IP = "192.168.123.10"
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, # Internet
                 socket.SOCK_DGRAM) # UDP

sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print ("received message:", data)
    command = str(data.decode('ASCII'))

    if command == "Play":
        os.system("omxplayer -o both --no-osd /home/pi/Doc*/Air*")

如上所述,脚本工作,我只是不能让这个autmate和运行在后台启动?你知道吗

提前谢谢。。。你知道吗

在cron作业中尝试了以下内容:

sudo crontab -e 

并补充道

@reboot sudo python /home/pi/UDP_Python_Omxplayer.py

我还把它变成了一个服务,如果我手动启动服务,那么它可以正常工作,但是从引导开始就不行了。。你知道吗


Tags: pyinfo脚本dataremoteinitrequiredsocket
1条回答
网友
1楼 · 发布于 2024-05-16 04:15:34

尝试创建服务。你知道吗

打开shell并键入命令:sudo vi/etc/rc.本地 这将打开一个包含以下详细信息的文件。你知道吗

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

cd /home/pi/XXXXX/XXXXX && python3 my_script.py > /home/pi/Desktop/log.txt 2>&1

exit 0

给出脚本的路径并替换我的_脚本.py用你的剧本名字。保存并退出文件。你知道吗

它还将scipt的日志保存在日志.txt文件。你知道吗

如果这不起作用修改你的脚本如下。你知道吗

#! /usr/bin/python3

# /etc/init.d/UDP_Python_Omxplayer.py
### BEGIN INIT INFO
# Provides:          UDP_Python_Omxplayer.py
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start daemon at boot time
# Description:       Enable service provided by daemon.
### END INIT INFO

from time import sleep
sleep(45)

import socket
import os

UDP_IP = "192.168.123.10"
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, # Internet
                 socket.SOCK_DGRAM) # UDP

sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print ("received message:", data)
    command = str(data.decode('ASCII'))

    if command == "Play":
        os.system("omxplayer -o both  no-osd /home/pi/Doc*/Air*")

相关问题 更多 >