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

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!

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:

Related

Reacting to Keypress

So, I want to make some simple code with Python on Visual Studio Code where when I press Enter, it registers and adds one to a variable, like...
if Enter pressed:
variable += 1
Here is what I did using the keyboard module-
import keyboard
variable = 0
while True:
if keyboard.is_pressed("Enter"):
variable += 1
print(variable)
You may have to download keyboard. For this run this command in your computer's command prompt/terminal-
py -m pip install keyboard
There is probably a better way to do this using keyboard.on_press_key() , as using is_pressed adds 1 to variable continuously as long as the key is pressed.
Hope my answer helps!
import keyboard
variable = 0
print("Please Press Enter key")
def on_press_event(event):
global variable
if event.name == "enter":
variable += 1
print("pressed count %d times"%variable)
keyboard.on_press(on_press_event)
while True:
pass

How to run a function (in Python) when user presses a specific key?

I tried this
from msvcrt import getch
while True:
key = ord(getch())
if key == 27: #ESC
print("You pressed ESC")
elif key == 13: #Enter
print("You pressed key ENTER")
but it works only in terminal, i want to run a function whenever user presses the key, even his curser in not in terminal, Please help...
Thank you!
What you're trying to do is not the easiest thing if you want to get it working correctly. If you have a window/widget in focus, using Qt and a QKeyEvent would be the easiest solution. However, if you want your input to be read globally/in other applications and not just from the terminal, you'll need to do something a bit more involved:
How to generate keyboard events in Python?

How to make Python execute a command when a key is detected to be pressed

I want to make Python execute my command when a key is pressed.
Like if "a" is pressed, the output should be:
A is pressed
or like it asks you to press key "a" and if you press it, its output should be Thanks for pressing the key! We are processing!
Sorry if I'm not clear, I'm actually not english
Assuming you don't need this to work when the window is not in focus, you should use getch from msvcrt to react to the keypresses immediately and then if and elif to distinguish the keys. I'd also recommend normalizing the case of the keys with upper or lower:
import msvcrt
while True:
key = msvcrt.getch().lower()
if key == b'a':
print("You've pressed A. I'll now do the thing I'm supposed to do when you press A.")
elif key == b'q':
print("Quitting...")
break
else:
print("You've pressed a key I don't know how to handle! PANIC!")
On Windows, you can call msvcrt.getch() to get the character of a single key press.
>>> import msvcrt
>>> msvcrt.getch()
b'a'
If using Windows OS, you can use msvcrt module as explained in other answers.
Or, you can simply get user input and check if it is corresponding key.
key = input('press key')
if key == 'a':
print('a is pressed')
But, user must press enter after the key.
Third option would be to use GUI library like Tkinter. Check this short tutorial for Events and Bindings in Tkinter.
You need some module that can handle key or mouse events. Depending what you want to achieve you can use for example Tkinter or even Pygame

Code that recognises a keypress in Python 3

Is there anyway for python 3 to recognise a keypress? For example, if the user pressed the up arrow, the program would do one thing whereas if the down arrow was pressed, the program would do something else.
I do not mean the input() function where the user has to press enter after the keypress , I mean where the program recognises the keypress as some as it was pressed.
Is this question too confusing? xD
Python has a keyboard module with many features. You Can Use It In Both Shell and Console.
Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard #Using module keyboard
while True: #making a loop
try: #used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('up'): #if key 'up' is pressed.You can use right,left,up,down and others
print('You Pressed A Key!')
break #finishing the loop
else:
pass
except:
break #if user pressed other than the given key the loop will break
You can set it to multiple Key Detection:
if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
#then do this
You Can Also Do Something like:
if keyboard.is_pressed('up') and keyboard.is_pressed('down'):
#then do this
It Also Detect Key For The Whole Windows.
Thanks.
I assume this is a gui program,
If using the built-in gui module Tkinter, you can use bind to connect a function to a keypress.
main.bind('<Up>', userUpkey)
Where userUpKey is a function defined in the current scope.

How to break a for loop when pressing space bar?

I want to break an infinite loop when pressing space bar. I dont want to use Pygame, since it will produce a window.
How can i do it?
I got an answer. We can use msvcrt.kbhit() to detect a keypress. Here is the code i wrote.
import msvcrt
while 1:
print 'Testing..'
if msvcrt.kbhit():
if ord(msvcrt.getch()) == 32:
break
32 is the number for space. 27 for esc. like this we can choose any keys.
Important Note: This will not work in IDLE. Use terminal.
Python has a keyboard module with many features. You Can Use It In Both Shell and Console.
Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard #Using module keyboard
while True: #making a loop
try: #used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed(' '): #if key space is pressed.You can also use right,left,up,down and others like a,b,c,etc.
print('You Pressed A Key!')
break #finishing the loop
except:
pass
You can set it to multiple Key Detection:
if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
#then do this
You Can Also Do Something like:
if keyboard.is_pressed('up') and keyboard.is_pressed('down'): #if both keys are pressed at the same time.
#then do this
Hope This Helps You.
Thanks.
Using space will be difficult because each system maps it differently. If you are okay with enter, this code will do the trick:
import sys, select, os
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print ("I'm doing stuff. Press Enter to stop me!")
print (i)
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = input()
break
i += 1
Source

Categories