» pip install keyboard
How Can i Simulate Key Presses In Python ?
python - How to detect key presses? - Stack Overflow
How to detect keypress in python using keyboard module? - Stack Overflow
Using keyboard in my program
Videos
Hi, i want to simulate key presses (and shortcuts) in Python on Linux. I have already looked into pynput, and while it works, it is not global. what i am trying to do is as follows: i am using kde plasma as a desktop environment, and so in kde plasma settings, i made a shortcut (ctrl + a) that triggers the audio applet. so when i press that shortcut, the audio applet will open up. now what i want to achieve is that when a specific condition happens in my program, i open the applet.
from pynput.keyboard import Key, Controller
keyboard = Controller()
key = "a"
key2 = Key.ctrl
keyboard.press(key)
keyboard.press(key2)
keyboard.release(key)
keyboard.release(key2)
and while it works, but it is not global, and what i mean by this is that when i run this script i see "a" in the terminal as if i pressed it in the terminal, and the applet does not open up.
so any help on how can i achieve this ?
EDIT: i found a so much easier solution that works like a charm. There is a linux package called xdotool that stimulates mouse and keyboard stuff. So with this simple command xdotool key ctrl+a . It works perfectly. So i would just use an os.system and execute this.
Python has a keyboard module with many features. 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('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
except:
break # if user pressed a key other than the given key the loop will break
For those who are on windows and were struggling to find an working answer here's mine: pynput.
Here is the pynput official "Monitoring the keyboard" source code example:
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
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()
The function above will print whichever key you are pressing plus start an action as you release the 'esc' key. The keyboard documentation is here for a more variated usage.
Markus von Broady highlighted a potential issue that is: This answer doesn't require you being in the current window to this script be activated, a solution to windows would be:
from win32gui import GetWindowText, GetForegroundWindow
current_window = (GetWindowText(GetForegroundWindow()))
desired_window_name = "Stopwatch" #Whatever the name of your window should be
#Infinite loops are dangerous.
while True: #Don't rely on this line of code too much and make sure to adapt this to your project.
if current_window == desired_window_name:
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
First of all, you forgot to close the strings on lines 4 and 6.
But your main issue is that you call keyboard.read_key() once for each arm of your if statement. This makes your code wait for a keypress, check if it's 'enter', then wait for another keypress, check if it's 'q', and so on.
What you should do is save the key to a variable, then check the variable. It should look something like this:
import keyboard
while True:
key = keyboard.read_key()
if key == 'enter':
print('Enter is pressed')
if key == 'q':
print('Quitting the program')
break
if key == 's':
print('Skiping the things')
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')
I know that it was a year ago, but I have found this question today.
Sooo, according to the Keyboard API:
keyboard.press(hotkey) emulates pressing a hotkey on keyboard.
keyboard.release(hotkey) emulates releasing a hotkey on keyboard.
A hotkey is an key number, key name, or combination of two or more keys.
keyboard.press_and_release(hotkey) or keyboard.send(hotkey) emulates pressing and releasing a key or hotkey.
Pressing and releasing behaviour depends on values of do_press and do_release when using keyboard.send().
For example:
keyboard.send('space', do_press=True, do_release=True)
will emulate pressing and releasing space key, but:
keyboard.send('space', do_press=False, do_release=True)
will emulate only releasing space key.
keyboard.is_pressed(key) returns True if a specified key has been pressed, and False otherwise
Hope I've helped!
keyboard.is_pressed() is basically checking if a certain key code is pressed. If you put keyboard.is_pressed('x'), it will basically check if the letter x is being pressed, using its keycode, 88.
On the other hand, I can see that the majority of the script works, checking if 'u' is pressed, and then 'elseif's appear fine, but I don't know fully why this part, keyboard.release('w'), is at the very bottom. I suggest either removing this line lines:
else: # (this line is fine)
print(4) # (this line is fine)
keyboard.release('w')
and adjusting the lines a wee bit for this completed code!
while True:
if keyboard.is_pressed('u'):
keyboard.press('w')
keyboard.release('w')
print(0)
elif keyboard.is_pressed('j'):
#keyboard.press_and_release('s')
print(1)
elif keyboard.is_pressed('k'):
#keyboard.press_and_release('d')
print(2)
elif keyboard.is_pressed('h'):
#keyboard.press_and_release('a')
print(3)
else:
print("No Key pressed.") #alternatively, you can keep it as print(4).
Hope this helped, despite being over 4 years late.