Key press and wait for a fixed amount of time

2019-08-21 18:07发布

问题:

I want to make a python program wait 1'' per loop cycle (doesn't have to be real time so i'm fine with time.sleep(1) accuracy) after that I would like to know if a key was pressed and if so which one.

I found a solution here Python wait x secs for a key and continue execution if not pressed, but it's not exactly my problem. Since when the button is pressed I still want to wait the remainder of the second.

OS: Win 7 - but preferably crossplatform (at least to ubuntu)

I did try msvcrt but this seems rather clumsy to me and I was wondering if there doesn't exist any more straight foreward method. Surely I'm not the first one with this problem.

回答1:

Here's a simple example using threads.

import threading
import time

# define a thread which takes input
class InputThread(threading.Thread):
    def __init__(self):            
        threading.Thread.__init__(self)
        self.user_input = None

    def run(self):
        self.user_input = input('input something: ')

    def get_user_input(self):
        return self.user_input

# main
it = InputThread()
it.start()
while True:
    print('\nsleeping 1s and waiting for input... ')
    time.sleep(1)
    ui = it.get_user_input()
    if ui != None:
        print('The user input was', ui)
        it = InputThread()
        it.start()