Hack 88 Use Python from Word![]() ![]() Python objects that you can run from within Word using VBA.[Hack #85] showed you how to control Word from Python using COM automation [Hack #84] . Python also includes a way to create your own COM objects, which you can then use from within a Word macro.
method, SplitString. This method has semantics identical to the standard Python function string.split: the first argument is the string to split, and the second (optional) argument is the delimiter string.There are two steps to implement COM objects in Python:Define a Python class with the methods and properties you wish to expose.Annotate the Python class with special attributes required by the PythonCOM framework to expose the Python class as a COM object.Both of these steps are accomplished by the code in the following section. 9.10.1 The CodeThe following Python code shows a small COM server: #SimpleCOMServer.py - A sample COM server - almost as small as they come!Save this code as SimpleCOMServer.py.Note the following line from the script: _reg_clsid_ = "{40CEA5F8-4D4C-4655-BD8B-0E7B6A26B556}"In this line, you assign a unique identifier to your COM object. Windows uses these identifiers to keep track of the components installed on the system. Do not just copy the one from this sample into your own code. You need to create your own, which you can do easily with Python right from the DOS command line: > pythonThis prints a new, unique identifier to the command line. Use the number created on your system in place of the sample in the code above. 9.10.2 Running the HackNow you'll need to register the object with COM. You can do this by executing the code as a normal Python script. From the DOS command line, type: > python SimpleCOMServer.pyAfter running the script, you'll see the following messages: Registering COM server...Now, to test the COM object from Word, put the following macro in the template of your choice [Hack #50] and run it from Tools Sub PythonObj( )Running this code displays three message boxes, each showing one of the words in the phrase "Hello from Python!"The default delimiter is a space, but you can also provide a delimiter string: vResponse = py.SplitString("Hello, Word", ",")To keep things tidy and help keep your registry clean, run your script again from the command line to unregister the sample COM server, but this time use the --unregister argument: > python SimpleCOMServer.py --unregisterMark Hammond |