0

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

SAM Acc
  • 38
  • 8
  • Does this answer your question? [Is it possible to create a custom Keyboard Interrupt key in Python?](https://stackoverflow.com/questions/70509265/is-it-possible-to-create-a-custom-keyboard-interrupt-key-in-python) – Chrimle Jan 02 '22 at 16:03
  • that's my previous querstion – SAM Acc Jan 02 '22 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. – Chrimle Jan 02 '22 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 – SAM Acc Jan 02 '22 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. – Chrimle Jan 02 '22 at 16:22

1 Answers1

0

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()
Feras Alfrih
  • 492
  • 3
  • 11