我正在尝试制作一个Python脚本,该脚本在开关打开(LOW)时启动mdk3,在关闭(HIGH)时将其杀死。但是,无论开关处于什么位置,mdk3命令始终在启动脚本时启动。如预期的那样,在开关处于ON位置的情况下启动脚本,然后在运行时将其关闭,这会杀死该命令。但是,将其重新打开时不会再次开始运行。有趣的是,设置为打印的文本功能完全符合预期。我的代码如下:
import RPi.GPIO as GPIO
import time
import subprocess
import os
import signal
FSU = 'sudo mdk3 mon0 d'
pro = 'subprocess.Popen(FSU, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)'
# tell the GPIO module that we want to use the chip's numbering scheme
GPIO.setmode(GPIO.BCM)
# Set up GPIO16 as an input with internal pull-up resistor to hold it HIGH until it is pulled down to GND by the connected switch
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)
running = False
while True:
if GPIO.input(16) == GPIO.LOW:
if running == False:
print('Button was pushed!')
pro
running = True
time.sleep(0.1)
elif running == True:
print('The process is running.')
time.sleep(0.1)
elif GPIO.input(16) == GPIO.HIGH and running == True:
os.killpg(os.getpgid(pro.pid), signal.SIGTERM)
print('Process killed.')
running = False
time.sleep(0.1)
elif running == False:
print('The process is not running.')
time.sleep(0.1)
else:
print('Critical error.')
time.sleep(0.1)
之所以使用我自己的循环来轮询GPIO引脚而不是RPi.GPIO库中内置的事件检测,是因为它除了引起问题外,没有造成任何其他问题,而我自己做起来似乎更简单。任何帮助,将不胜感激。
编辑:我不确定为什么我没有想到要将该报价放在引号中。现在,它不会在脚本启动时运行,而只能运行一次。如下所示:我在关闭脚本的情况下启动了脚本,但脚本没有运行(按预期)。我将其打开并运行。我将其关闭并成功杀死了脚本。但是,将其重新打开不会重启脚本。抱歉,这是一个不好的解释。
subprocess.Popen()
会在调用后立即启动该进程,并返回该进程。因此,您可以在需要运行时只需再次调用同一函数即可在循环中再次启动该过程。
稍微修改您的代码:
import RPi.GPIO as GPIO
import time
import subprocess
import os
import signal
proc = subprocess.Popen(FSU, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
FSU = 'sudo mdk3 mon0 d'
# tell the GPIO module that we want to use the chip's numbering scheme
GPIO.setmode(GPIO.BCM)
# Set up GPIO16 as an input with internal pull-up resistor to hold it HIGH until it is pulled down to GND by the connected switch
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)
running = False
while True:
if GPIO.input(16) == GPIO.LOW:
if running == False:
print('Button was pushed!')
# declare the proc variabe again and also start the process
proc = subprocess.Popen(FSU, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
running = True
time.sleep(0.1)
elif running == True:
print('The process is running.')
time.sleep(0.1)
elif GPIO.input(16) == GPIO.HIGH and running == True:
os.killpg(os.getpgid(pro.pid), signal.SIGTERM)
print('Process killed.')
running = False
time.sleep(0.1)
elif running == False:
print('The process is not running.')
time.sleep(0.1)
else:
print('Critical error.')
time.sleep(0.1)