Detect enter key pressed python - python

is there a way to detect if ENTER is pressed with python? I was able to detect letters with win32api using win32api.GetAsyncKeyState(ord('H')) , but couldn't do the same with enter. I need to run the code on windows.
Thanks.

You can use keyboard lib.
pip3 install keyboard
import keyboard
if keyboard.read_key() == "enter":
...
https://github.com/boppreh/keyboard

Related

How to press Enter using PyAutoGUI

please tell me how to press the Enter button using the PyAutoGUI library. I've tried everything, but nothing is pressed. Can you suggest how to do it?
Use pyautogui.press(“enter”) or pyautogui.hotkey(“enter”)
for pressing 3 times:
use pyautogui.press(“enter”, presses=3)
or
for i in range(3):
pyautogui.press(“enter”)
for pressing lots of keys:
pyautogui.press([“enter”, “shift”])
or
for key in [“enter”, “shift”]:
pyautogui.press(key)
dispatch user holding down the key until keyup:
pyautogui.keyDown(“enter”)
and for keyup:
pyautogui.keyUp(“enter”)
and also one thing, if you’re used keyDown, you can still use pyautogui.press(“enter”) too :D
If you want to know more go to https://pyautogui.readthedocs.io/en/latest/keyboard.html
Short answer
pyautogui.press('enter')
or
pyautogui.write('\n')
source
If not working, could be because the mouse cursor is not on the desired place, maybe you would need to first click over the app you want to enter with for example pyautogui.click(100, 200); where (100,200) are the X,Y coordinates of screen, you will need to locate where do you need that enter.
For more details, you could see this
on windows I could never get Pyautogui key presses to work. I had to use pywinauto instead. I would still use pyautogui for finding images and typing our characters but used pywinauto to press keys.
from pywinauto.keyboard import send_keys
send_keys('{ENTER}')
https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html
I had a problem like you,but i solved it by turning the keyboard language from Chinese to English ,so the enter_press is useful to send message but not write message

How can I find if someone is pressing a key repeatedly in python?

im trying to make a reaction test thing in python. basically you press enter to start and then at a random point between 5 seconds it will stop and you have to click enter again. it finds the time that it took for you to press enter. but i need a way to stop the person from just holding enter and cheating the program. help??
You could do also do this as a key release.
from pynput import keyboard
def on_release(key):
print('Key released: {0}'.format(key))
# Collect events until released
with keyboard.Listener(on_release=on_release) as listener:
listener.join()
Make sure to also install the module:
pip install keyboard

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

Create Keyboard Shortcut?

I am searching for a way to create a cross-platform keyboard shortcut in Python. Such that when I press something like Ctrl+C or Ctrl+Alt+F, the program will run a certain function.
Does there exist such method or library?
I don't know is it possible to send combinations of Ctrl and/or alt. I tried couple of times but I think it doesn't work. (If someone has any other information please correct me). What you can do is something like this:
from msvcrt import getch
while True:
key = ord(getch())
if key == 27: #ESC
PrintSomething()
def PrintSomething():
print('Printing something')
this will run a scrpit every time you press ESC although it will only work when you run it in command prompt.
You can create a listener for keypress event by pynput library.
this is a simple code that run a function when press CTRL+ALT+H keys:
from pynput import keyboard
def on_activate():
print('Global hotkey activated!')
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<ctrl>+<alt>+h'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()
Try keyboard. It can be installed with pip install keyboard, and the Ctrl + C example can be accomplished with the syntax:
import keyboard
keyboard.add_hotkey("ctrl + c", print, args=("Hello", "world!"))

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.

Categories