How to use keyboard event as part of a conditional statement - python

I'm trying to make a program that outputs a key press event as a response to another keyboard event. How do I get it to use the particular value of the key pressed in a conditional statement? The codes I try seem to be skipping the conditional statement altogether.
Initially tried [if key == '1':], then tired by [if key == 1:]. Also tried various means of assigning [key] to a variable. Also tried [print('2')] instead of using [pyautogui.typewrite('2')]. Tried putting the code both in on_press(key) and in on_release(key).
`
import pyautogui
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(key))
def on_release(key):
print('{0} release'.format(key))
k = format(key)
if k == '1': #THIS IS THE PART I CAN'T GET TO WORK
pyautogui.typewrite('2', 0.5)
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
`
Expected to output '2' whenever I press '1' on the keyboard(in addition to the output of the keypress and keyrelease event). The output for the pressing of '1' doesn't work.

You can use keyboard library, in order to handle/create key events.
while True:
try:
if keyboard.is_pressed('1'):
print('{} is pressed'.format(1))
break
else:
pass
except:
break
the above code runs until 1 is received as a keypress. Upon pressing the key, 1 is pressed will be printed.
You can further use other functions of this library, in order to detect a key down even too.

The key parameter that your on_press/on_release receives is not the character string but rather a Key/KeyChar object, that's why you can't compare it directly with a string.
To access the keyboard input character, use key.char instead:
def on_press(key):
print("pressed '{}'".format(key.char))
Look at the example codes on pynput's documentation on how to capture non letter keys.

Related

How to detect keypress in python using keyboard module?

