Which is the easiest way to simulate keyboard and mouse on Python?

Bruno 'Shady' picture Bruno 'Shady' · May 7, 2010 · Viewed 65.6k times · Source

I need to do some macros and I wanna know what is the most recommended way to do it.

So, I need to write somethings and click some places with it and I need to emulate the TAB key to.

Answer

Ishpeck picture Ishpeck · May 8, 2010

I do automated testing stuff in Python. I tend to use the following:

http://www.tizmoi.net/watsup/intro.html
Edit: Link is dead, archived version: https://web.archive.org/web/20100224025508/http://www.tizmoi.net/watsup/intro.html

http://www.mayukhbose.com/python/IEC/index.php

I do not always (almost never) simulate key presses and mouse movement. I usually use COM to set values of windows objects and call their .click() methods.

You can send keypress signals with this:

import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys("^a") # CTRL+A may "select all" depending on which window's focused
shell.SendKeys("{DELETE}") # Delete selected text?  Depends on context. :P
shell.SendKeys("{TAB}") #Press tab... to change focus or whatever

This is all in Windows. If you're in another environment, I have no clue.