用python编写com server程序 Com server using python preparation procedures
因为同事工作上需要使用到htmltidy (一个开源的用于规正html代码的工具。用来对html代码进行格式化,效果非常好),但平时使用的是delphi,虽然其主页上提供了delphi的封装包,但是可能是版本比较旧的缘故,无法处理繁体中文和日文。 Work because my colleagues need to use to htmltidy (an open source code for the regulation is a tool for html. Used to html code format, the effect was very good), but in peacetime use the delphi, although its home page to provide a delphi The package, but may be the older version of the reason, not able to deal with Traditional Chinese and Japanese.
我看了一下,上面有phthon的封装包,于是试了一下,发现能很好的处理多国语言,于是就想起写一个com server让他调用. I read about the top of the package have phthon, then tried to found a better job handling multiple languages, therefore reminded to write on a com server let him call.
用python实现com非常简单,具体实现可以参考《 Python Programming on Win32 》,这是一本介绍python window编程,非常经典的书籍。 Com using python achieve very simple, concrete realization of reference "Python Programming on Win32" This is a program introduced python window, very classic books.
这里我介绍一下实现步骤: Here, I explain to achieve steps:
- 下载并安装Python wrapper for TidyLib ,因为该库依赖于ctypes库,所以您可能还需要安装ctypes库 Download and install Python wrapper for TidyLib because it relies on the ctypes library, so you may also want to install the ctypes
- 下载并安装pywin32 Download and install pywin32
- 实现起来很简单,代码如下: PLAIN TEXT It's easy to achieve, the following code: PLAIN TEXT
PYTHON: PYTHON:
#–coding:utf8– #-Coding:-utf8
# pytidycom.py # Pytidycom.py
# #
# A contrived sample Python server that demonstrates # A contrived sample Python server that demonstrates
# wrapping, unwrapping, and passing IDispatch objects. # Wrapping and unwrapping, and passing IDispatch objects.
# Import the utilities for wrapping and unwrapping. # Import the utilities for wrapping and unwrapping.
from win32com. server . util import wrap, unwrap From win32com. Server. Util import wrap, unwrap
import win32com. client Import win32com. Client
import tidy Import tidy
# Although we are able to register our Parent object for debugging, # Although we are able to register our Parent object for debugging,
# our Child object is not registered, so this won’t work. To get # Our Child object is not registered, so this won't work. To get
# the debugging behavior for our wrapped objects, we must do it ourself. # The debugging behavior for our wrapped objects, we must do it ourself.
debugging = 1 Debugging = 1
if debugging: If debugging:
from win32com. server . dispatcher import DefaultDebugDispatcher From win32com. Server. Dispatcher import DefaultDebugDispatcher
useDispatcher = DefaultDebugDispatcher UseDispatcher = DefaultDebugDispatcher
else : Else:
useDispatcher = None UseDispatcher = None
# Our Parent object. # Our Parent object.
# This is registered, and therefore creatable # This is registered, and therefore creatable
# using CreateObject etc from VB. # Using CreateObject etc from VB.
class Parse: Class Parse:
_public_methods_ = [ ‘parseString’ ] _public_methods_ = [ 'ParseString']
# Use “print pythoncom.CreateGuid()” to make a new one. # Use the "print pythoncom.CreateGuid ()" to make a new one.
_reg_clsid_ = “{7AB98634-4E1E-40D0-8970-27CC9B1A1C40}” _reg_clsid_ = "(7AB98634-4E1E-40D0-8970-27CC9B1A1C40)"
_reg_progid_ = “pytidycom.Parse” _reg_progid_ = "Pytidycom.Parse"
def parseString ( self ,msg ) : Def parseString (self, msg):
msg= unicode ( msg ) Msg = unicode (msg)
Options= dict ( char_encoding= ‘utf8′ ,show_body_only= True ,output_html= True ,input_encoding= ‘utf8′ ,output_encoding= ‘utf8′ ) Options = dict (char_encoding = 'utf8' show_body_only = True, output_html = True, input_encoding = 'utf8' output_encoding = 'utf8')
msg=tidy. parseString ( msg. encode ( ‘utf8′ ) ,**Options ) Msg = tidy. ParseString (msg. encode ( 'utf8'), ** Options)
#msg=tidy.parseString(’test’) Msg = # tidy.parseString ( 'test')
#return msg # Return msg
return str ( msg ) . decode ( ‘utf8′ ) Return str (msg). Decode ( 'utf8')
if __name__== ‘__main__’ : If __name__ == '__main__':
import win32com. server . register Import win32com. Server. Register
win32com. server . register . UseCommandLine ( Parse, debug=debugging ) Win32com. Server. Register. UseCommandLine (Parse, debug = debugging)
以上的代码创建了一个简单输出parseString的com server The above code to create a simple output of the com server parseString
您可以像这样用vbs调用它 You can use this as you called it vbsVisual Basic: Visual Basic:
Set TidyObj = CreateObject ( “pytidycom.Parse” ) Set TidyObj = CreateObject ( "pytidycom.Parse")
theString =TidyObj. parseString ( “<a>總統” ) TheString = TidyObj. ParseString ( "<a> president")
msgbox theString Msgbox theString
- 将其封装成成dll或exe Be packaged as a dll or exe
这里我使用py2exe进行打包生成pytidycom.dll和pytidycom.exe(您也可以设置成只生成其中之一),使用regsrv32 pytidycom.dll或pytidycom.exe /register注册,这样就可以像其他正常的windows程序一样调用,而不用带python环境了,虽然体积有点大,但效果还是不错的。 Here, I use a package py2exe generated pytidycom.dll and pytidycom.exe (You also can be configured to generate only one), or use regsrv32 pytidycom.dll pytidycom.exe / register registered, and this can be like other normal windows procedure call, and not with python environment, although volume somewhat, but the effect is quite good. 这里要注意的是打包后需要将cygtidy-0-99-0.dll这个动态库和打包后的程序放在一起,否则调用会失败 It should be noted here is the need to pack after cygtidy-0-99-0.dll this dynamic library and package put together after the procedure, otherwise call will fail #–coding:utf-8– #-Coding: utf-8 -
# This is the distutils script for creating a Python-based com (exe or dll) # This is the distutils script for creating a Python-based com (exe or dll)
# server using win32com. This script should be run like this: # Server using win32com. This script should be run like this:
# #
# % python setup.py py2exe #% Python setup.py py2exe
# #
# After you run this (from this directory) you will find two directories here: # After you run this (from this directory) you will find two directories here:
# “build” and “dist”. The .dll or .exe in dist is what you are looking for. # "Build" and "dist." The. Dll or. Exe in dist is what you are looking for.
############################################################################## ################################################## ############################
from distutils . core import setup From distutils. Core import setup
import py2exe Import py2exe
import sys Import sys
if len ( sys . argv ) == 1 : If len (sys. Argv) == 1:
sys . argv . append ( “py2exe” ) Sys. Argv. Append ( "py2exe")
class Target: Class Target:
def __init__ ( self , **kw ) : Def __init__ (self, ** kw):
self . __dict__ . update ( kw ) Self. __dict__. Update (kw)
# for the version info resources (Properties — Version) # For the version info resources (Properties - Version)
self . version = “0.0.1″ Self. Version = "0.0.1"
self . company_name = u “XXXXX” Self. Company_name = u "XXXXX"
self . copyright = u “© 2006, yxl” Self. Copyright = u "© 2006, yxl"
self . name = “htmltidy(python) activex” Self. Name = "htmltidy (python) activex"
my_com_server_target = Target ( Target my_com_server_target = (
description = “htmltidy(python) activex” , Description = "htmltidy (python) activex"
# use module name for win32com exe/dll server # Use module name for win32com exe / dll server
modules = [ “pytidycom” ] , Modules = [ "pytidycom"]
# specify which type of com server you want (exe and/or dll) # Specify which type of com server you want (exe and / or dll)
create_exe = True , Create_exe = True,
create_dll = True Create_dll = True
) )
excludes = [ ] #[”pywin”, “pywin.debugger”, “pywin.debugger.dbgcon”, Excludes = [] # [ "pywin", "pywin.debugger", "pywin.debugger.dbgcon"
# “pywin.dialogs”, “pywin.dialogs.list”, “win32com.client”] # "Pywin.dialogs", "pywin.dialogs.list", "win32com.client"]
setup ( Setup (
name= “pytidycom” , Name = "pytidycom"
# the following two parameters embed support files within exe/dll file # The following two parameters embed support files within exe / dll file
options= { “py2exe” : { “bundle_files” : 1 , Options = ( "py2exe": ( "bundle_files": 1.
“dll_excludes” : [ “w9xpopen.exe” ] , ‘excludes’ :excludes, ‘packages’ : [ ‘encodings’ , ‘tidy’ , ‘ctypes’ ] "Dll_excludes": [ "w9xpopen.exe"], 'excludes': excludes,' packages': [ 'encodings',' tidy ',' ctypes']
} } , ))
zipfile = None , Zipfile = None,
version= “0.0.1″ , Version = "0.0.1"
description= “htmltidy(python)” , Description = "htmltidy (python)."
# author, maintainer, contact go here: # Author, maintainer, contact go here:
author= “chyni” , Author = "chyni"
author_email= “coolchyni@gmail.com” , Author_email = "coolchyni@gmail.com"
com_server= [ my_com_server_target ] Com_server = [my_com_server_target]
) )
这里是setup.py的代码 Here is the code setup.py
PYTHON: PYTHON:




