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

Susan Sarandon
Release: 2024-10-30 12:47:02
Original
269 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template