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?
-
Well, this is more a question of setting up your terminal/IDE/whatever. Some might have the functionality to rebind keys.KTibow– KTibow2021-12-28 15:49:27 +00:00Commented Dec 28, 2021 at 15:49
-
See here is my problem I want to be set within the script so whoever has access to the code will press the same universal button to sop the codeSAM Acc– SAM Acc2021-12-28 15:51:36 +00:00Commented Dec 28, 2021 at 15:51
-
There are many ways you could go about this: 1. Set up your terminal/IDE (I might be able to help) 2. Create a global keybind (I can recommend a library and how to use it) 3. Look at STDIN in a thread (No clue how you would do this)KTibow– KTibow2021-12-28 15:54:07 +00:00Commented Dec 28, 2021 at 15:54
-
By that you mean create like a hotkey for the taskSAM Acc– SAM Acc2021-12-28 15:55:28 +00:00Commented Dec 28, 2021 at 15:55
-
Which one are you talking about?KTibow– KTibow2021-12-28 15:56:26 +00:00Commented Dec 28, 2021 at 15:56
|
Show 2 more comments
3 Answers
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
5 Comments
SAM Acc
So in the def function I put the key I want to assign?
SAM Acc
It's not working can you apply it to this code so I can see how this works online-python.com/L9lTSey4GH
Jimmy Fraiture
def on_press(key): if key == keyboard.Key.esc: raise KeyboardInterrupt
Jimmy Fraiture
You cannot make it work on an online executor since keys are manage by the navigator
SAM Acc
yeah just write the code even if it doesn't work because I can't seem to understand how I am supposed to arrange the code
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')
3 Comments
SAM Acc
thank you I will try this now and keep you posteed
SAM Acc
that did not work
Chrimle
As suggested here, you will have to create another thread to be responsible for the listener. But that makes me think you will have to use some of the other "stop"-commands I linked in my answer, because now you not only want to kill the listener, but also the thread doing your while-loop.