2

I have the following 2 extracts of starting pynput's keyboard listener.

Source

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()
# ...or, in a non-blocking fashion:
listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()

Im using Python 3.10.10

I tried using both of them but only the first one is working properly,its reading my input and keeps running. The second one just ends the program without reading any input at all. It also doesn't provide any output.

No error message is given.

What is the difference between those 2 and why is only the first one working?

1 Answers1

2

The documentation you've linked includes a line after the code snippet:

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

# ...or, in a non-blocking fashion:
listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()

When using the non-blocking version above, the current thread will continue executing.

And according to this answer:

The with statement is blocking the main thread. Using start instead of with / join you create a non-blocking thread allowing the main loop to start.

I can't tell you why the blocking version works without knowing how you've structured the rest of your program, but I hope this clarifies the difference between the two.