Key Presses in Python Key Presses in Python python python

Key Presses in Python


Install the pywin32 extensions. Then you can do the following:

import win32com.client as comcltwsh= comclt.Dispatch("WScript.Shell")wsh.AppActivate("Notepad") # select another applicationwsh.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 comctlwsh = comctl.Dispatch("WScript.Shell")# Google Chrome window titlewsh.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 pyautoguipyautogui.press('Any key combination')

You can also send keys like the shift key or enter key with:

import pyautoguipyautogui.press('shift')

Pyautogui can also send straight text like so:

import pyautoguipyautogui.typewrite('any text you want to type')

As for pressing the "A" key 1000 times, it would look something like this:

import pyautoguifor 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 keypyautogui.keyDown("alt")# Presses the tab key oncepyautogui.press("tab")# Lets go of the alt keypyautogui.keyUp("alt")


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 WordSend {A 100}