Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 399
Bruno 'Shady' Avatar asked May 07 '10 21:05

Bruno 'Shady'


People also ask

How do you simulate a keyboard key in Python?

Import Key and Controller from pynput. keyboard . Make a variable called keyboard and set it to an instance of Controller . Now using the keyboard variable we can press and release keys.

How do you simulate mouse and keyboard events in code?

The best way to simulate mouse events is to call the On EventName method that raises the mouse event you want to simulate. This option is usually possible only within custom controls and forms, because the methods that raise events are protected and cannot be accessed outside the control or form.


2 Answers

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.

like image 50
Ishpeck Avatar answered Oct 06 '22 00:10

Ishpeck


Maybe you are looking for Sendkeys?

SendKeys is a Python module for Windows that can send one or more keystrokes or keystroke combinations to the active window.

it seems it is windows only

Also you have pywinauto (copied from my SO answer)

pywinauto is a set of open-source (LGPL) modules for using Python as a GUI automation 'driver' for Windows NT based Operating Systems (NT/W2K/XP).

and example from the web page

> from pywinauto import application > app = application.Application.start("notepad.exe") > app.notepad.TypeKeys("%FX") > app.Notepad.MenuSelect("File->SaveAs") > app.SaveAs.ComboBox5.Select("UTF-8") > app.SaveAs.edit1.SetText("Example-utf8.txt") > app.SaveAs.Save.Click() 
like image 20
joaquin Avatar answered Oct 06 '22 00:10

joaquin