Key Presses in Python
Asked Answered
M

11

43

Is it possible to make it appear to a system that a key was pressed, for example I need to make A key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.

A better way to put it, I need to emulate a key press, I.E. not capture a key press.

More Info (as requested): I am running windows XP and need to send the keys to another application.

Moldboard answered 25/9, 2008 at 22:58 Comment(1)
It's probably possible - but where do you want the key presses to go? To another application? That would probably be a case of understanding your platform's windowing toolkit and sending the right messages to the right window. Clarify your requirements, and I'm sure we can help out.Zinovievsk
V
51

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}")
Vice answered 25/9, 2008 at 23:9 Comment(1)
This is by far the best answer. The reason? It doesn't need any extra package to be installed! And most importantly, it can be compiled to EXE with 'py2exe' w/o problem, whereas 'pynput' and 'pyautogui' produce problems. If only I could upvote you multiple times! :)Similarity
B
49

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")
Beaudoin answered 21/10, 2015 at 0:57 Comment(3)
Awesome, exactly what I needed... and it allows to capture screenshots as well.Pewee
Just an FYI that this module depends on pyobjc which has an enormous number of dependencies. Just to keep in mind when you install it.Heterogeneity
I agree with @numbermaniac. E.g. 'py2exe' has a problem in converting to EXE PY files using this package most probably because of the large number of depencencies. Also, someone has to install an extra minor package whereas the end result can be achieved with 'win32com', which comes with Python (or major package PyWin32.)Similarity
C
13

Check This module keyboard with many features.Install it, perhaps with this command:

pip3 install keyboard

Then Use this Code:

import keyboard
keyboard.write('A',delay=0)

If you Want to write 'A' multiple times, Then simply use a loop.
Note:
The key 'A' will be pressed for the whole windows.Means the script is running and you went to browser, the script will start writing there.

Colbert answered 26/6, 2017 at 10:12 Comment(2)
Is there a way to use this library to press and hold the key for a number of seconds. I don't want multiple keypress, just one until its released. I've looked through the API docs and cant find exactly what I'm looking for - plenty of stuff with button combos.Traction
What about keyboard.press(hotkey)? It "presses and holds down a hotkey", see: github.com/boppreh/keyboard#keyboardpresshotkeyMalikamalin
P
11

AutoHotKey is perfect for this kind of tasks (keyboard automation / remapping)

Script to send "A" 100 times:

Send {A 100}

That's all

EDIT: to send the keys to an specific application:

WinActivate Word
Send {A 100}
Primrose answered 25/9, 2008 at 23:3 Comment(1)
This works, but does not answer the question, so I will vote it up but I can't accept it as the answer.Moldboard
S
3

If you're platform is Windows, I wouldn't actually recommend Python. Instead, look into Autohotkey. Trust me, I love Python, but in this circumstance a macro program is the ideal tool for the job. Autohotkey's scripting is only decent (in my opinion), but the ease of simulating input will save you countless hours. Autohotkey scripts can be "compiled" as well so you don't need the interpreter to run the script.

Also, if this is for something on the Web, I recommend iMacros. It's a firefox plugin and therefore has a much better integration with websites. For example, you can say "write 1000 'a's in this form" instead of "simulate a mouseclick at (319,400) and then press 'a' 1000 times".

For Linux, I unfortunately have not been able to find a good way to easily create keyboard/mouse macros.

Sikorsky answered 25/9, 2008 at 23:12 Comment(0)
S
3

Alternative way to set prefer window into foreground before send key press event.

hwnd = win32gui.FindWindowEx(0,0,0, "App title")
win32gui.SetForegroundWindow(hwnd)
Sfax answered 15/8, 2009 at 19:16 Comment(0)
H
3

PyAutoGui also lets you press a button multiple times:

pyautogui.press('tab', presses=5)   # press TAB five times in a row

pyautogui.press('A', presses=1000)   # press A a thousand times in a row
Hers answered 18/2, 2020 at 8:25 Comment(0)
B
3
import keyboard

keyboard.press_and_release('anykey')
Bunnell answered 12/12, 2020 at 8:4 Comment(0)
P
1

There's a solution:

import pyautogui
for i in range(1000):
    pyautogui.typewrite("a")
Poverty answered 17/2, 2021 at 14:6 Comment(0)
S
0

You can use pyautogui module which can be used for automatically moving the mouse and for pressing a key. It can also be used for some GUI(very basic). You can do the following :- import pyautogui pyautogui.press('A') # presses the 'A' key

If you want to do it 1000 times, then you can use a while loop

Hope this is helpful :)

Stylist answered 27/3, 2021 at 19:53 Comment(0)
I
0

You can use this code that I wrote which will press “a” key 1000 times

import pyautogui 
loop = 1
while loop <= 1000: 
  pyautogui.press("a")
   loop += 1
Impuissant answered 30/7, 2021 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.