简体   繁体   中英

How to force an “enter” on Python's input after x seconds?

That's my code:

while True:
    prompt = "Enter code: "
    code = input(prompt)
    if code == "123":
        open_door()

The program automatically opens a door when the user types "123" on a USB keypad that does not have the "Enter" key.

Since my keypad does not have the "Enter" key, I want to force an "Enter" after 5 seconds. 5 seconds after the beginning of the loop, the program hits "Enter" no matter what has been typed. If by any chance code get to hold successfully "123" when "Enter" is hit, the door is open; otherwise, there'll be a second chance.

How can I do that?

Addt'l info: this program will run in a Raspberry Pi 3, but I am using Mac for the tests.

Please note that "buying a keypad that has an "Enter" key" is not possible, because it's not actually a keypad; it's a RFID reader that works exactly like a keypad. I preferred to use "keypad" for understandability.

This worked fine for me:

import pyautogui
import threading

def break_input():
    time.sleep(5)
    pyautogui.press('enter')

while True:
    threading.Thread(target=break_input).start()
    prompt = "Enter code: "
    code = input(prompt)
    if code == '123':
        open_door()

You will need the third-party library pyautogui .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM