• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Chapter 3. Scripting and Objects > Using Objects with ActivePython

Using Objects with ActivePython

Many powerful CGI (Web-based) applications are written in Python, and ActiveState's ActivePython does a great job of integrating Python into the ASP scripting environment. This means it may also be used with Windows Script Host. Python, like Perl, has a rich set of built-in and add-on functions that give you complete access to the Windows API, so the scripting utility objects described in this book aren't going to be terribly interesting to the Python programmer. Still, you may want to use the scripting objects in the interest of increasing your scripts' language portability, and because COM/ActiveX objects are the only way to get programmatic access to Automation servers such as Microsoft Word.

Unlike Perl, Python was designed from the ground up as an object-oriented language. Objects, properties, and methods are its bread and butter, so to speak. If you're coming to Python from a background in other languages, there are a few points you should be aware of:

  • The WScript object discussed throughout this chapter is predefined. Python is case sensitive, so the object must be referred to as WScript, exactly.

  • Although Python is generally case sensitive, the names of COM object methods and properties are not.

  • Perhaps the easiest way to create ActiveX/COM objects is with the CreateObject method provided by WScript. Here's an example:

    fso = WScript.CreateObject("Scripting.FileSystemObject") 
    files = fso.GetFolder("C:\\").Files
  • You cannot directly assign a value to a COM object property. You must use

    object.SetValue("propertyname", newvalue) 


  • Python automatically imports all predefined constants associated with an OLE object when you create an instance of the object. The constant values are created as properties of win32com.client.constants. For example, if you create a Microsoft Word document, the value win32com.client.constants.wdWindowStateMinimize will be defined.

For more information about COM integration with Python, see the ActiveState documentation for the win32com package.

Working with Collections

Python automatically treats COM collection objects as enumerations. The easiest way to scan through the contents of an enumeration is with the for...in statement, as in this example:

fso = WScript.CreateObject("Scripting.FileSystemObject") 
files = fso.GetFolder("c:\\").Files

for file in files:
    print file.name

Now, you may want to skip ahead to the section titled “Using the WScript Object” for more information about the built-in WScript object.

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint