簡體   English   中英

在python中沒有按下鍵后如何執行操作?

[英]How to do an action after a key hasn't been pressed in 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)

enter, it triggers the second sequence of code, but I want it so that when a key hasn't been pressed for 10 seconds, the second sequence of code is run and when you press Enter the first sequence of code is run. 當前的作用是,如果您按下另一個鍵輸入,它會觸發第二個代碼序列,但是我想要它,以便當一個鍵沒有被按下10秒鍾時,第二個代碼序列就會運行並在您按下時輸入第一個運行的代碼序列。 那可能嗎?

您需要在使用時間模塊倒計時時測試按鍵的按下,因此您應該使用線程處理或多處理。 如果您不介意安裝一個名為“ getch”的微型模塊,那么它會更容易,否則請查看此問題以獲取字符。 這里是使用Threading和Getch的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並保持程序運行。

有關如何安裝“ getch”的更多信息,請參見PyPi的文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM