⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 133.html

📁 Python Ebook Python&XML
💻 HTML
📖 第 1 页 / 共 2 页
字号:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<META NAME="Robots" content="INDEX,NOFOLLOW">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<TITLE>Safari | Python Developer's Handbook -&gt; Implementing COM Objects in Python</TITLE>
<LINK REL="stylesheet" HREF="oreillyi/oreillyN.css">
</HEAD>
<BODY bgcolor="white" text="black" link="#990000" vlink="#990000" alink="#990000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">

<table width="100%" cellpadding=5 cellspacing=0 border=0 class="navtopbg"><tr><td><font size="1"><p class="navtitle"><a href="8.html" class="navtitle">Web Development</a> &gt; <a href="0672319942.html" class="navtitle">Python Developer's Handbook</a> &gt; <a href="128.html" class="navtitle">7. Objects Interfacing and Distribution</a> &gt; <span class="nonavtitle">Implementing COM Objects in Python</span></p></font></td><td align="right" valign="top" nowrap><font size="1"><a href="main.asp?list" class="safnavoff">See All Titles</a></font></td></tr></table>
<TABLE width=100% bgcolor=white border=0 cellspacing=0 cellpadding=5><TR><TD>
<TABLE border=0 width="100%" cellspacing=0 cellpadding=0><TR><td align=left width="15%" class="headingsubbarbg"><a href="132.html" title="Introduction to COM Objects"><font size="1">&lt;&nbsp;BACK</font></a></td><td align=center width="70%" class="headingsubbarbg"><font size="1"><a href="popanote.asp?pubui=oreilly&bookname=0672319942&snode=133" target="_blank" title="Make a public or private annnotation">Make Note</a> | <a href="133.html" title="Use a Safari bookmark to remember this section">Bookmark</a></font></td><td align=right width="15%" class="headingsubbarbg"><a href="134.html" title="Distributing Objects with Python"><font size="1">CONTINUE&nbsp;&gt;</font></a></td></TR></TABLE>
<a href="5%2F31%2F2002+4%3A37%3A13+PM.html" TABINDEX="-1"><img src=images/spacer.gif border=0 width=1 height=1></a><font color=white size=1>152015024128143245168232148039199167010047123209178152124239215162147035189205032045199079</font><a href="read8.asp?bookname=0672319942&snode=133&now=5%2F31%2F2002+4%3A37%3A13+PM" TABINDEX="-1"><img src=images/spacer.gif border=0 width=1 height=1></a><br>
<FONT><h3>Implementing COM Objects in Python</h3>
				<p>In order to implement COM objects in the Python version of Windows, you need a set of extensions developed by <a NAME="idx1073744383"></a>Mark Hammond and <a naME="idx1073744384"></A>Greg Stein. Part of the <A name="idx1073744385"></A><A NAme="idx1073744386"></a><a name="idx1073744387"></a><a name="idx1073744388"></a><tt claSs="monofont">win32com</tT> package, these extensions enable you to do everything that is COM-related, including writing COM clients and COM servers.</p>

				<p>The following link takes you to the download page of these extensions:</p>

				<P><a tarGet="_blank" hREF="http://www.python.org/download/download_windows.html">http://www.python.org/download/download_windows.html</A></p>

				<p>All the Win32 extensions (including the COM extensions) are part of the <a nAME="idx1073744389"></A><a namE="idx1073744390"></A><A Name="idx1073744391"></a><A NAMe="idx1073744392"></a><tt class="monofont">win32all</tt> installation package. This package also installs the <tt class="monofont">PythonWin</tt> IDE in your machine.</P>

				<p>The latest version of this whole package is located at the win32all home page. Search for the <tT claSs="monofont">win32all.exe</tt> file:</p>

				<P><a taRGET="_blank" href="http://www.python.org/windows/win32all/">http://www.python.org/windows/win32all/</A></P>

				<P>You can also go directly to Mark Hammond's starship home page, which might have more recent beta releases of this package:</P>

				<p><a taRGET="_blank" href="http://starship.python.net/crew/mhammond/">http://starship.python.net/crew/mhammond/</A></P>

				<P>After installing the package in your machine, take a look at the <Tt class="monofont">readme.htm</tt> file, which is stored at the <tt class="monofont">win32com</tt> directory.</p>

				<p>COM support for Python is compounded of the core PythonCOM module, which supports the C++ code, and the other modules that implement helper code in Python. The whole package is known as <tT clAss="monofont">win32com.</tT></p>

				<h4>The <tt ClasS="monofont">win32com</TT> Package</H4>
					<p>The <tt cLASS="monofont">win32com</tt> support is standalone, as it does not require PythonWin. The <tt CLASs="monofont">win32com</tt> package itself does not provide any functionality. Some of the <a NAME="idx1073744393"></a><a name="idx1073744394"></a>modules contained in this package are</p>

					<blockquote>
<p><p><B>win32com.pythoncom棤</b>
Provides core C++ support for COM objects and exposes COM object methods, such as <tT claSs="monofont">QueryInterface()</tt> and <tT claSS="monofont">Invoke(),</TT> just as the C++ API does. Note that all the reference counting is automatically done for you. Programmers rarely access this module directly. Instead, they usually use the <tt clASS="monofont">win32com</Tt> wrapper classes and functions written in Python to provide a nice, programmable interface.<a naME="idx1073744395"></A><A name="idx1073744396"></A><A NAme="idx1073744397"></a><a name="idx1073744398"></a><a name="idx1073744399"></a><a name="idx1073744400"></A><a nAme="idx1073744401"></a><A name="idx1073744402"></A><a naME="idx1073744403"></A><A name="idx1073744404"></A></P>
</P>
<P><p><b>win32com.client棤</b>
Provides support for COM clients (for example, using Python to start Microsoft Excel and create a spreadsheet). The COM client support enables Python to manipulate other COM objects via their exposed interfaces. All client-side <tT CLAss="monofont">IUnknown</tt>-derived objects, including <TT CLass="monofont">IDispatch,</tt> are supported.</p>
</p>
<p><p><b>win32com.server棤</b>
Provides support for COM servers (for example, creating and registering a COM server object in Python and using a language such as Visual Basic or Delphi to access the Python objects). The COM server support enables Python to create COM servers, which can be manipulated by another COM client. All server-side <tt class="monofont">IUnknown</tt>-derived objects are supported.</P>
</p>
<p><P><b>win32com.axscript棤</b>
This is the ActiveX Scripting implementation for Python.</p>
</P>
<p><p><b>win32com.axdebug棤</b>
This is the Active Debugging implementation for Python.</P>
</p>
<p><p><B>win32com.mapi棤</B>
Provides utilities for working with MAPI and the Microsoft Exchange Server.<A Name="idx1073744405"></a><A NAMe="idx1073744406"></a><a nAME="idx1073744407"></A><a namE="idx1073744408"></A><A Name="idx1073744409"></a><a name="idx1073744410"></a><a name="idx1073744411"></a><a namE="idx1073744412"></a><a Name="idx1073744413"></A><a namE="idx1073744414"></a></p>

						</p>
