我在raspberry pi上运行服务,这意味着在启动时运行python脚本。有时候python脚本会失败,但是当它失败时,服务仍然会报告它成功,这是错误的。
下面是python脚本:
import cec
import sys
import time
import configparser
from tuya.devices import TuyaSmartSwitch
class SmartSwitch:
def __init__(self, config_path):
CONFIG = configparser.ConfigParser()
CONFIG.read(config_path)
try: # connect to the smart switch
self.device = TuyaSmartSwitch(
username=CONFIG["TUYA"]["username"],
password=CONFIG["TUYA"]["password"],
location=CONFIG["TUYA"]["location"],
device=CONFIG["TUYA"]["device"])
except:
print("Could not connect to the switch")
sys.exit()
def turn_off(self):
self.device.turn_off()
def turn_on(self):
self.device.turn_on()这是终端输出:
pi@raspberrypi:~/subwoofer_switch $ sudo systemctl status subwoofer.service
● subwoofer.service - My script to control suboowfer smart switch
Loaded: loaded (/etc/systemd/system/subwoofer.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Thu 2020-07-02 19:46:43 BST; 23h ago
Process: 541 ExecStart=/usr/bin/python3 /home/pi/subwoofer_switch/subwoofer_control.py (code=exited, status=0/SUCCESS)
Main PID: 541 (code=exited, status=0/SUCCESS)
Jul 02 19:46:30 raspberrypi systemd[1]: Started My script to control suboowfer smart switch.
Jul 02 19:46:43 raspberrypi python3[541]: Could not connect to the switch
Jul 02 19:46:43 raspberrypi systemd[1]: subwoofer.service: Succeeded.正如您所看到的,脚本连接确实失败了,sys.exit()应该已经运行并关闭了脚本,但它仍然报告成功。
服务代码如下:
[Unit]
Description=My script to control suboowfer smart switch
After=multi-user.target
[Service]
Restart=on-failure
RestartSec=10s
Type=idle
ExecStart=/usr/bin/python3 /home/pi/subwoofer_switch/subwoofer_control.py
[Install]
WantedBy=multi-user.target我不确定我做错了什么,因为我希望如果服务启动失败,它将再次尝试运行python脚本
发布于 2020-07-11 22:16:10
如果像您的代码中一样,没有向sys.exit()提供任何参数,则其缺省值为0,这意味着“成功”。因此,如果您打算以失败退出,请使用:
sys.exit(1)https://stackoverflow.com/questions/62721139
复制相似问题