Raspberry Pi 4 和 Python3 脚本启动但在启动时不起作用

问题描述

我写了这段代码,如果我手动启动它,它可以完美运行,但是当我通过 crontab 在启动时启动它时,它启动但无法正常工作。 我声明 gpio 库和麦克风驱动程序都可以工作,因为它可以监听我可以从 LED 和它正在工作的日志文件中看到它。似乎无法正常工作的是语音识别库。
Uso python da pochi mesi。 这是我添加到 crontab 文件中的行: @reboot python3 /home/pi/SpeechRecognition/raspuino_home_assistan.py &

#!/usr/bin/python3

import time
#time.sleep(180)

import speech_recognition as sr
import urllib.request as request
from wireless import Wireless
from RPi import GPIO
import os

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(23,GPIO.OUT)
GPIO.setup(24,GPIO.OUT)
GPIO.setup(25,GPIO.OUT)
GPIO.setup(22,GPIO.OUT)
GPIO.setup(27,GPIO.OUT)
GPIO.output(22,GPIO.LOW)
GPIO.output(27,GPIO.LOW)
GPIO.output(25,GPIO.LOW)

log = open("log.txt","w")
log.write("Start at:" + time.strftime("%H:%M:%s") + "\n")
log.write("Start listenig:" + "\n")
log.close() 

def internet_on():
    
    try:
        request.urlopen('http://google.com',timeout=1)
        return True
    
    except request.URLError as err: 
        return False
    
def internet_check():
    while(internet_on()==False):
        GPIO.output(24,GPIO.HIGH)
    
while(internet_on()==False):
    GPIO.output(24,GPIO.HIGH)

recognizer_instance = sr.Recognizer()

with sr.Microphone() as source:
    recognizer_instance.adjust_for_ambient_noise(source)  
        
def luce_sala():
    GPIO.output(25,GPIO.HIGH)
    time.sleep(0.2)
    GPIO.output(25,GPIO.LOW)     

def luce_cucina():
    GPIO.output(22,GPIO.HIGH)
    time.sleep(0.2)
    GPIO.output(22,GPIO.LOW)      

def luce_led():
    GPIO.output(27,GPIO.HIGH)
    time.sleep(0.2)
    GPIO.output(27,GPIO.LOW)

def tutte_le_luci():
    GPIO.output(25,GPIO.HIGH)
    GPIO.output(22,GPIO.HIGH)
    GPIO.output(27,GPIO.LOW)
    GPIO.output(22,GPIO.LOW)
    GPIO.output(27,GPIO.LOW)                

while (True):
    
    with sr.Microphone() as source:
        recognizer_instance.adjust_for_ambient_noise(source)
        GPIO.output(23,GPIO.HIGH)
        GPIO.output(24,GPIO.LOW)

        audio = recognizer_instance.listen(source)
        GPIO.output(23,GPIO.LOW)
        
    try:
        text = recognizer_instance.recognize_google(audio,language="it-IT")
        log = open("log.txt","a")
        log.write(text + "\n")
        log.close() 
        
        if ("luce sala") in text.lower():
            luce_sala()

        elif ("luce cucina") in text.lower():
            luce_cucina()
            
        elif ("luce led")  in text.lower():
            luce_led()
            
        elif ("tutte le luci") in text.lower():
            tutte_le_luci()         
            
    except Exception as e:
        log = open("log.txt","a")
        log.write("Error: " + str(e) + "\n" )
        log.close() 
        internet_check()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)