Key Presses in Python
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.
Solution 1:
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}")
Solution 2:
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")
Solution 3:
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}
Solution 4:
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.
Solution 5:
Alternative way to set prefer window into foreground before send key press event.
hwnd = win32gui.FindWindowEx(0,0,0, "App title")
win32gui.SetForegroundWindow(hwnd)