Friday 11 April 2014

PyWinAtuto - Python Windows GUI Automation

'pywinauto' is a python module to automate windows GUI applications. 'pywinauto' in turn uses 'SendKeys' and 'ctypes'  python modules. In this post I'll discuss the installation of 'pywinauto' module and its dependencies. I'll also discuss automation of notepad  using pywinauto . So lets start..

  • Download and install Python 2.7
  • 'ctypes' module comes with Python 2.7 , so no need to install it.
  • Download appropriate version of SendKeys module installer from here.
  • All the dependencies are installed , now download 'pywinauto' bundle(zip file) from here.
  • Extract zip file to a folder
  • Copy pywinauto and sandbox folders from extracted location to "C:\Python27\Lib\site-packages" (default python external modules folder)
  • Installation of pywinauto is completed with previous step, test pywinauto using the below script. 
import pywinauto
app = pywinauto.application.Application()
app.start_("notepad")

above code will invoke notepad application.

As stage set for us, let us try to simple GUI automation of notepad application. Copy the below code and save it as python (.py) file and run the file. Most of the code is self explanatory if not comments will help you in understating the code.

from pywinauto import application

#start notepad application
window = application.Application().start_("notepad")

#Display/type hello world using TypeKeys method, Edit is the text editor control of notepad application
window.Notepad.Edit.TypeKeys("Hello World",with_spaces = True)

#Goto new line, its like pressing Enter key on keyboard
window.Notepad.Edit.TypeKeys("{ENTER}")

#with_spaces = fale by default
window.Notepad.Edit.TypeKeys("Text Without spaces will be like this")

window.Notepad.Edit.TypeKeys("{ENTER}")
window.Notepad.Edit.TypeKeys("Today Date is: ",with_spaces = True)
window.Notepad.Edit.TypeKeys("{F5}{ENTER}") #Pressing F5 in notepad will print date
window.Notepad.Edit.TypeKeys("Now let us save the file",with_spaces = True)

#we can access the menu bar using MenuSelect method
window.Notepad.MenuSelect("File->Save")

#top_window_() will return the currently focused child window
saveDlg = window.top_window_() 

#below 3 lines will save the file
saveDlg.TypeKeys("notepadAtumation")
saveDlg.print_control_identifiers()
saveDlg.Save.Click()

#close the notepad application
window.Notepad.MenuSelect("File->Exit")

In the next post I'll discuss automation controls and SendKeys mini syntax ( the strings we used in TypeKeys methods)

0 comments:

Post a Comment