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

W0J

yzn

下面就该书中Implementing COM Objects with Python章节进行分析,首先给出原文:51Testing软件测试网p+Qa}P"m0X

Implementing COM Objects with Python@?0LDw5f5X:Ow

LN$C0

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.51Testing软件测试网J,@(r_iS4pu"D

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.jd@h?1xO&qG)uF0

There are two steps to implement COM objects in Python:51Testing软件测试网+elH6Vw$UEc8]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对象有两个步骤:)W$g$]:S7G$q]0

1.定义你希望暴露的类的方法和属性j5_[c@.WN:}\U+V%a0

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

b

The following code shows a smallCOM server written in Python:WR*S3j8x"}$x0

# SimpleCOMServer.py - A sample COM server - almost as small as they come!51Testing软件测试网|3l-pn;\

?!E

#51Testing软件测试网V"@^4nD"r

# We expose a single method in a Python COM object.51Testing软件测试网&@5e^{ Y-N ^

class PythonUtilities:51Testing软件测试网8oB@vg'u*_dN

_public_methods_ = [ 'SplitString' ]51Testing软件测试网D"V@k&m9O.E"s{

_reg_progid_ = "PythonDemos.Utilities"51Testing软件测试网

\*tr%Lf"ZT

# NEVER copy the following ID51Testing软件测试网`Ek4Fq){q}

# Use "print pythoncom.CreateGuid()" to make a new one.kn!]em0

_reg_clsid_ = "{41E24E95-D45A-11D2-852C-204C4F4F5020}"h&s3M$vY.g(]A&L3Q0

51Testing软件测试网n+l3x2jp

jS

def SplitString(self, val, item=None):51Testing软件测试网!D'ceU;Y:y s

import string51Testing软件测试网 ^8_4GQ$o-Aj.^#D\

if item != None: item = str(item)51Testing软件测试网.M)RCJU;{(o)^

return string.split(str(val), item)51Testing软件测试网m P5}D~Dtg^

:xq/GDB6LFE0

# Add code so that when this script. is run by51Testing软件测试网:Nv C*e \;@

# Python.exe, it self-registers.T?RZ:c9[w+sU0

if __name__=='__main__':51Testing软件测试网"zyN||FLEp:\O

print "Registering COM server..."E}#q0aYMvG0

import win32com.server.registerbj/XJ7@yF0

win32com.server.register.UseCommandLine(PythonUtilities)?#w%v\f?b0

The bulk of the class definition is taken up by the specialattributes:51Testing软件测试网$Jh#[,\Q&q2AyP&Z

m1r;S,[)f?-S8bl]0

A list of all methods in the object that are to be exposed via COM; the sample exposes only one method, SplitString.;w!?-sgW3in

v0

一列包含所有需要暴露的类方法的列表51Testing软件测试网EG1lQ2FZx

_reg_progid_ev-~i5N0

TheProgID for the new object, that is, the name that the users of this object must use to create the object.x;\P4ypW

ud9TVe0

新对象的ProgID,该名称是所有调用Com,创建对象时必须用到的。51Testing软件测试网#Ca1di&EQD%x~

_reg_clsid_51Testing软件测试网5kIv m:kRt.c

The uniqueCLSID for the object. As noted in the source code, you must never copy these IDs, but create new ones using pythoncom.CreateGuid()./zz'}1CRdw0

对象的CLSID(独一无二的),你可以通过Pythoncom.CreateGuid()创建。M9}Gj)r#?H9R6O"x,E0

Full details of these and other possible attributes can be found inChapter 12.51Testing软件测试网*E`q+Rb9|K+r#P\

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.51Testing软件测试网z$tAe

?c5Ek;K|

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:51Testing软件测试网:F%E*o0t-TK,YV

Registering COM server...51Testing软件测试网~Nt:H_!mz

Registered: PythonDemos.Utilitiesr1p {:Z#Q1so+ND:z0

Finally, let's test theCOM object. UseVisual Basic for Applications, which ships with both Microsoft Office and Microsoft Excel, and perform. the following steps:51Testing软件测试网7rE{D^dOvUv^P$mStart Microsoft Word or Microsoft Excel.

Press ALT-F8 to display the macros dialog.

Enter a name for the macro (e.g., TestPython) and select Create.

The Visual Basic editor is displayed. In the editor, enter the following code:

5.Set PythonUtils = CreateObject("PythonDemos.Utilities")51Testing软件测试网o/L+N;PSP8{

6.response = PythonUtils.SplitString("Hello from VB")51Testing软件测试网 }+fv4Hm1^3ZW`

7.for each Item in response3\tX(dgl nR,x IK)X$z0

8.MsgBox Item51Testing软件测试网;e6p-J cn1U)B"n:v

