Month: April 2013

Calling AutoIt using COM

AutoIt is a scripting language that came about from the requirement to automate Windows GUI actions. It is commonly used to solve installation issues but that is not of much interest to us. What is a little more interesting is some of the functionality of AutoIt is available to external programs through AutoItX.

This comes as a DLL (well two, a 32- and 64-bit version) which you can call a function from or register the DLL to get a COM server. In this article I will use the COM interface which is documented nicely in the accompanying help file.

If you installed the whole AutoIt package it should register the DLL for you. If not change into the directory with the DLL and type in regsvr32.exe AutoItX3.dll (or AutoItX3_x64.dll for a 64-bit OS).

To check whether everything is set up correctly try the following example code. It just moves the currently active window to the top left hand corner of the screen. Gimmicky but fairly short.

import win32com.client
aitcom = win32com.client.Dispatch("AutoItX3.Control")

# get currently active window title and its x & y position
wintitle = aitcom.WinGetTitle("")
startx = aitcom.WinGetPosX(wintitle)
starty = aitcom.WinGetPosY(wintitle)

# tool tip - stays on the screen until cleared
aitcom.ToolTip("Currently active window: "+wintitle,startx+25,starty+25)

# move window to top left hand corner in steps
steps = 10
x = range(startx,0,-startx//steps)
y = range(starty,0,-starty//steps)
for i in range(1,steps):
  aitcom.WinMove(wintitle,"",x[i],y[i])
aitcom.WinMove(wintitle,"",0,0)
aitcom.ToolTip("") # clear tool tip

Look through the documentation for more functionality and experiment.

Advertisements

Running shell commands

As much as we like to criticize Microsoft’s command prompt some of the commands provided can be very useful. The Internet is littered with commands to get helpful information. To make them really useful we need to get output from these commands into Python. Thankfully this is easy if you use the correct command.

You will need to import the subprocess module. All the work in this module is done by popen constructor which allows a good deal of flexibility. However we do not need such fine grained control so we can just you the convenience function check_output().

Just need an example now. I’m going to use a command from Rob van der Woulde’s scripting pages to list all of the domain controllers using dsquery. Feel free to change this to something suitable. This returns each DC on a line as you can see from the output. I can get a more useful list simply with DCs.split()

import subprocess
try:
  DCs = subprocess.check_output("dsquery server -o rdn",universal_newlines=True)
  print(DCs)
except subprocess.CalledProcessError:
  pass

This doesn’t just work for shell commands. Batch files can be ran in exactly the same way.