为新手 Python 帖子道歉,但有点谷歌搜索,我仍然找不到我需要的东西。
我有以下 Pi Hat;https://github.com/modmypi/Jam-HAT,...我正在使用他们的文档来指导我;https://gpiozero.readthedocs.io/en/stable/recipes.html
我的想法很简单;
- 按下按钮时运行脚本
- 等待它运行,运行时显示闪烁的灯光
- 如果我按下另一个按钮,停止/终止脚本
但是,我被困在需要用按钮停止脚本的部分
#!/usr/bin/env python3
import gpiozero
import subprocess
from signal import pause
from time import sleep
button1 = gpiozero.Button(18)
button2 = gpiozero.Button(19)
green1 = gpiozero.LED(16)
green2 = gpiozero.LED(17)
red1 = gpiozero.LED(5)
red2 = gpiozero.LED(6)
script = ""
yellow1 = gpiozero.LED(12)
yellow2 = gpiozero.LED(13)
def kill_hello():
global script
script.kill()
print("Killed PID: ", script.pid)
red1.on()
sleep(.5)
red1.off()
red2.on()
sleep(.5)
red2.off()
def say_hello():
global script
green1.on()
sleep(.5)
green1.off()
green2.on()
sleep(.5)
green2.off()
script = subprocess.Popen(['/home/kali/hello.sh'])
print("Script PID: ", script.pid)
while script.poll() is None:
if not button2.when_pressed:
green1.on()
sleep(.5)
green1.off()
sleep(1)
button2.when_pressed = kill_hello
print("Press Ctrl & C to Quit")
try:
button1.when_pressed = say_hello
pause()
except KeyboardInterrupt:
print( "\n...Quit!")
我已经尝试了try
/except
那个while
循环所在的位置,但这也没有奏效(不像KeyboardInterrupt
)。它无法识别按钮已被按下,我假设它不在有效的 catch/else/something 块内。
请问有什么简单的跳出循环的建议吗?