【问题标题】:How to stop a while loop with a user input without interrupting the program?如何在不中断程序的情况下停止用户输入的while循环?
【发布时间】:2021-03-21 23:29:33
【问题描述】:

如何无限循环 5 个 LED 灯以保持一个接一个地打开,直到用户输入一些内容?我不希望用户输入中断循环。现在一切正常,只是在循环中间输入会中断程序。

import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

print("Press h to exit the program")

while True:

    GPIO.setup(19,GPIO.OUT)
    GPIO.output(19,True)
    time.sleep(0.5)
    GPIO.output(19,False)

    GPIO.setup(26,GPIO.OUT)
    GPIO.output(26,True)
    time.sleep(0.5)
    GPIO.output(26,False)

    GPIO.setup(22,GPIO.OUT)
    GPIO.output(22,True)
    time.sleep(0.5)
    GPIO.output(22,False)

    GPIO.setup(27,GPIO.OUT)
    GPIO.output(27,True)
    time.sleep(0.5)
    GPIO.output(27,False)

    GPIO.setup(17,GPIO.OUT)
    GPIO.output(17,True)
    time.sleep(0.5)
    GPIO.output(17,False)

    x = input("")

    if (x == "h"):
        print("Exiting the program")
        break

    GPIO.setwarnings(False)

GPIO.cleanup()

【问题讨论】:

  • 您的问题与树莓派无关。在这里提出问题时,最好提供一个可运行的 minimal reproducible example 并把不相关的所有内容排除在外。

标签: python while-loop user-input


【解决方案1】:

您可以使用第三方keyboard 库轻松完成此操作。

import keyboard

while True:
    print(1)
    print(2)
    print(3)
    print(4)
    if keyboard.is_pressed("h"):
       break

【讨论】:

  • 感谢您的帮助。我尝试了您的建议,但出现 ModuleNotFoundError: No module named 'keyboard' 错误。有没有办法来解决这个问题?谢谢
  • 由于它是第三方库,您需要先安装它。 pip install keyboard
  • 显然我必须做 sudo pip3 install keyboard 虽然我仍然有错误。
  • Traceback (last last call last): raise ImportError('You must be root to use this library on linux.') ImportError: You must be root to use this library on linux.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
  • 2021-11-27
  • 2018-03-23
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多