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. (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.
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. 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.
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!")