我们从Python开源项目中,提取了以下29个代码示例,用于说明如何使用win32com.client.gencache.EnsureDispatch()。
def test(): import win32com.client oldcwd = os.getcwd() try: session = gencache.EnsureDispatch("MAPI.Session") try: session.Logon(GetDefaultProfileName()) except pythoncom.com_error, details: print "Could not log on to MAPI:", details return except pythoncom.error: # no mapi.session - let's try outlook app = gencache.EnsureDispatch("Outlook.Application") session = app.Session try: TestUser(session) TestAddress(session) DumpFolders(session) finally: session.Logoff() # It appears Exchange will change the cwd on us :( os.chdir(oldcwd)
def testLeaksGencache(self): try: gtrc = sys.gettotalrefcount except AttributeError: print "Please run this with python_d for leak tests" gtrc = lambda: 0 # note creating self.object() should have consumed our "one time" leaks object = EnsureDispatch("Python.Test.Pippo") start = gtrc() for i in range(1000): object = EnsureDispatch("Python.Test.Pippo") object.Method1() object = None end = gtrc() if end-start > 10: self.fail("We lost %d references!" % (end-start,))
def test(): import win32com.client oldcwd = os.getcwd() try: session = gencache.EnsureDispatch("MAPI.Session") try: session.Logon(GetDefaultProfileName()) except pythoncom.com_error as details: print("Could not log on to MAPI:", details) return except pythoncom.error: # no mapi.session - let's try outlook app = gencache.EnsureDispatch("Outlook.Application") session = app.Session try: TestUser(session) TestAddress(session) DumpFolders(session) finally: session.Logoff() # It appears Exchange will change the cwd on us :( os.chdir(oldcwd)
def testLeaksGencache(self): try: gtrc = sys.gettotalrefcount except AttributeError: print("Please run this with python_d for leak tests") gtrc = lambda: 0 # note creating self.object() should have consumed our "one time" leaks object = EnsureDispatch("Python.Test.Pippo") start = gtrc() for i in range(1000): object = EnsureDispatch("Python.Test.Pippo") object.Method1() object = None end = gtrc() if end-start > 10: self.fail("We lost %d references!" % (end-start,))
def setUp(self): def factory(): # Our VB test harness exposes a property with IEnumVariant. ob = self.object.EnumerableCollectionProperty for i in self.expected_data: ob.Add(i) # Get the raw IEnumVARIANT. invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET iter = ob._oleobj_.InvokeTypes(pythoncom.DISPID_NEWENUM,0,invkind,(13, 10),()) return ob, iter.QueryInterface(pythoncom.IID_IEnumVARIANT) # We *need* generated dispatch semantics, so dynamic __getitem__ etc # don't get in the way of our tests. self.object = EnsureDispatch("PyCOMVBTest.Tester") self.expected_data = [1, "Two", "3"] self.iter_factory = factory
def GenerateSupport(): # dao gencache.EnsureModule("{00025E01-0000-0000-C000-000000000046}", 0, 4, 0) # Access # gencache.EnsureModule("{4AFFC9A0-5F99-101B-AF4E-00AA003F0F07}", 0, 8, 0) gencache.EnsureDispatch("Access.Application")
def TestWord(): # Try and load the object exposed by Word 8 # Office 97 - _totally_ different object model! try: # NOTE - using "client.Dispatch" would return an msword8.py instance! print "Starting Word 8 for dynamic test" word = win32com.client.dynamic.Dispatch("Word.Application") TestWord8(word) word = None # Now we will test Dispatch without the new "lazy" capabilities print "Starting Word 8 for non-lazy dynamic test" dispatch = win32com.client.dynamic._GetGoodDispatch("Word.Application") typeinfo = dispatch.GetTypeInfo() attr = typeinfo.GetTypeAttr() olerepr = win32com.client.build.DispatchItem(typeinfo, attr, None, 0) word = win32com.client.dynamic.CDispatch(dispatch, olerepr) dispatch = typeinfo = attr = olerepr = None TestWord8(word) except pythoncom.com_error: print "Starting Word 7 for dynamic test" word = win32com.client.Dispatch("Word.Basic") TestWord7(word) print "Starting MSWord for generated test" from win32com.client import gencache word = gencache.EnsureDispatch("Word.Application.8") TestWord8(word)
def setUp(self): self.arr = gencache.EnsureDispatch("PyCOMTest.ArrayTest")
def testGenerated(self): re = EnsureDispatch("VBScript.Regexp") self._TestVBScriptRegex(re)
def makeRealWordDoc(infile, outfile): word = gencache.EnsureDispatch("Word.Application") try: worddoc = word.Documents.Open(FileName=infile) try: worddoc.TablesOfContents.Add(Range=word.ActiveWindow.Selection.Range, \ RightAlignPageNumbers=1, \ UseHeadingStyles=1, \ UpperHeadingLevel=1, \ LowerHeadingLevel=2, \ IncludePageNumbers=1, \ AddedStyles='', \ UseHyperlinks=1, \ HidePageNumbersInWeb=1) worddoc.TablesOfContents(1).TabLeader = constants.wdTabLeaderDots worddoc.TablesOfContents.Format = constants.wdIndexIndent word.ActiveWindow.ActivePane.View.SeekView = constants.wdSeekCurrentPageHeader word.Selection.TypeText(Text="Dive Into Python\t\thttp://diveintopython.org/") word.ActiveWindow.ActivePane.View.SeekView = constants.wdSeekCurrentPageFooter word.NormalTemplate.AutoTextEntries("- PAGE -").Insert(Where=word.ActiveWindow.Selection.Range) word.ActiveWindow.View.Type = constants.wdPrintView worddoc.TablesOfContents(1).Update() worddoc.SaveAs(FileName=outfile, \ FileFormat=constants.wdFormatDocument) finally: worddoc.Close(0) del worddoc finally: word.Quit() del word
def setUp(self): self.tablename = "pywin32test_users" self.db_filename = None self.conn = self.cur = None try: # Test any database if a connection string is supplied... conn_str = os.environ['TEST_ODBC_CONNECTION_STRING'] except KeyError: # Create a local MSAccess DB for testing. self.db_filename = tempfile.NamedTemporaryFile().name + '.mdb' # Create a brand-new database - what is the story with these? for suffix in (".36", ".35", ".30"): try: dbe = EnsureDispatch("DAO.DBEngine" + suffix) break except pythoncom.com_error: pass else: raise TestSkipped("Can't find a DB engine") workspace = dbe.Workspaces(0) newdb = workspace.CreateDatabase(self.db_filename, constants.dbLangGeneral, constants.dbEncrypt) newdb.Close() conn_str = "Driver={Microsoft Access Driver (*.mdb)};dbq=%s;Uid=;Pwd=;" \ % (self.db_filename,) ## print 'Connection string:', conn_str self.conn = odbc.odbc(conn_str) # And we expect a 'users' table for these tests. self.cur = self.conn.cursor() ## self.cur.setoutputsize(1000) try: self.cur.execute("""drop table %s""" %self.tablename) except (odbc.error, odbc.progError): pass ## This needs to be adjusted for sql server syntax for unicode fields ## - memo -> TEXT ## - varchar -> nvarchar self.assertEqual(self.cur.execute( """create table %s ( userid varchar(25), username varchar(25), bitfield bit, intfield integer, floatfield float, datefield datetime, rawfield varbinary(100), longtextfield memo, longbinaryfield image )""" %self.tablename),-1)
def makemdb(testfolder, mdb_name): # following setup code borrowed from pywin32 odbc test suite # kindly contributed by Frank Millman. import os _accessdatasource = os.path.join(testfolder, mdb_name) if not os.path.isfile(_accessdatasource): try: from win32com.client.gencache import EnsureDispatch from win32com.client import constants win32 = True except ImportError: #perhaps we are running IronPython win32 = False #iron Python try: from System import Activator, Type except: pass # Create a brand-new database - what is the story with these? dbe = None for suffix in (".36", ".35", ".30"): try: if win32: dbe = EnsureDispatch("DAO.DBEngine" + suffix) else: type= Type.GetTypeFromProgID("DAO.DBEngine" + suffix) dbe = Activator.CreateInstance(type) break except: pass if dbe: print(' ...Creating ACCESS db at '+_accessdatasource) if win32: workspace = dbe.Workspaces(0) newdb = workspace.CreateDatabase(_accessdatasource, constants.dbLangGeneral, constants.dbEncrypt) else: newdb = dbe.CreateDatabase(_accessdatasource,';LANGID=0x0409;CP=1252;COUNTRY=0') newdb.Close() else: print(' ...copying test ACCESS db to '+_accessdatasource) mdbName = os.path.normpath(os.getcwd() + '/../examples/test.mdb') import shutil shutil.copy(mdbName, _accessdatasource) return _accessdatasource
def makemdb(testfolder, mdb_name): # following setup code borrowed from pywin32 odbc test suite # kindly contributed by Frank Millman. import os _accessdatasource = os.path.join(testfolder, mdb_name) if not os.path.isfile(_accessdatasource): try: from win32com.client.gencache import EnsureDispatch from win32com.client import constants win32 = True except ImportError: #perhaps we are running IronPython win32 = False #iron Python try: from System import Activator, Type except: pass # Create a brand-new database - what is the story with these? dbe = None for suffix in (".36", ".35", ".30"): try: if win32: dbe = EnsureDispatch("DAO.DBEngine" + suffix) else: type= Type.GetTypeFromProgID("DAO.DBEngine" + suffix) dbe = Activator.CreateInstance(type) break except: pass if dbe: print((' ...Creating ACCESS db at '+_accessdatasource)) if win32: workspace = dbe.Workspaces(0) newdb = workspace.CreateDatabase(_accessdatasource, constants.dbLangGeneral, constants.dbEncrypt) else: newdb = dbe.CreateDatabase(_accessdatasource,';LANGID=0x0409;CP=1252;COUNTRY=0') newdb.Close() else: print((' ...copying test ACCESS db to '+_accessdatasource)) mdbName = os.path.normpath(os.getcwd() + '/../examples/test.mdb') import shutil shutil.copy(mdbName, _accessdatasource) return _accessdatasource