专注于自动化测试,性能测试.......

Python生成COM组件(原创)

上一篇 / 下一篇  2009-09-13 22:46:57 / 个人分类:Python

   经过一段对Python的使用,发现它确实是一门比较优秀的语言,语法简练,类库丰富且调用简单,在数据库,文本处理,网络编程方面都很棒。所以就一直想在实际工作中,确切地来说是现在正在进行的自动化测试使用Python,但是由于测试工具不支持python语言,所以没法直接在工具中使用。就考虑怎么在C#或者VBS中引用Python,一直没有太好的思路。偶然间阅读了《Python programming on win32,里面提到了把Python的类注册成为Com组件供VBDelphi实用的例子,顿时豁然开朗。

9c6S$}`u t0

 下面就该书中Implementing COM Objects with Python章节进行分析,首先给出原文:51Testing软件测试网9yA+t'ZO JA#H;|F

Implementing COM Objects with Python

3YA2\f z!Sw7a0

In this section, we discuss how to implement COM objects using Python and a small sample of such an object. We also present some Visual Basic code that uses our Python implemented object.

;t*m4v @+q Dm~$D0

For this demonstration, you'll write a simple COM object that supports a number of string operations. As Visual Basic is somewhat lacking in the string-processing department where Python excels, it's a good candidate. The sample provides a COM object with a single method, SplitString(). This method has semantics identical to the standard Python function string.split(); the first argument is a string to split, and the second optional argument is a string holding the character to use to make the split. As you have no doubt guessed, the method won't do much more than call the Python string.split() function.51Testing软件测试网 Y%iv~ soD+[[]

There are two steps to implement COM objects in Python:51Testing软件测试网%v3w*h6[ q N2p-[

  • 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. These annotations include information such as the objects ProgID, CLSID, and so forth.

Python中实现COM对象有两个步骤:51Testing软件测试网T Z;\)~J$DfW {

1.           定义你希望暴露的类的方法和属性51Testing软件测试网b,g#@P!r-W*]*c

2.           注解PythonCOM框架为了暴露python类所需的专用属性,其中包括对象ProgID,CLSID等等51Testing软件测试网k-I3_ pU@

The following code shows a smallCOM server written in Python:51Testing软件测试网0bO*U+f g*|

# SimpleCOMServer.py - A sample COM server - almost as small as they come!51Testing软件测试网7P0Y@9VXK|

#

e+iN8V L:[)B0

# We expose a single method in a Python COM object.

ImP'H]US0

class PythonUtilities:

5^Q-A:^"e \4E N0

   _public_methods_ = [ 'SplitString' ]

z_c\uAWM"lJ0

   _reg_progid_ = "PythonDemos.Utilities"

R;z]4[3N-pN0

   # NEVER copy the following ID51Testing软件测试网` qRVnB

   # Use "print pythoncom.CreateGuid()" to make a new one.

[${}Rx7X z&}0

   _reg_clsid_ = "{41E24E95-D45A-11D2-852C-204C4F4F5020}"

$^`4H0n3l^x M0

   51Testing软件测试网tT2?"m;a@)P

   def SplitString(self, val, item=None):51Testing软件测试网0k!qj_ _t&f5H$X]8zy

       import string51Testing软件测试网DA@&X3^B

       if item != None: item = str(item)

D'hO]y*p7F:BV8D6hR{0

       return string.split(str(val), item)

P*J&@S6U4y&|.A,}0

 

7y)p:^(v#u%a/s I)b0

# Add code so that when this script. is run by51Testing软件测试网u!LK M-v{a'H

# Python.exe, it self-registers.51Testing软件测试网a?V7W;a3S1kRj!ic

if __name__=='__main__':

#kSqd.M3J~'vD0

   print "Registering COM server..."

5DM%P&t T1@0

   import win32com.server.register51Testing软件测试网2Xg*B F7mr~H.V

   win32com.server.register.UseCommandLine(PythonUtilities)

8BlELj0

The bulk of the class definition is taken up by the specialattributes:51Testing软件测试网1d9hg'qM/^@

_public_methods_51Testing软件测试网\e\ l8T

A list of all methods in the object that are to be exposed via COM; the sample exposes only one method, SplitString.51Testing软件测试网$m&s#E6g,`$\

