【问题标题】:Python script boot - DebianPython 脚本启动 - Debian
【发布时间】:2021-08-15 00:13:53
【问题描述】:

我正在尝试在启动时启动程序但没有成功。 该程序启动良好,但不能保持活力(它应该是一个无限脚本)。 但是当我正常启动程序时,我没有任何问题!我不明白为什么当我在重新启动时运行它不起作用。

我使用这样的 cron 选项卡:

@reboot sudo python /bin/gestion.py &

我可以给你看我的代码:

import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.PWM as PWM
import time
import socket
import threading
import sys

from os.path import expanduser
import datetime

print("DEBUT")

vitesse = 4
etat_moteur_droit = 0
etat_moteur_gauche = 0
data_thr = "Starting"
etat_thr = 1
HOST = '192.168.1.50'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

file = open('/home/log.txt', 'w')
file.write("It worked!\n" + str(datetime.datetime.now()))
file.close()

print("MID")

def main():
    global data_thr
    global etat_thr
    global etat_moteur_droit
    global etat_moteur_gauche
    global vitesse
    
    print("START")
    etat_moteur_droit=0
    setup_io()
    # gestion_bonus(0)
    # gestion_moteur_droit(4,0)
    # gestion_moteur_gauche(4,0)
    # avancer()
    # time.sleep(3)
    # tourner_a_gauche()
    # time.sleep(3)
    # tourner_a_droite()
    # time.sleep(3)
    # arreter()
    x = threading.Thread(target=thread_serveur)
    x.start()
    while True:
        try:
            data_thr = data_thr.partition('\n')[0]
            if(data_thr == ""):
                etat_thr = 0
            if(data_thr == "Fin thread"):
                x = threading.Thread(target=thread_serveur)
                x.start()
                data_thr = "Fin thread step 2"
            if(data_thr == "avance"):
                avancer()
            if(data_thr == "stop"):
                arreter()
            if(data_thr == "gauche"):
                tourner_a_gauche()
            if(data_thr == "droite"):
                tourner_a_droite()
            if(data_thr[:7] == "vitesse"):
                vitesse  = int(data_thr[8:10])
                if(etat_moteur_droit == 1):
                    PWM.set_duty_cycle("P9_14", vitesse)
                if(etat_moteur_gauche == 1):
                    PWM.set_duty_cycle("P8_19", vitesse)
        except:
            print("Erreur lors de reception message")
    print("FIN")
    file = open('/home/log.txt', 'w')
    file.write("FIN!\n" + str(datetime.datetime.now()))
    file.close()
    

def thread_serveur():
    global data_thr
    global etat_thr
    connected = 0
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
    while connected == 0:
        try :
            s.bind((HOST, PORT))
        except socket.error:
            pass
        finally:
            connected = 1
    s.listen(1)
    conn, addr = s.accept()
    print('Connected by', addr)
    timing = 0
    start = time.time()
    while etat_thr == 1:
        try:
            data_thr = conn.recv(1024)
            if not data_thr:
                break
            if data_thr != "":
                print(data_thr)
            conn.sendall("Bien recu")
        except:
            print("Erreur lecture thread")
    s.shutdown(socket.SHUT_RDWR)
    s.close()
    data_thr = "Fin thread"
    
def setup_io():
    GPIO.setup("P9_17", GPIO.OUT)
    GPIO.setup("P9_24", GPIO.OUT)
    GPIO.setup("P9_23", GPIO.OUT)
    PWM.start("P9_14", 0)
    PWM.stop("P9_14")
    PWM.start("P8_19", 0)
    PWM.stop("P8_19")
    PWM.cleanup()

def gestion_bonus(etat):
    if(etat == 1):
        GPIO.output("P9_17", GPIO.HIGH)
    else:
        GPIO.output("P9_17", GPIO.LOW)
    GPIO.cleanup()
    
def gestion_moteur_droit(vitesse,enable):
    global etat_moteur_droit
    
    if(enable == 1 and etat_moteur_droit == 0):
        PWM.start("P9_14", vitesse)
        GPIO.output("P9_24",GPIO.HIGH)
        etat_moteur_droit = 1
    elif(enable == 1 and etat_moteur_droit == 1):
        PWM.set_duty_cycle("P9_14", vitesse)
        GPIO.output("P9_24",GPIO.HIGH)
    elif(enable == 0):
        PWM.stop("P9_14")
        GPIO.output("P9_24",GPIO.LOW)
        etat_moteur_droit =0
    GPIO.cleanup()