</BLOCkquoTE>
				
				<H4>Talking to Windows Applications</H4>
					<p>The COM technology has been part of the Windows world for a long time. The COM genealogy can be traced back to DDE (Dynamic Data Exchange). DDE was the first device for transferring data between various applications in a multi-tasking computer. After some time, DDE was expanded to Object Linking and Embedding (OLE)梟ote that COM was invented as part of OLE. The creation of the Visual Basic Extensions (VBXs) enhanced the OLE technology for visual components, originating a new standard called OLE2, which was based on top of COM. Soon, the OLE2 technology became more integrated with COM, which is a general-purpose mechanism. Nowadays, COM is mostly known, in part, because of the ActiveX technology.</p>

					<p>Professional applications such as Microsoft Office and the Netscape browser enable you to control their objects using COM. Therefore, programs written in Python can be easily used to control those applications.</p>

					<P>COM passes string objects as Unicode characters. Before using these objects in Python, it's necessary to convert them to strings. The Python-2.0 Unicode string type is not the same as the string type, but it is easy to convert between the two.</P>

					<P>PythonWin comes with a basic COM browser (Python Object browser). This program helps you to identify the current objects in your system that implement COM interfaces.</P>

					<p>To run the browser, select it from the PythonWin Tools menu, or double-click on the file <tt cLASS="monofont">win32com\client\combrowse.py.</tt></p>

					<p>Note that there are other COM browsers available, such as the one that comes with the Microsoft Visual C++.</p>

					<p>If you study the file <tt class="monofont">\python\win32com\servers\interp.py,</tt> which is installed as part of your PythonWin distribution, you will learn how to implement a very simple COM server. This server exposes the Python interpreter by providing a COM object that handles both the <tt claSs="monofont">exec</tT> and <tt cLass="monofont">eval</tT> methods. Before using this object, register it by running the module from Python.exe. Then, from Visual Basic, use CreateObject('Python.Interpreter') to initialize the object, and you can start calling the methods.<a naME="idx1073744415"></A><A name="idx1073744416"></A><A NAme="idx1073744417"></a><a NAME="idx1073744418"></a><a naME="idx1073744419"></A><A name="idx1073744420"></a><a name="idx1073744421"></a><a name="idx1073744422"></a><a naMe="idx1073744423"></a><A namE="idx1073744424"></a><a naMe="idx1073744425"></a><a NAME="idx1073744426"></a></p>

				
				<h4>Word and Excel</h4>
					<P>Let's quit talking and get to some practicing. Our objective here is to open and manipulate Microsoft applications from Python.</P>

					<P>The first thing that you need to do is to <A name="idx1073744427"></A><A NAme="idx1073744428"></a>import the COM client and dispatch the right object. In the next example, a variable is assigned a reference to an Excel application:</p>

					<PRE>
						
&gt;&gt;&gt; import win32com.client
&gt;&gt;&gt; xl = win32com.client.Dispatch("Excel.Application")

					</Pre>

					<p>The following does the same thing, but this time the reference is to a Word application.</p>

					<pre>
						
&gt;&gt;&gt; wd = win32com.client.Dispatch("Word.Application")

					</pre>

					<p><tt class="monofont">Excel.Application</tt> and <Tt cLass="monofont">Word.Application</Tt> are the Program IDs (progid), which are the names of the objects for which you want to create an instance. Internally, these objects have a Class ID (clsid) that uniquely registers them in the Windows Registry. The matching table between progids and clsids is stored in the Windows Registry and the matching is performed by the COM mechanism.</p>

					<p>It is not an easy job to identify an application progid, or to find out object methods and attributes. You can use COM browsers to see what applications have COM interfaces in your system.</p>

					<P>For the Microsoft Products, you can take a look at the documentation; it is a good source of information.</p>

					<p>Not necessarily every COM object implements the same interface. However, there are similarities.</p>

					<P>For example, if the previous assignments have just created the objects and you want to make them visible, you have to type</P>

					<PRe>
						
&gt;&gt;&gt; xl.Visible = 1  # Sets the visible property for the Excel application
&gt;&gt;&gt; wd.Visible = 1  # Sets the visible property for the Word application

					</pre>

					<P>To <A NAme="idx1073744429"></a><a NAME="idx1073744430"></a><a naME="idx1073744431"></A>close both programs and release the memory, you need to say</P>

					<pre>
						
&gt;&gt;&gt; xl = None
&gt;&gt;&gt; wd = None

					</pre>

					<p>or, you could use<a name="idx1073744432"></a><a name="idx1073744433"></a><a NamE="idx1073744434"></a><a nAme="idx1073744435"></a><a Name="idx1073744436"></A><A NAme="idx1073744437"></a><a NAME="idx1073744438"></a><a naME="idx1073744439"></A><A name="idx1073744440"></A><A NAme="idx1073744441"></a><a name="idx1073744442"></a><a name="idx1073744443"></a><a name="idx1073744444"></A><a nAme="idx1073744445"></a></P>

					<pre>
						