一列包含所有需要暴露的类方法的列表51Testing软件测试网}AaEy;J9[

_reg_progid_51Testing软件测试网z/G$qr W$t e

TheProgID for the new object, that is, the name that the users of this object must use to create the object.51Testing软件测试网C#|.q ^{5UTT

新对象的ProgID,该名称是所有调用Com,创建对象时必须用到的。

H(aN4~P PSn0

_reg_clsid_

NB1H jn*aX"f1G0

The uniqueCLSID for the object. As noted in the source code, you must never copy these IDs, but create new ones using pythoncom.CreateGuid().51Testing软件测试网{ W v3n8Gl4U

对象的CLSID(独一无二的),你可以通过Pythoncom.CreateGuid()创建。

*Ca1Lb$e3G9R+p v0

Full details of these and other possible attributes can be found inChapter 12.51Testing软件测试网@&n}8~1uF+y!`/o

The SplitString() method is quite simple: it mirrors the behavior. of the Python string.split() function. A complication is that COM passes all strings asUnicode characters, so you must convert them to Python strings using the str() function. Note that in Python 1.6, it's expected that the string and Unicode types will be unified allowing the explicit conversions to be removed.

%FSyf4z,sr b0

The only thing remaining is to register theobject with COM. As the comments in the code imply, you can do this by executing the code as a normal Python script. The easiest way to do this is to open the source file in PythonWin and use the Run command from the File menu. After running the script, the PythonWin interactive window should display:

'{!f| y|sz"c0

Registering COM server...

4y4g/g8E_o0ac0

Registered: PythonDemos.Utilities

Y4orf/{&G9Fj0

Finally, let's test theCOM object. UseVisual Basic for Applications, which ships with both Microsoft Office and Microsoft Excel, and perform. the following steps:

@\)r aF.z4@#~Cv0
  1. Start Microsoft Word or Microsoft Excel.
  2. Press ALT-F8 to display the macros dialog.
  3. Enter a name for the macro (e.g., TestPython) and select Create.
  4. The Visual Basic editor is displayed. In the editor, enter the following code:

5.           Set PythonUtils = CreateObject("PythonDemos.Utilities")51Testing软件测试网U&]b:z7k3qt ?g[&fz

6.           response = PythonUtils.SplitString("Hello from VB")

/a(Y*n,?ws7`)S0

7.           for each Item in response

7Y3h@,c3Pe;hY0

8.             MsgBox Item51Testing软件测试网UU4Q#?m

nex

1|_r$J \c#`j&f0

Now run this code by pressing the F5 key. If all goes well, you should see three message boxes. The first one is shown inFigure 5.2.

wM4j)c@!Hj+ul0

Just to be complete and help keep your registry clean, unregister your sample COM server. You do this by following the same process that registered the server, except specify --unregister as an argument to your script. A message is printed saying the object is unregistered.51Testing软件测试网)f^ D7q5uTKivv

自己练习实现的例子:51Testing软件测试网L;SX OL1c

import win32com.server.register51Testing软件测试网/X#qS;fD@(HYgX

import pythoncom51Testing软件测试网7T4m6S*o[?%^

class MyFirstCom(object):51Testing软件测试网$Te*b|5}I x3| W'?H

 

)J-]{-vC Vm6eSX0

   _public_methods_ = ['Instring']

/qYSAjV0

 

N@N6_W s*O wZ0

   _reg_progid_ ="Pythoncom.FirstCom"

)ZZ V1LpL(z`"lV0

 51Testing软件测试网5Cky0dXwY}

   _reg_clsid_ = pythoncom.CreateGuid()51Testing软件测试网!x Tay J!S

 51Testing软件测试网#ZYL)[ptKU:t

   def Instring(self,val,vals):

r ESO#\$lz0

       if val in vals:

)i`W b_0

           return True51Testing软件测试网9v:g g _v)vq

       else:51Testing软件测试网E"Bo,SYCu

           return False51Testing软件测试网&RK,}8S4e*o7b:`'O2V

 

2x I'WfR$y)x0

if __name__ == "__main__":51Testing软件测试网7?:El9Xip zV+B

   win32com.server.register.UseCommandLine(MyFirstCom)

TAG: Python python

 

评分:0

我来说两句

wxf_xsfy

wxf_xsfy

自动化测试的拥簇者,善于自动化测试的框架和工具开发,TIB工作室核心成员

日历

« 2024-05-06  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 381605
  • 日志数: 79
  • 图片数: 1
  • 文件数: 1
  • 书签数: 3
  • 建立时间: 2007-09-19
  • 更新时间: 2018-01-30

RSS订阅

Open Toolbar