简体   繁体   English

需要使用此脚本来检查服务状态

[英]Need a hand with this script to check service status

Sorry I am a beginner in programming.抱歉,我是编程初学者。 I encountered a problem that I cannot figure out to complete the script in a way I expected.我遇到了一个问题,我无法以我预期的方式完成脚本。

Expected : This python script will identify a service [Webmin] is currently active or not then turn on the light corresponding to the GPIO.pinout.预期:此 python 脚本将识别服务 [Webmin] 当前是否处于活动状态,然后打开与 GPIO.pinout 对应的灯。 (If the service is active then the light will be on otherwise it'll be turned off) (如果服务处于活动状态,则指示灯将亮起,否则将关闭)

Problem now: When I ran the script, the script will keep returning "active" in the command-line interface and the light wouldn't turn on.现在的问题:当我运行脚本时,脚本将在命令行界面中不断返回“活动”并且灯不会亮。 I tried to modify os.system('systemctl is-active webmin') to os.system('systemctl is-active --quiet webmin') to mute the output but the light still wouldn't work.我试图将os.system('systemctl is-active webmin')os.system('systemctl is-active --quiet webmin')以将输出静音,但灯仍然无法工作。

Please help me to check whether if something is coded wrongly, I tried to Google it for similar information and solution but little did it helped me.请帮我检查是否有什么东西编码错误,我试图在谷歌上搜索类似的信息和解决方案,但对我几乎没有帮助。 Thank you in advance.先感谢您。

#!/usr/bin/env python
import RPi.GPIO as GPIO
import os
import time

GREEN = 26
YELLOW = 19
RED = 13

# Pin Setup:
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(GREEN, GPIO.OUT)
GPIO.setup(YELLOW, GPIO.OUT)
GPIO.setup(RED, GPIO.OUT)


while True:

        check = os.system('systemctl is-active webmin')
        match = ('active')
        if check == match:
                GPIO.output(RED, True)
                time.sleep (1)

        else:
                GPIO.output(RED, False)
                GPIO.output(YELLOW, False)
                GPIO.output(GREEN, False)

Using os.system() only give you back the error code of the command, not the result of the command.使用os.system()只会返回命令的错误代码,而不是命令的结果。 As stated in the documentation for os.system() , you should look into using the subprocess module for running OS commands and retrieving the results of them.正如指出的文档os.system()你应该考虑使用subprocess模块用于运行操作系统命令和检索它们的结果。

import subprocess
check = subprocess.run(["systemctl", "is-active", "webmin"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if check.stdout == b"active":  # Your result may end in a newline: b"active\n"
    print("Webmin is active!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM