How to "continue" OR "exit" the program by pressing keys
14,145
You can use Keyboard module to detect keys pressed. It can be installed by using pip
. You can find the documentation here. Keyboard API docs
pip install keyboard
check the below code to understand how it can be done.
import sys
import keyboard
a=[1,2,3,4]
print("Press Enter to continue or press Esc to exit: ")
while True:
try:
if keyboard.is_pressed('ENTER'):
print("you pressed Enter, so printing the list..")
print(a)
break
if keyboard.is_pressed('Esc'):
print("\nyou pressed Esc, so exiting...")
sys.exit(0)
except:
break
Output:
Author by
Leo
Updated on June 05, 2022Comments
-
Leo over 1 year
Lets say I have 2 lines of code like this:
a = [1 , 2 , 3 , 4] print (a)
Now I want to add something to this code to give the user 2 options:
1: press "Enter" to continue.
In this case the code should print "a"
2: press "Esc" to exit the program.
In this case the program should be stopped (e.g. exit the code).
I need to mention that I only want to use these 2 keys (Enter&Esc) NOT any key
I have been palying with raw_input and sys.exit but it did not work. Any idea how I can do it in this example? Thanks!
-
Leo over 5 yearsThanks for your response but I do not think you have ever run your code even once because it does not even work! In addition I do not think you read my question carefully. I indicated that python asks user to press Enter or Esc key to continue or exit (like: "press Enter to continue or press Esc to exit"). That is why I mentioned raw.input method.
-
Leo over 5 yearsAny better idea? Thanks!
-
Murali over 5 yearscheck the usage of raw_input here. docs.python.org/2/library/functions.html#raw_input, it takes the input from the user and converts it to string so by using that method you can't detect key pressed by user unless if it comes to you as string in raw_input function.
-
Murali over 5 yearsI ran and tested my code on my linux machine, if its not working for you then please mention the problem you're facing, I will be happy to help you.
-
Murali over 5 yearsI edited my answer to display your requirement and also please check the attached screenshot of the output for your reference, raw_input can't able to detect keyboard events like enter or escape, it can only take user input in the form of strings after user pressed enter.