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
Answer from user8167727 on Stack Overflow
» pip install keyboard
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()
How do you hold down keys using the "Keyboard" module in python? - Stack Overflow
keypress - Key Presses in Python - Stack Overflow
How to make a script that will hold down a key for x seconds
Using keyboard in my program
Videos
Your thing of using keyboard.press('w') works, but it just doesn't show as it would when you hold a key. You can test this with some kind of game that uses "w" as a movement key, then running your script and you should move forwards for the said amount of time.
I think that the keyboard module is not as good of a choice to hold the key down as @Alderven mentioned, but it is great for detecting key presses instead if that helps your code. I would recommend using pyautogui. For example:
import pyautogui
import time
def accelerate():
pyautogui.keyDown('w') #holds the key down
time.sleep(5) #could be replaced with detecting an input
pyautogui.keyUp('w') #releases the key
return 0
Note: When you run the program, in the shell, there will not be a bunch of w's being typed as you'd expect, like this: wwwwwwwwwwwwwwwwwww. Instead, at least for me, only one w was pressed. I don't know why this occurs, although I can tell you that the key w is being pressed and this is NOT an error. I know this because I tried playing a game that involved pressing the key w (just an online web browser racing game), and the code worked. If you truly wanted the output "wwwwwwwwwwwwwwwwwwwwwwwwwww", then you can just use pyautogui's write() function:
pyautogui.write("wwwwwwwwwwwwwwwwwwwwwwwwwwwwww")
and there you go. Since you were referring to a racing game that doesn't involve getting a string of w's, this probably doesn't apply to your code.
If you want to wait for a certain input instead of holding down the key for a certain amount of time like I did, you could instead replace this:
time.sleep(5)
with this:
while True:
if keyboard.is_pressed('del')
break
You would have to import the keyboard module for that to work, since pyautogui cannot detect key presses.
Pynput is another great choice of module besides pyautogui, and there are a lot of other great Stack Overflow posts about pyautogui and pynput, so if this solution doesn't work, you should check those out if you haven't already. It would also help if you clarified about the context of the code, as mentioned by @OysterShucker. If it is a racing game AI, why does it need the user to input the del key so the AI knows when to release the w key, and why not automate it? Those are questions that I would recommend answering.
Install the pywin32 extensions. Then you can do the following:
import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want
Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start here, perhaps.
EDIT: Sending F11
import win32com.client as comctl
wsh = comctl.Dispatch("WScript.Shell")
# Google Chrome window title
wsh.AppActivate("icanhazip.com")
wsh.SendKeys("{F11}")
You could also use PyAutoGui to send a virtual key presses.
Here's the documentation: https://pyautogui.readthedocs.org/en/latest/
import pyautogui
pyautogui.press('Any key combination')
You can also send keys like the shift key or enter key with:
import pyautogui
pyautogui.press('shift')
Pyautogui can also send straight text like so:
import pyautogui
pyautogui.typewrite('any text you want to type')
As for pressing the "A" key 1000 times, it would look something like this:
import pyautogui
for i in range(999):
pyautogui.press("a")
alt-tab or other tasks that require more than one key to be pressed at the same time:
import pyautogui
# Holds down the alt key
pyautogui.keyDown("alt")
# Presses the tab key once
pyautogui.press("tab")
# Lets go of the alt key
pyautogui.keyUp("alt")
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.