How to "continue" OR "exit" the program by pressing keys

Leo picture Leo · Jun 7, 2018 · Viewed 9.4k times · Source

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!

Answer

Murali picture Murali · Jun 7, 2018

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