I am making a program in python to detect what key is pressed and based on my keyboard it will make a decision.
I want to implement it using keyboard module in python.
I would do something like this,
import keyboard
while True:
if keyboard.read_key() == 'enter':
print('Enter is pressed)
if keyboard.read_key() == 'q':
print('Quitting the program)
break
if keyboard.read_key() == 's':
print('Skiping the things')
But it doesn't work. When I execute this program, I have to press s twice to execute the "s" block.
Also, I have a problem that is after the execution is finished, it writes all the keys in my command prompt is it possible to fix that?
As per Keyboard documentation:
Other applications, such as some games, may register hooks that swallow all key events. In this case keyboard will be unable to report events.
One way to solve your problem with keyboard module is keyboard.wait('key')
# Blocks until you press esc
keyboard.wait('esc')
Something work around is as below:
import keyboard
keyboard.wait('enter')
print('Enter is pressed')
keyboard.wait('q')
print('Quitting the program')
keyboard.wait('s')
print('Skiping the things')
As Far I Know There is only one efficient way to Detect user input weather it keybored or mouse input Which is library called pynput ......
from pynput.keyboard import Key , Listener , Controller
keyboard = Controller()
DoubleShot=False
shot=False
def on_press(key):
global DoubleShot
global shot
if Key.num_lock == key:
print("activate")
DoubleShot=True
if DoubleShot:
if Key.shift == key:
shot = not shot
if shot:
keyboard.press(Key.shift)
keyboard.release(Key.shift)
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press , on_release=on_release) as listener:
listener.join()
i create this for a game to shoot multiple time on 'shift' clicked
code activate only when ' numlock ' clicked.....
Controller is for clicking any key you want
Note:
In My case infinity looping was a problem that's why shot variable is there to stop looping

I want to check if ANY key is pressed, is this possible?

How do I check if ANY key is pressed?
this is how I know to detect one key:
import keyboard # using module keyboard
while True: # making a loop
if keyboard.is_pressed('a'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
How do I check if any key (not just letters) is pressed?
For example, if someone presses the spacebar it works, the same for numbers and function keys, etc.
while True:
# Wait for the next event.
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN:
print(event.name) # to check key name
Press any key and get the key name.
it can be done using the msvcrt module as the following:
import msvcrt
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
break
or the keyboard, although i am not sure of how of a good practice this code is:
import keyboard
while True:
try:
print(keyboard.read_key())
break
except:
pass
if this is bad practice please informe me in the coments so i can mark it as unfavored
thankyou.
Correct solution in Windows is to use msvcrt
Please check thread here:
How to detect key presses?
I think somehow should be possible also with builtin input() command.
Have a nice day!

How to run multiple loops simultaneously in Python?

I'm trying to do something that seems very basic, but I keep getting myself stuck inside of loops that don't allow me to perform other actions. For example:
def functionOne():
if x key is pressed:
do something
def functionTwo():
if y key is pressed:
do something else
def functionThree():
if z key is pressed:
do something else
def main():
functionOne()
functionTwo()
functionThree()
main()
I was trying to to do while loops in each function, but that locks each function in its own loop cycle. I essentially want my program to run until I press a very specific key combination from the Python keyboard package. I assume loops are the way to keep a program running?
Or say, if I wanted to implement this on a GUI, and only exit the program when hitting the quit button on the GUI, while waiting for the other buttons to be clicked to do something else.
I'm aware that I could do a giant main loop with conditions nested inside one another, but I'm hoping there is a cleaner way to do this involving functions.
Try this way:-
def functionOne(key):
if key != 'x':
return
if x key is pressed:
do something
def functionTwo(key):
if key != 'y':
return
if y key is pressed:
do something else
def functionThree(key):
if key != 'z':
return
if z key is pressed:
do something else
def main():
while key != 'q':
key = input("Enter the key :")
functionOne(key)
functionTwo(key)
functionThree(key)
main()
Other than that you can use threading if functions are computationally heavy and key input interval is smaller than the computational time of the functions.
you could take advantage of pynput
first install it
pip install pynput
then you can achieve what you are looking for like the following example (obtained from pynput documentation):
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = keyboard.Listener(
on_press=on_press,
on_release=on_release)
listener.start()

Typing Test, how to make input save when spacebar is pressed

My friend and I were building a typing test. We are using the input() function in python to get input from the user. The problem is that we have to press enter to make the input save and we want that button to be spacebar instead. Is there any way to do this or another module we could use to solve this problem?
for i in range(num_words):
print(final_sentence)
print("")
typed_word = input("Type>")
words_to_list(typed_word)
os.system('clear')
You should probably use other modules like keyboard or pynput because input() detects whole strings while those modules detect key presses. Detect key presses, print them, and stop when Key.space (in pynput case) is pressed.
Something like this:
from pynput.keyboard import Listener
from pynput.keyboard import Key
words=''
def on_press(key):
if key==Key.space:
listener.stop()
print (words)
def on_release(key):
global words
typed = str(key).replace("'", "")
words = words + typed
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
This code detects key press using pynput.keyboard's handy listener, and adds it to words until space is pressed. When space is pressed the script stops the listener and prints the typed sentence.

How can I ignore all user inputs for duration of function run?

I have a Python module that listens for a key combination using pynput then, once it's pressed, it types a string into a text program.
It works great! Except...
In the example below, the user's key combo is set to shift + space. This makes a lot of sense and will likely be the most common chosen key command for Windows users running my program. The trouble is, while the shift key is held down it changes what pynput types. Instead of 01/20/2019, it will type )!/20/2019.
I need a way to disable the keyboard until pyautogui is finished typing the string. Thanks a lot for your help!!!
Bonus question: I can't seem to get a result when the key combination includes a ctrl key. Key.ctrl simply fails to ever trigger, whilst other keys work fine.
from pynput.keyboard import Key, Controller, Listener
import time
keyboard = Controller()
def insert(): # check line 1 of config file
keyboard.type('01/20/2019')
# The currently active modifiers
current = set()
def on_press(key):
if key in COMBINATION:
current.add(key)
if all(k in current for k in COMBINATION): # I don't know what this k in current for k shit is.
current.remove(key)
insert() # run insert
if key == Key.esc:
listener.stop()
def on_release(key):
try:
current.remove(key)
except KeyError:
pass
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
``
You can use pyautogui.keyUp("shift") before you type.
def insert():
f=open('tc.txt')
line=f.readlines()
insert.timestamp=(line[0])
time.sleep(.1)
pyautogui.keyUp("shift")
pyautogui.typewrite(insert.timestamp)

Categories

Resources