Python服务被报告为已成功,即使它已失败

2024-04-26 00:59:53 发布

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

我正在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脚本


Tags: toimportself脚本configsmartdeviceservice