1

I posted this question a few days ago but I did not get an exact answer all I got is some unexplained code from the user, Jimmy Fraiture

Here is the code that he provided:

from pynput.keyboard import Listener

def on_press(key):
    # check that it is the key you want and exit your script for example



with Listener(on_press=on_press) as listener:
    listener.join()

# do your stuff here
while True:
    pass

I got the code but I did not know how to use it like if I had a while loop how to I set up my space key to break this loop or to be the Keyboard Interrupt key please someone explain the code or provide an answer I would be very grateful

5
  • Does this answer your question? Is it possible to create a custom Keyboard Interrupt key in Python? Commented Jan 2, 2022 at 16:03
  • that's my previous querstion Commented Jan 2, 2022 at 16:04
  • 1
    This was autogenerated, because I flagged your post. You should not create duplicate questions. Regardless if you never get an answer, or you don't understand it. You keep it there, it is a waste of time for everyone to have two identical posts. If you don't like the answer, wait for a new one (in the original post), don't create a new one. Commented Jan 2, 2022 at 16:06
  • @Chrimle I am sorry but its kind of dead and also this is not the same question my question is to explain the code I provided because I don't know how to work it's not a duplicate question Commented Jan 2, 2022 at 16:10
  • 5 days ago? Nah, you haven't seen anything yet. There are questions that were posted years ago that still have no answer. Let's continue the discussion in the original thread. Commented Jan 2, 2022 at 16:22

1 Answer 1

1

is this what you are looking for?

import keyboard  # using module keyboard
from pynput.keyboard import Listener
    
    
def on_press(key):
    if keyboard.is_pressed("s"):  # if key 's' is pressed
        exit()
        


with Listener(on_press=on_press) as listener:
    listener.join()

to use while loop, you should remove the listener

import keyboard  # using module keyboard
from pynput.keyboard import Listener


while True:
    if keyboard.is_pressed("s"):  # if key 's' is pressed
        exit()
Sign up to request clarification or add additional context in comments.

4 Comments

that will only run my script if I press s
it will exit your script if you press s
sry I didn't test my code with while True... it didn't work until i removed that line
thank you this worked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.