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

问题描述:

这里是我目前有上运行Raspbian杰西我树莓派3代码:如何在python中没有按下按键之后执行操作?

#!/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秒钟时,第二个代码序列就会运行,当你按下Enter键时,第一个代码序列被运行。那可能吗?

+0

'raw_input'块程序,所以你必须在线程中运行它 - 或者找到在互联网功能'的getchar()'/'GET_CHAR()'它检查键盘,但不会阻止它,然后你可以循环检查键盘和时间。 – furas

+0

你是什么意思序列? – thesonyman101

+0

@ thesonyman101第一个序列是“if”,第二个序列是“else”。 –

您需要在使用时间模块倒计时的同时测试按键,以便使用线程或多处理。如果你不介意安装一个名为“getch”的小模块,那么它更容易,否则看看this question获得一个角色。使用线程和残培这里是Python的2

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并保持程序运行。

有关如何安装“残培”的更多信息看PyPi's documentation.