追风逐月

关注网络赚钱、网赚经验、网赚工具、SEO、国外主机信息

推荐使用

订阅追风逐月博客feed
订阅到google 订阅到哪吒
订阅到鲜果 订阅到抓虾
* 更多订阅本站方式请看 订阅帮助

用python编写com server程序

2007年04月19日 • 追风逐月 • 分类: 技术开发

因为同事工作上需要使用到htmltidy(一个开源的用于规正html代码的工具。用来对html代码进行格式化,效果非常好),但平时使用的是delphi,虽然其主页上提供了delphi的封装包,但是可能是版本比较旧的缘故,无法处理繁体中文和日文。
我看了一下,上面有phthon的封装包,于是试了一下,发现能很好的处理多国语言,于是就想起写一个com server让他调用.
python实现com非常简单,具体实现可以参考《Python Programming on Win32》,这是一本介绍python window编程,非常经典的书籍。
这里我介绍一下实现步骤:

  1. 下载并安装Python wrapper for TidyLib,因为该库依赖于ctypes库,所以您可能还需要安装ctypes库
  2. 下载并安装pywin32
  3. 实现起来很简单,代码如下:PLAIN TEXT

    PYTHON:

    1. #–coding:utf8–

    2. # pytidycom.py

    3. #

    4. # A contrived sample Python server that demonstrates

    5. # wrapping, unwrapping, and passing IDispatch objects.

    6.  

    7. # Import the utilities for wrapping and unwrapping.

    8. from win32com.server.util import wrap, unwrap

    9.  

    10. import win32com.client

    11. import tidy

    12.  

    13. # Although we are able to register our Parent object for debugging,

    14. # our Child object is not registered, so this won’t work. To get

    15. # the debugging behavior for our wrapped objects, we must do it ourself.

    16. debugging = 1

    17. if debugging:

    18. from win32com.server.dispatcher import DefaultDebugDispatcher

    19. useDispatcher = DefaultDebugDispatcher

    20. else:

    21. useDispatcher = None

    22.  

    23. # Our Parent object.

    24. # This is registered, and therefore creatable

    25. # using CreateObject etc from VB.

    26. class Parse:

    27. _public_methods_ = [‘parseString’]

    28. # Use “print pythoncom.CreateGuid()” to make a new one.

    29. _reg_clsid_ = “{7AB98634-4E1E-40D0-8970-27CC9B1A1C40}”

    30. _reg_progid_ = “pytidycom.Parse”

    31.  

    32. def parseString(self,msg):

    33. msg=unicode(msg)

    34. Options=dict(char_encoding=‘utf8′,show_body_only=True,output_html=True,input_encoding=‘utf8′,output_encoding=‘utf8′)

    35. msg=tidy.parseString(msg.encode(‘utf8′),**Options)

    36. #msg=tidy.parseString(’test’)

    37. #return msg

    38. return str(msg).decode(‘utf8′)

    39.  

    40. if __name__==‘__main__’:

    41. import win32com.server.register

    42. win32com.server.register.UseCommandLine(Parse, debug=debugging)

    以上的代码创建了一个简单输出parseString的com server
    您可以像这样用vbs调用它

    PLAIN TEXT

    Visual Basic:

    1. Set TidyObj = CreateObject(“pytidycom.Parse”)

    2. theString =TidyObj.parseString(“<a>總統”)

    3. msgbox theString

  4. 将其封装成成dll或exe
    这里我使用py2exe进行打包生成pytidycom.dll和pytidycom.exe(您也可以设置成只生成其中之一),使用regsrv32 pytidycom.dll或pytidycom.exe /register注册,这样就可以像其他正常的windows程序一样调用,而不用带python环境了,虽然体积有点大,但效果还是不错的。这里要注意的是打包后需要将cygtidy-0-99-0.dll这个动态库和打包后的程序放在一起,否则调用会失败
  5. 这里是setup.py的代码

    PLAIN TEXT

    PYTHON:

    1. #–coding:utf-8–

    2. # This is the distutils script for creating a Python-based com (exe or dll)

    3. # server using win32com. This script should be run like this:

    4. #

    5. # % python setup.py py2exe

    6. #

    7. # After you run this (from this directory) you will find two directories here:

    8. # “build” and “dist”. The .dll or .exe in dist is what you are looking for.

    9. ##############################################################################

    10.  

    11. from distutils.core import setup

    12. import py2exe

    13. import sys

    14. if len(sys.argv) == 1:

    15. sys.argv.append(“py2exe”)

    16.  

    17. class Target:

    18. def __init__(self, **kw):

    19. self.__dict__.update(kw)

    20. # for the version info resources (Properties — Version)

    21. self.version = “0.0.1″

    22. self.company_name = u“XXXXX”

    23. self.copyright = u“© 2006, yxl”

    24. self.name = “htmltidy(python) activex”

    25.  

    26. my_com_server_target = Target(

    27. description = “htmltidy(python) activex”,

    28. # use module name for win32com exe/dll server

    29. modules = [“pytidycom”],

    30. # specify which type of com server you want (exe and/or dll)

    31. create_exe = True,

    32. create_dll = True

    33. )

    34. excludes = []#[”pywin”, “pywin.debugger”, “pywin.debugger.dbgcon”,

    35. # “pywin.dialogs”, “pywin.dialogs.list”, “win32com.client”]

    36. setup(

    37. name=“pytidycom”,

    38. # the following two parameters embed support files within exe/dll file

    39. options={“py2exe”: {“bundle_files”: 1,

    40. “dll_excludes”: [“w9xpopen.exe”],‘excludes’:excludes,‘packages’:[‘encodings’,‘tidy’,‘ctypes’]

    41. }},

    42. zipfile=None,

    43. version=“0.0.1″,

    44. description=“htmltidy(python)”,

    45. # author, maintainer, contact go here:

    46. author=“chyni”,

    47. author_email=“coolchyni@gmail.com”,

    48.  

    49. com_server=[my_com_server_target]

    50. )

标签: ,

你可能还喜欢



发表你的意见