You are on page 1of 8

###################### 22.4.1 Importing the Python COM Modules from win32com.server.exception import COMException import win32com.server.util import win32com.client.

dynamic ###################### 22.4.2 Setting up the Python COMserver class # Previous part of the module comes here-usually just the 'import' statements abo ve class DemoServer: _reg_clsid_ = "{864C87C0-DCB8-11D0-A30E-444553540000}" _reg_desc_ = "PythonComExample DemoServer" _reg_progid_ = "PythonComExample.DemoServer" _reg_class_spec_ = "ar_com_servers.DemoServer" _public_methods_ = ['DoubleIt', 'AskMeAQuestion'] _readonly_attrs_ = ['author'] ###################### 22.4.3 Writing server class methods def __init__(self): self.author = 'Andy Robinson' def DoubleIt(self, num): return num * 2 def AskMeAQuestion(self, str): return "The answer is 42" ###################### 22.4.4 Registering the Python server class with COM def Register(): import win32com.server.register win32com.server.register.UseCommandLine(DemoServer) def UnRegister(): from win32com.server.register import UnregisterServer UnregisterServer(DemoServer()._reg_clsid_) print "DemoServer Class unregistered."

###################### 22.4.5 Test code def TestDirect(): ds = DemoServer() if ds.DoubleIt(2)==4: print 'passed direct test' def TestCOM(): try: ds = win32com.client.dynamic.Dispatch("PythonComExample.DemoServer") print 'DemoServer class created from COM' except: print "**** - The PythonComExample.DemoServer is not available" return if ds.DoubleIt(2)==4: print 'passed COM test'

###################### 22.4.6 Creating a module body if __name__=='__main__': import sys if "/unreg" in sys.argv: UnRegister() elif "/test" in sys.argv: print "doing direct tests..." TestDirect() print "testing COM" TestCOM() else: Register() ###################### 22.4.7 The Python COM server template as a whole # generic Python COM server template # import statements from win32com.server.exception import COMException import win32com.server.util import win32com.client.dynamic class DemoServer: # COM-specific special attributes. _reg_clsid_ = "{864C87C0-DCB8-11D0-A30E-444553540000}" _reg_desc_ = "PythonComExample DemoServer" _reg_progid_ = "PythonComExample.DemoServer" _reg_class_spec_ = "ar_com_servers.DemoServer" _public_methods_ = ['DoubleIt', 'AskMeAQuestion'] # You can use a _public_attrs_ list also _readonly_attrs_ = ['author'] # Class methods. def __init__(self): self.author = 'Andy Robinson' def DoubleIt(self, num): return num * 2 def AskMeAQuestion(self, str): return "The answer is 42" # Registration and unregistration functions-note that these are not methods! def Register(): import win32com.server.register win32com.server.register.UseCommandLine(DemoServer) def UnRegister(): from win32com.server.register import UnregisterServer UnregisterServer(DemoServer()._reg_clsid_) print "DemoServer Class unregistered." # Testing code-these are functions, not methods of the server class. def TestDirect(): ds = DemoServer() if ds.DoubleIt(2)==4:

print 'passed direct test' def TestCOM(): try: ds = win32com.client.dynamic.Dispatch( "PythonComExample.DemoServer") print 'DemoServer class created from COM' except: print "**** - The PythonComExample.DemoServer is not available" return if ds.DoubleIt(2)==4: print 'passed COM test' # This code is executed whenever the module is executed; it can be used to regis ter, unregister, # or test the module. if __name__=='__main__': import sys if "/unreg" in sys.argv: UnRegister() elif "/test" in sys.argv: print "doing direct tests..." TestDirect() print "testing COM" TestCOM() else: Register() ###################### 22.5 Creating and using the server from Visual Basic <Visual Basic code> Dim DemoSrv as Variant Set DemoSrv = CreateObject("PythonComExample.DemoServer") ###################### 22.5.2 Using the server <Visual Basic code> Option Explicit Public Server As Object Private Sub Form_Load() Set Server = CreateObject("PythonComExample.DemoServer") lblServerStatus.Caption = "DemoServer is up and running" End Sub Private Sub cmdAsk_Click() lblAskAnswer.Caption = Server.AskMeAQuestion(txtAsk.Text) End Sub Private Sub cmdDoubleIt_Click() lblDoubleResult.Caption = Server.DoubleIt(Val(txtDoubleInput.Text)) End Sub ###################### 22.5.3 Server shutdown def __del__(self):

"do something when freed" from time import time, gmtime, asctime f = open('C:\\temp\\ServerKilled.txt ','a') f.write('DemoServer shut down at' + asctime(gmtime(time()))) f.write('\n') f.close()

###################### 22.6.1 Numbers <Visual Basic code> Dim x as Integer X = DemoSrv.DoubleIt(2) <Python code> Def DoubleIt(self, number): return 2 * number ###################### 22.6.2 Stings <Visual Basic code> Dim S as String S = DemoSrv.Repeat("Hello") <Python code> def Repeat(self, word): # note use of 'str()' return 2 * str(word) ###################### 22.6.3 Retrieving lists <Visual Basic code> Dim pyList As Variant, item As Variant List1.Clear PyList = Server.GetList For Each item In pyList List1.AddItem item Next item <Python code> def GetList(self): # return mixed strings & numbers return ['heading'] + range(10) ###################### 22.6.4 Passing in lists <Visual Basic code> MyList = Array(1,2,3, "Spam") Server.Reverse(MyList)

<Python code> def Reverse(self, list): result = list.reverse() ###################### 22.6.5 Retrieving tabular data <Visual Basic code> Dim MyTable As Variant Dim Rows As Integer, Cols As Integer Dim x As Integer, y As Integer MyTable = Server.GetFinancials Rows = UBound(MyTable, 1) 'the first dimension Cols = UBound(MyTable, 2) 'the second dimension MSFlexGrid1.Rows = Rows MSFlexGrid1.Cols = Cols For y = 0 To Rows - 1 For x = 0 To Cols - 1 MSFlexGrid1.Row = y MSFlexGrid1.Col = x MSFlexGrid1.Text = MyTable(y, x) Next x Next y <Python code> def GetFinancials(self): # returns a list of tuples of # numbers and strings # eg.: # return [(1, "Hello"), (2, "G'bye"), ] ###################### 22.6.8 class Employee: _reg_clsid_ = "{DAFFCF40-24A4-11D2-BCC8-0040333B49A4}" _reg_desc_ = "PythonComExample Employee" _reg_progid_ = "PythonComExample.Employee" _reg_class_spec_ = "ar_com_servers.Employee" _public_methods_ = [] _public_attrs_ = ['name','salary'] def __init__(self): self.name = '<new employee>' self.salary = 0 #### # basic data management def AddEmployee(self, ComEmp): PyEmp = win32com.server.util.unwrap(ComEmp) self.employees.append(PyEmp)

def GetEmployee(self, idx): return win32com.server.util.wrap(self.employees[idx]) def DeleteEmployee(self, idx): del self.employees[idx] def CountEmployees(self): return len(self.employees) def ReportEmployees(self): reportList = [] for emp in self.employees: reportList.append(emp.name + ': ' + str(emp.salary)) return reportList #### <Visual Basic code> Private Sub cmdAddEmp_Click() Dim Emp As Object Set Emp = CreateObject("PythonComExample.Employee") Emp.Name = txtName.Text Emp.Salary = Val(txtSalary.Text) Server.AddEmployee Emp End Sub ###################### 22.7 Callbacks <Visual Basic code> Public Sub DrawLine(x1, y1, x2, y2) Picture1.Line (x1, y1)-(x2, y2) End Sub Private Sub cmdLetPythonDraw_Click() Server.DrawOn Me End Sub <Python code> def DrawOn(self, vbForm): from random import random pyForm = win32com.client.dynamic.Dispatch(vbForm) for i in range(20): x1 = int(random() * 200) y1 = int(random() * 200) x2 = int(random() * 200) y2 = int(random() * 200) pyForm.DrawLine(x1,y1,x2,y2)