&gt;&gt;&gt; del xl, wd

					</pRe>

					<p>These were simple examples of implementing COM clients in Python. Next, we will see how to <a NAME="idx1073744446"></a><a naME="idx1073744447"></A><A name="idx1073744448"></A><A NAme="idx1073744449"></a><a NAME="idx1073744450"></a>implement a Python COM server by creating a Python interface that exposes an object. The next block of code registers the interface in the Windows Registry.</p>

					<p>Note that every new COM object that you create must have a unique clsid, but you don't have to worry about it. The complex algorithm that works behind the scenes is ready to generate a unique identification, as shown here:</p>

					<pre>
						
&gt;&gt;&gt; import pythoncom
&gt;&gt;&gt; print pythoncom.CreateGuid()

					</pre>

					<p>Your COM server is defined next. You have to execute the program in order to make the COM object available in the system. Store it on a file, and double-click on it.</p>

					<pre>
						
 1: class TaxApplication:
 2:     _public_methods_ = ['PAtax']
 3:     _reg_progid_ = "Tax.Application"
 4:     _reg_clsid_ = "{D2DEB6E1-3C6D-11D4-804E-0050041A5111}"
 5:
 6:     def PAtax(self, amount, tax=0.07):
 7:         return amount + (amount * tax)
 8:
 9: if __name__=='__main__':
10:     print "Registering COM server"
11:     import win32com.server.register
12:     win32com.server.register.UseCommandLine(TaxApplication)

					</pre>

					<p>Line 2: Exposes the method to be exported.</p>

					<P>Line 3: Defines the name that the COM client application must use to connect to the object.</p>

					<p>Line 4: Defines the unique Class ID (<Tt clAss="monofont">clsid</tt>) used by the object.<A namE="idx1073744451"></A><A Name="idx1073744452"></a><A NAMe="idx1073744453"></a><a nAME="idx1073744454"></A><a namE="idx1073744455"></A><A Name="idx1073744456"></a><a name="idx1073744457"></a><a name="idx1073744458"></a><a namE="idx1073744459"></a><a Name="idx1073744460"></A><a namE="idx1073744461"></a><a nAME="idx1073744462"></A><a namE="idx1073744463"></A><A Name="idx1073744464"></a><A NAMe="idx1073744465"></a><a nAME="idx1073744466"></A><a name="idx1073744467"></a><a name="idx1073744468"></a><a name="idx1073744469"></a></p>

					<p>Line 12: Registers the <Tt cLass="monofont">TaxApplication</Tt> class.</p>

					<p>In order to <a Name="idx1073744470"></A>test the program, we need to have an external COM client. Let's use the Visual Basic for Applications Editor, which is present in both Excel and Word.</P>

					<P>Open your Microsoft application, type <B><tt clASS="monofont">ALT+F8</Tt></b> in the Macro dialog box, and select the option that creates a macro. Now, you need to type the following block of code:</p>

					<pRE>
						
Sub Tax()

    Set TaxApplication = CreateObject("Tax.Application")
    newamount = TaxApplication.PAtax(100)
    MsgBox newamount
    Set TaxApplication = Nothing

End Sub

					</PRe>

					<p>Now, if you press F5, Visual Basic should display a message box showing the result of our simple tax operation, which, in our case, is <i>107.</i><A NAMe="idx1073744471"></a></p>

					<p>To <a name="idx1073744472"></a><a name="idx1073744473"></a><a namE="idx1073744474"></a>unregister your COM object you can either pass the argument <tT claSs="monofont">--unregister</tt> when calling your script, or you can use the following line of code inside your Python program:</p>

					<Pre>
						

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -