190 likes | 451 Views
win32com Tricks and Secrets. The essential tools for using com objects in Python Presented by Craig Miller craigmiller@utah.gov Utah Division of Water Resources November 9, 2010. What Tricks (you might ask) . Create reports with Word Create tables, charts, graphics
E N D
win32com Tricks and Secrets The essential tools for using com objects in Python Presented by Craig Miller craigmiller@utah.gov Utah Division of Water Resources November 9, 2010
What Tricks (you might ask) • Create reports with Word • Create tables, charts, graphics • Use any database accessible through ADODB. • Translate existing VB, C+ into python to use the same com objects • Etc.
Download/Install Pythonwin Navigate to http://sourceforge.net/projects/pywin32/ Select this To view this Computer/System Python version
Where is PythonWin installed? ArcGIS 10 setup
Basic example (will work after install) Import win32com.client xlApp = win32com.client.Dispatch( "Excel.Application") xlApp.Visible = True xlApp.WorkBooks.Add() Note: Should show Excel with 3 standard worksheets, sheet1, sheet2, sheet3
What Strings to Use with Dispatch • Do not use Task Manager to find strings. Old help suggests this but now doesn’t work. • For Word use “Word.Application” • For other applications use MakePy
Where to get help • Create macros and translate the code from Word or Excel. • Use .chmhelpfiles from Microsoft, for example vbalx10.chm for excel.
What you get after DispatchNote: This only works in PythonWin You can now inspect xlApp’s methods
Rules are for following! • If you use MakePy • …. and distribute your code, distribute the files created by MakePy. Suggestions for modifying VBA to work in python: • Case for methods and attributes matters. • RS.MoveFirst() not RS.movefirst() • Always use () with methods • RS.MoveFirst() not RS.MoveFirst • Attributes or values don’t need () • while not RS.EOF: acceptable • Don’t use shortcuts! (Use PythonWin here) • RS.Fields(“ID”).Value not RS(“ID”)
If you use MakePy • Make sure that you also include the proper COM files if you use a specific version. • Consider using generic versions by simply deleting the version number, ie. “ADODB.Connection” not “ADODB.Connection.6.0”
Hints • Develop initial code in VB, C+, or C++ • Can integrate python and ruby into Visual Studio 2010. Less need for these workarounds when VS 2010 is standard for ArcGIS. • You can integrate python into microsoft code now if you register it!
Thank You! Questions? Email: CraigMiller@Utah.gov Phone: 801-538-7280