Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 201
UnkwnTech Avatar asked Sep 25 '08 22:09

UnkwnTech


People also ask

What are key presses?

keypress (plural keypresses) The depression of an input key; a keystroke. (computing) The buffered electrical signal resulting from such an event, sometimes distinguished from the release.

What is in press in Python?

press(key) - presses a key and holds until the release(key) function is called. keyboard. release(key) - releases a key.

What does keyboard () do in Python?

It helps to enter keys, record the keyboard activities and block the keys until a specified key is entered and simulate the keys.


2 Answers

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}") 
like image 198
tzot Avatar answered Sep 22 '22 20:09

tzot


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") 
like image 33
Malachi Bazar Avatar answered Sep 21 '22 20:09

Malachi Bazar