def gestion_moteur_gauche(vitesse,enable):
    global etat_moteur_gauche
    
    if(enable == 1 and etat_moteur_gauche == 0):
        PWM.start("P8_19", vitesse)
        GPIO.output("P9_23",GPIO.HIGH)
        etat_moteur_gauche = 1
    elif(enable == 1 and etat_moteur_gauche == 1):
        PWM.set_duty_cycle("P8_19", vitesse)
        GPIO.output("P9_23",GPIO.HIGH)
    elif(enable == 0):
        PWM.stop("P8_19")
        GPIO.output("P9_23",GPIO.LOW)
        etat_moteur_gauche =0
    GPIO.cleanup()

def avancer():
    global vitesse
    gestion_moteur_droit(vitesse,1)
    gestion_moteur_gauche(vitesse,1)

def tourner_a_gauche():
    global vitesse
    gestion_moteur_droit(vitesse,1)
    gestion_moteur_gauche(vitesse,0)
    
def tourner_a_droite():
    global vitesse
    gestion_moteur_droit(vitesse,0)
    gestion_moteur_gauche(vitesse,1)

def arreter():
    global vitesse
    gestion_moteur_droit(vitesse,0)
    gestion_moteur_gauche(vitesse,0)
if __name__ == "__main__":
    main()

你能帮帮我吗?

【问题讨论】:

  • 切线,192.168.1.50 绝对不是标准的环回地址。
  • 没有任何调试细节,甚至很难推测。从cron 运行sudo 可能不是一个好主意;从rootcrontab 运行它(在这种情况下,没有sudo 有用或必要,或者如果脚本可以无特权运行,则在没有sudo 的情况下自己运行它。应该不需要运行该进程无论哪种方式都在后台运行;cron 作业已经在没有终端或其他交互设施的情况下运行。
  • 可能另请参阅提供minimal reproducible example 的指南。您发布的大多数代码可能与问题完全无关,只会掩盖它。如果重现您的问题需要我们完全拥有您的设备,那么人们不太可能提供帮助。
  • 另外,可能不要把你本地的东西直接放在/bin。发行版希望能够随时擦除此目录 - 可能不会,但如果您遵循有用的约定,许多管理任务会更容易。您的本地可执行文件应位于专门为此目的而存在的/usr/local/bin(或/opt,如果您愿意)。

标签: python debian boot


【解决方案1】:

我可以看到您正在使用一些网络服务。也许当 cron 在@reboot 运行时,网络还没有准备好。可能值得尝试以这种方式实现为服务并运行命令。

示例实现

创建一个可以找到系统守护程序服务的文件,例如:/lib/systemd/system/TestStartup.service。成员内容示例:

[Unit]
Description=Test service for startup
After=network.target

[Service]
User=root
ExecStart=/usr/bin/python /bin/gestion.py
Restart=on-failure
RestartSec=30

[Install]
WantedBy=multi-user.target

/usr/bin/pythn 可以根据您使用的版本和安装在您的机器上的位置而有所不同,但您可以通过whereis python 命令输出查看:

ati@atihome:/lib/systemd/system$ whereis python
python: /usr/bin/python2.7 /usr/bin/python /usr/bin/python3.7 /usr/bin/python3.7m /usr/lib/python2.7 /usr/lib/python3.7 /etc/python2.7 /etc/python /etc/python3.7 /usr/local/lib/python2.7 /usr/local/lib/python3.7 /usr/share/python /usr/share/man/man1/python.1.gz

然后您需要重新加载系统守护程序并启用该服务以允许在系统启动后运行。该服务将在网络启动后启动。你可以通过这些命令来做:

systemctl daemon-reload
systemctl enable TestStartup (or how you named your member)

你可以测试,这个命令启动命令是否正确:

systemctl start TestStartup

并通过以下命令检查其状态:

systemctl status TestStartup

然后您可以重新启动计算机并检查它是否正常工作。我并不是说这是 100% 的解决方案,但它可能值得一试。

【讨论】:

  • 您好,感谢您的帮助!你是对的,它是由于你的网络启动。我已经尝试过您的解决方案,但没有成功,要使其正确,我需要对我的代码进行一些编辑:将 ip 地址更改为 localhost "0.0.0.0" 及其工作!我在绑定部分“无法分配请求的地址”上遇到问题。再次感谢:)
猜你喜欢
  • 2013-02-16
  • 2016-02-01
  • 1970-01-01
  • 2023-03-28
  • 2016-03-14
  • 2021-08-15
  • 2021-04-07
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多