在python中,如何在没有按下某个键之后执行操作?

2024-04-19 12:05:54 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我目前运行Raspbian Jessie的Raspberry Pi 3的代码:

#!/usr/bin/python
import time
import os
os.system('cls' if os.name == 'mt' else 'clear')
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
GPIO.output(18,GPIO.HIGH)
text = raw_input('Success! LED on. Press Enter to turn off...')
if text == "":
        print('LED off.')
        GPIO.output(18,GPIO.LOW)
else:
        time.sleep(10)
        os.system('cls' if os.name == 'mt' else 'clear')
        print('Auto turn off in')
        time.sleep(1)
        print('5')
        time.sleep(1)
        print('4')
        time.sleep(1)
        print('3')
        time.sleep(1)
        print('2')
        time.sleep(1)
        print('1')
        time.sleep(1)
        print('LED off.')
        GPIO.output(18,GPIO.LOW)

它当前所做的是,如果您按另一个键,然后按回车键,它将触发第二个代码序列,但我希望这样,当一个键10秒未按时,第二个代码序列将运行,当您按回车键时,第一个代码序列将运行。有可能吗?你知道吗


Tags: 代码importoutputledgpioiftimeos
1条回答
网友
1楼 · 发布于 2024-04-19 12:05:54

您需要在使用时间模块倒计时时测试按键,因此应该使用线程或多处理。如果您不介意安装一个名为“getch”的小模块,那么就更容易了,否则请查看this question获取字符。这里使用线程和Getch是python2的代码。你知道吗

import getch
import threading

light_on = True
def countdown(count_from):
  global light_on
  print("Light will turn off in...")
  x = count_from
  while not light_on:
    print x
    time.sleep(1)
    x -= 1
  quit(0)

def testkey(keyname):
  global light_on
  while 1:
    char = getch.getch()
    if char == keyname:
      light_on = True

threading.Thread(target=testkey, args=('\n')).start()
while 1:
  if light_on: print("ON!")
  light_on = False
  threading.Thread(target=countdown, args=(10)).start()

这是一个最小版本的代码,您应该能够找出如何在您的程序中使用这个。程序将打印灯亮了,然后从十开始倒计时。必须按Enter键或Return键才能将light_on变量设置为True,并保持程序运行。你知道吗

有关如何安装“getch”的更多信息,请参阅PyPi's documentation.

相关问题 更多 >