Home  >  Article  >  Backend Development  >  How to Implement a Keyboard Handler Using a BlockingQueue in Python?

How to Implement a Keyboard Handler Using a BlockingQueue in Python?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 12:47:02204browse

How to Implement a Keyboard Handler Using a BlockingQueue in Python?

One of the simplest ways of implementing a keyboard handler that will call a function every time it receives a key press (this will work on both Linux and Windows) is to use a BlockingQueue and a thread that will place the key in the queue when it is pressed, and the queue will get it later in your code. Here's a simple implementation:

<code class="python">import queue
import sys
import threading

# blocking
q = queue.Queue()
last_input = 0.0


def input_thread(q):
    global last_input
    while True:
        ch = sys.stdin.read(1)
        last_input = time.time()
        print("got key: '{}'".format(ch))
        q.put(ch)

if __name__ == '__main__':
    t = threading.Thread(target=input_thread, args=(q,))
    t.daemon = True
    t.start()

    last_input_time = last_input

    while True:
        if not q.empty() and (time.time() - last_input) < 5:
            print("polling '{}' in the queue".format(q.get()))

        if time.time() - last_input_time > 5:
            print("nothing in the queue for a while")
            raise RuntimeError("no input")</code>

The above is the detailed content of How to Implement a Keyboard Handler Using a BlockingQueue in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn