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:

enter image description here

Share:
14,145
Leo
Author by

Leo

Updated on June 05, 2022

Comments

  • Leo
    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
    Leo over 5 years
    Thanks 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
    Leo over 5 years
    Any better idea? Thanks!
  • Murali
    Murali over 5 years
    check 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
    Murali over 5 years
    I 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
    Murali over 5 years
    I 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.