###################### 22.8.2 Fetching data (Excel client)

<Visual Basic code> Private Sub cmdFetchFinancials_Click() 'push array data out Dim mystuff As Variant mystuff = DemoSrv.GetFinancials Worksheets("Sheet2").Range("C7:p27").Value = mystuff End Sub ###################### 22.10.1 Fetching data from Access from win32com.client.dynamic import Dispatch dbEngine = Dispatch('DAO.DBEngine') db = dbEngine.OpenDatabase('C:\\Database\\Recept.mdb') db = dbEngine.OpenDatabase('C:\\Database\\Recept.mdb') MyQueryString = "SELECT MemberID, FirstName, Surname FROM Members ORDER BY Membe rID" MyRecordset = db.OpenRecordset(MyQueryString) MyRecordset.MoveFirst() FieldCount = MyRecordset.Fields.Count while not MyRecordset.EOF: row = [] for i in range(FieldCount): MyFieldValue = MyRecordset.Fields(i).Value row.append(MyFieldValue) print row MyRecordset.MoveNext() #move to next record ###################### 22.10.2 Update an Access record MyDatabase.Execute("UPDATE Members SET FirstName = 'John' WHERE FirstName = 'Jon '") MyRecordset.MoveFirst() MyRecordset.Edit() MyRecordset.Fields('Surname').Value = 'Robinson' MyRecordset.Update() ###################### 22.10.3 Start Excel from Python, push in some data xlApp = Dispatch("Excel.Application") xlApp.WorkBooks.Add() xlApp.Range('A1:C1').Value = ['January','February','March'] ###################### 22.10.4 Start Word, push in some data Word = Dispatch("Word.Application") Word.Visible = 1 WordDoc = Word.Documents.Add() WordRange = WordDoc.Range() WordRange.InsertAfter('Python was here') ###################### 22.13.1 Windows Scripting Host

# get at the Shell object, which knows how to make shortcuts WSHShell = WScript.CreateObject("WScript.Shell") # Put a shortcut to Notepad on the desktop. DesktopPath = WSHShell.SpecialFolders("Desktop") MyShortcut = WSHShell.CreateShortcut(DesktopPath + "\\A shortcut to notepad.lnk") MyShortcut.TargetPath =WSHShell.ExpandEnvironmentStrings( "%windir%\\notepad.exe") MyShortcut.WorkingDirectory = WSHShell.ExpandEnvironmentStrings("%windir%") MyShortcut.WindowStyle = 4 MyShortcut.IconLocation = WSHShell.ExpandEnvironmentStrings( "%windir%\\notepad.exe, 0") MyShortcut.Save() # now put a shortcut to Notepad in the start menu StartMenuPath = WSHShell.SpecialFolders("StartMenu") MyShortcut = WSHShell.CreateShortcut(StartMenuPath + "\\Another shortcut to note pad.lnk") MyShortcut.TargetPath = WSHShell.ExpandEnvironmentStrings( "%windir%\\notepad.exe") MyShortcut.WorkingDirectory = \ WSHShell.ExpandEnvironmentStrings("%windir%") MyShortcut.WindowStyle = 4 MyShortcut.IconLocation = \ WSHShell.ExpandEnvironmentStrings("%windir%\\notepad.exe, 0") MyShortcut.Save() WScript.Echo("Shortcuts created") ###################### 22.13.2 ODBC import dbi, odbc MyConnection = odbc.odbc('RECEPT') MyCursor = MyConnection.cursor() MyCursor.execute('SELECT FirstName, Surname FROM Members') print MyCursor.fetchall()

You might also like