Home > Blockchain >  Is it possible to create a custom Keyboard Interrupt key in Python?
Is it possible to create a custom Keyboard Interrupt key in Python?

Time:01-03

I am writing a python script that has an infinite loop and for me to stop I use the usual Keyboard Interrupt key Ctrl c but I was wondering if I can set one of my own like by pressing space once the program can stop I want it to have the same function as Ctrl c So if it is possible how can I assign it?

CodePudding user response:

You can add a listener to check when your keys are pressed and then stop your script

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

CodePudding user response:

For creating the keyboard listener (Based on Jimmy Fraiture's answer and comments), and on Space stop the script using exit() (Suggested here)

from pynput.keyboard import Listener

def on_press(key):
    # If Space was pressed (not pressed and released), stop the execution altogether 
    if (key == Key.space):
        print('Stopping...')
        exit()

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


while True:
    print('Just doing my own thing...\n')
  • Related