nex51Testing软件测试网p(M(X9G5P#Yi8L/Ea

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.;Z.PFYgl0

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软件测试网3^o&\!NK,ES

自己练习实现的例子:51Testing软件测试网"q.X1b0j!YN4@W$h;R:~

import win32com.server.register;I~ B7lx

u1c0

import pythoncomg)w R%i{0

class MyFirstCom(object):PJ"]+S0e3ciA0

f0Rrp7G#xp0

_public_methods_ = ['Instring']51Testing软件测试网5GNgig:oU"b

0{qE,D+lqel7~"L.t0

_reg_progid_ ="Pythoncom.FirstCom"51Testing软件测试网?;Xw#LFWdged9DN

51Testing软件测试网!oo"Rqu!M

_reg_clsid_ = pythoncom.CreateGuid()51Testing软件测试网!yzT7Obb;~

51Testing软件测试网v$]'lX[1o a0m

def Instring(self,val,vals):51Testing软件测试网6m ^ R$Cz\3hp

if val in vals:51Testing软件测试网A+z[K#mm0P

return True51Testing软件测试网F/^1Ma$rQc

else:51Testing软件测试网Z htA3Xu-\

return False*UGXTmu-[m'`0

%t6pb;[9h1va0

if __name__ == "__main__":51Testing软件测试网P\JH:@$?:Uwin32com.server.register.UseCommandLine(MyFirstCom)

python开发com组件_Python生成COM组件(原创)相关推荐

  1. python开发桌面时钟_python基于Kivy写一个图形桌面时钟程序

    Kivy 是一个开源的 Python 第三方库,可以用来快速开发应用程序. 它有如下三个特点: 跨平台 Kivy 编写的程序可在 Linux,Windows,OS X,Android,iOS 和 Ra ...

  2. python开发效率怎样_Python 的开发效率真的比 Java高吗?

    真的比Java高很高. 几个例子. 爬虫领域,几年前就用Scrapy抓百度,新浪,股吧等各种东西. 五分钟写好一个小爬虫,爽到暴有没有?当年我就是靠教人写爬虫...才骗到小妹妹跟我约会的. 文本处理, ...

  3. python 开发视频播放网站_python开发微电影视频网站教程附源码

    做为一个合格的Pythoner,只掌握一个框架是不够,如果你有过其它Python框架(例如django)的使用经验,对比不同框架的特性来学习,你将收获更多 当前信息若含有黄赌毒等违法违规不良内容,请点 ...

  4. python开发游戏流程_python开发游戏的前期准备

    python开发游戏的前期准备 本文章面向有一定基础的python学习者,使用Pygame包开发一款简单的游戏 首先打开命令行,使用PyPI下载Pygame包(输入命令pip install pyga ...

  5. python开发的前景_python开发前景怎么样

    随着近几年Python的飞速发展,应用范围逐步趋于广泛,后端开发.前端开发.爬虫.金融量化分析.人工智能.自动化运维.自动化运维.大数据,Python都有涉及.Python相对其他编程语言来讲,语法较 ...

  6. python开发工具管理系统_Python开发桌面软件文档及网址管理工具,强迫症的福音...

    原标题:Python开发桌面软件文档及网址管理工具,强迫症的福音 写在前面 这两天用python鼓捣开发了一个软件,分享给同事,觉得很实用,可以大大提高工作效率,想通过平台分享出来给大家 希望给爱好p ...

  7. python设定数值范围_Python 生成周期性波动的数据 可指定数值范围

    代码 import numpy as np import math import matplotlib.pyplot as plt #python在指定的时间段生成周期性波动的数据: #周期性 lon ...

  8. python开发webservice服务_Python开发WebService系列教程之REST,web.py,eurasia,Djan

    在Bioinformatics(生物信息学)领域,WebService是很重要的一种数据交换技术,未来必将更加重要.目前EBI所提供的WebService就分别有SOAP和REST两种方式的服务,不管 ...

  9. python开发工程师工资_Python开发工程师工资一般多少钱

    Python工程师工资多少钱,相信每一个想要踏入Python开发行业的人都想知道这样一个问题,一个行业的薪资标准代表了它繁荣与否也代表了自己职业的未来的发展.下面就让我们来看一下一般Python开发工 ...

最新文章

  1. python 监控windows磁盘空间和备份大小
  2. 探秘新一代音视频技术融合通信平台全接触
  3. PHP 一键安装扩展的程序-(Windows 系统)
  4. mysql sum很慢,可以在MySQL中加快sum()吗?
  5. scrapy读取mysql数据库_python3实战scrapy获取数据保存至MySQL数据库
  6. 安装flash-----纠结
  7. 【转】科大校长给数学系学弟学妹的忠告本科数学参考书
  8. Java虚拟机(三)——类加载子系统概述
  9. 通过Windows Live Writer发布日志到各大博客
  10. PS 图像调整算法——自动色阶 (Auto Levels)
  11. STL vector使用方法介绍
  12. Windows上如何搭建web网站,并发布到外网可访问?2-2
  13. 软件需求规格说明书范例
  14. 统计调查制度申请流程和申请书公文模板
  15. 项目如行军——《孙子兵法》之九地篇
  16. CSS基础班笔记(三)
  17. UOS系统适配-常用开发工具安装
  18. border渐变 ios_IOS画渐变的三种方式
  19. wxPython的界面设计wxformbuilde初学笔记
  20. 科研论文citespace下载

热门文章

  1. 详解:非结构化数据治理
  2. 【Aactiviti7 从入门到放弃】(一)Activiti7工作流引擎入门
  3. 如何把mac照片导入u盘_苹果电脑怎么把文件复制到u盘
  4. php来电跳转,调用网站并使用php识别来电显示
  5. DevStudio · 云端开发平台
  6. 硕士论文查重检测哪些部分?
  7. 模版的分离编译 解决方案
  8. 视频!ASP.NET MVC 音乐商店 - 1 创建项目 2 控制器
  9. Android学习之重力传感器使用
  10. Geekbench 4 for Mac(mac跑分软件)