0

为新手 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 块内。

请问有什么简单的跳出循环的建议吗?

4

1 回答 1

0

似乎问题在于单个进程占用了 Python,因此创建多个线程有所帮助;

#!/usr/bin/env python3

import gpiozero
import subprocess
import time
import threading
from signal import pause

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)
switch  = True

def blink():
    def run():
        while (switch == True):
            green1.on()
            time.sleep(.2)
            green1.off()
            time.sleep(.2)
            if switch == False:
                break
    thread = threading.Thread(target=run)
    thread.start()

def switchon():
    global switch
    global script
    switch = True
    print('switch on')
    script = subprocess.Popen(['/home/kali/hello.sh'])
    blink()

def switchoff():
    global switch
    global script
    print('switch off')
    script.kill()
    switch = False

try:
    button1.when_pressed = switchon
    button2.when_pressed = switchoff
    pause()
except KeyboardInterrupt:
    print( "\n...Quit!")

于 2020-11-11T12:06:32.897 回答