Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.