我正在尝试使用一个按钮来查找服务,如果服务正在运行,然后调用 systemctl stop“service”,如果它没有运行,则调用 systemctl start“service”
这是我正在使用的代码:
import RPi.GPIO as GPIO
import time
import os
import subprocess
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
service_name = "record"
def minitor(channel):
try:
output = subprocess.run(["systemctl", "status", service_name], capture_output=True)
status = output.stdout.decode().strip()
if "inactive" in status:
subprocess.run(["systemctl", "start", service_name])
print(f"{service_name} service has been started")
time.sleep(1)
elif "Active" in status:
print(f"{service_name} service is Active so stopping it now")
subprocess.run(["systemctl", "stop", service_name])
except OSError as ose:
print("Error while trying to do something with the service", ose)
pass
while True:
try:
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(22,GPIO.RISING,callback=minitor)
time.sleep(10)
finally:
GPIO.cleanup()
message = input("Press enter to quit\n\n")
GPIO.cleanup() # Clean up
不幸的是,只有第一次推送似乎有效,然后循环就开始工作,因此服务启动然后停止并启动...停止...
添加了上面的建议: 这是下面的脚本,不幸的是 if 和 elif 的条件似乎仍在循环中。
这是我按下按钮一次时发生的情况:
Ready
inactive
record service has been started
active
record service is Active so stopping it now
Ready
_____下面的脚本
import RPi.GPIO as GPIO
import time
import os
import subprocess
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
service_name = "record"
service_inactive = "inactive"
service_active = "active"
def minitor(channel):
try:
output = subprocess.run(["systemctl", "is-active", service_name], capture_output=True)
status = output.stdout.decode().strip()
if service_inactive in status:
print(status)
subprocess.run(["systemctl", "start", service_name])
print(f"{service_name} service has been started")
status = "active"
elif service_active in status:
print(status)
print(f"{service_name} service is Active so stopping it now")
subprocess.run(["systemctl", "stop", service_name])
status = "inactive"
except OSError as ose:
print("Error while trying to do something with the service", ose)
pass
while True:
try:
print("Ready")
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(22,GPIO.RISING,callback=minitor)
time.sleep(10)
finally:
GPIO.cleanup()
message = input("Press enter to quit\n\n")
GPIO.cleanup() # Clean up