def Excel2Html(file, overwrite=True, show=True, leaveItOpen = True, width="100%", length="400px"): f = file.replace("/", "\\"); #xl = Dispatch('Excel.Application') xl = EnsureDispatch ("Excel.Application") cwd=os.getcwd() + "\\" + f ext = cwd.split(".")[-1] nef=cwd.replace(ext, "html") nhtml = file.replace(ext, "html") fileOpenNow = False; # if (not os.path.exists(cwd)): # display("File " + cwd + " not found"); # return; # else: # try: # f = open(cwd, "r+"); # f.close(); # except: # fileOpenNow =True; print (cwd, nef, nhtml, fileOpenNow) wb=xl.Workbooks.Open(cwd) xl.Visible = True #-- optional if os.path.exists(nef): os.remove(nef) wb.SaveAs(nef, constants.xlHtml) wb.Close() # if (fileOpenNow or leaveItOpen): wb=xl.Workbooks.Open(cwd) del xl; if (show): display(IFrame(nhtml, width, length))
def call_api(self): outlook = Dispatch("Outlook.Application") mapi = outlook.GetNamespace("MAPI") Accounts = mapi.Folders #解析邮件内容 if self.mail_title != "": try: for Account in Accounts: if Account.Name == self.account_name: Folders = Account.Folders #读取该账户下的文件夹列表 for Folder in Folders: #第一层目录 if len(self.folder_name[0]) == 0: #输入文件夹为空 if Folder.Name == "收件箱": mail_info = self.save_attachments( Folder) #调用邮件解析和附件下载函数 elif len(self.folder_name) == 1: if Folder.Name == self.folder_name[0]: mail_info = self.save_attachments( Folder) #调用邮件解析和附件下载函数 else: if Folder.Name == self.folder_name[0]: for i in range(1, len(self.folder_name)): for Folder2 in Folder.Folders: if Folder2.Name == self.folder_name[ i]: Folder = Folder2 mail_info = self.save_attachments( Folder) #调用邮件解析和附件下载函数 return (mail_info) except: traceback.print_exc() sys.exit() else: return ("邮件title不能为空!~")
def __init__(self): # make sure the Python wrappers are available for the COM client and # interfaces EnsureModule('ZOSAPI_Interfaces', 0, 1, 0) # Note - the above can also be accomplished using 'makepy.py' in the # following directory: # {PythonEnv}\Lib\site-packages\wind32com\client\ # Also note that the generate wrappers do not get refreshed when the # COM library changes. # To refresh the wrappers, you can manually delete everything in the # cache directory: # {PythonEnv}\Lib\site-packages\win32com\gen_py\*.* self.TheConnection = EnsureDispatch("ZOSAPI.ZOSAPI_Connection") if self.TheConnection is None: raise PythonStandaloneApplication.ConnectionException( "Unable to intialize COM connection to ZOSAPI") self.TheApplication = self.TheConnection.CreateNewApplication() if self.TheApplication is None: raise PythonStandaloneApplication.InitializationException( "Unable to acquire ZOSAPI application") if self.TheApplication.IsValidLicenseForAPI == False: raise PythonStandaloneApplication.LicenseException( "License is not valid for ZOSAPI use") self.TheSystem = self.TheApplication.PrimarySystem if self.TheSystem is None: raise PythonStandaloneApplication.SystemNotPresentException( "Unable to acquire Primary system")
def __init__(self, retain_dir=None): """ :param retain_dir: Retains recognized audio and/or metadata in the given directory, saving audio to ``retain_[timestamp].wav`` file and metadata to ``retain.tsv``. Disabled by default (``None``). :type retain_dir: str|None """ EngineBase.__init__(self) DelegateTimerManagerInterface.__init__(self) EnsureDispatch(self.recognizer_dispatch_name) EnsureDispatch("SAPI.SpVoice") self._recognizer = None self._speaker = None self._compiler = None self._recognition_observer_manager = Sapi5RecObsManager(self) self._timer_manager = DelegateTimerManager(0.02, self) if isinstance(retain_dir, string_types) or retain_dir is None: self._retain_dir = retain_dir else: self._retain_dir = None self._log.error("Invalid retain_dir: %r" % retain_dir)
def read_outlook_mailbox(): """连接Outlook邮箱,读取收件箱内的邮件内容""" # 使用MAPI协议连接Outlook account = Dispatch('Outlook.Application').GetNamespace('MAPI') # 获取收件箱所在位置 inbox = account.GetDefaultFolder(6) # 数字6代表收件箱 # 获取收件箱下的所有邮件 mails = inbox.Items mails.Sort('[ReceivedTime]', True) # 邮件按时间排序 # 读取收件箱内前3封邮件的所有信息(下标从1开始) for index in range(1, 4): print('正在读取第[{}]封邮件...'.format(index)) mail = mails.Item(index) print('接收时间:{}'.format(str(mail.ReceivedTime)[:-6])) print('发件人:{}'.format(mail.SenderName)) print('收件人:{}'.format(mail.To)) print('抄送人:{}'.format(mail.CC)) print('主题:{}'.format(mail.Subject)) print('邮件正文内容:{}'.format(mail.Body)) print('邮件附件数量:{}'.format(mail.Attachments.Count)) print('邮件MessageID:{}'.format(mail.EntryID)) print('会话主题:{}'.format(mail.ConversationTopic)) print('会话ID:{}'.format(mail.ConversationID)) print('会话记录相对位置:{}'.format(mail.ConversationIndex)) # 保存邮件中的附件,如果没有附件不会执行也不会产生异常 attachment = mail.Attachments for each in attachment: save_attachment_path = os.getcwd() # 保存附件到当前路径 each.SaveAsFile(r'{}\{}'.format(save_attachment_path, each.FileName)) print('附件({})保存完毕'.format(each.FileName))
def connection (): global _connection if _connection is None: _connection = EnsureDispatch ("ADODB.Connection") _connection.Provider = "ADsDSOObject" _connection.Open ("Active Directory Provider") return _connection
def __init__(self): EnsureDispatch("SAPI.SpSharedRecognizer") EnsureDispatch("SAPI.SpVoice") self._recognizer = Dispatch("SAPI.SpSharedRecognizer") self._speaker = Dispatch("SAPI.SpVoice") self._compiler = Sapi5Compiler() self._recognition_observer_manager = None
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 convertExcel (fname): yourExcelFile = fname + '.xlsx' newFileName = fname + '.html' xl = EnsureDispatch('Excel.Application') wb = xl.Workbooks.Open(yourExcelFile) wb.SaveAs(newFileName, constants.xlHtml) xl.Workbooks.Close() xl.Quit() del xl
def getdocsfolder(): # Gets local user document folder and appends 'Autosaves' oshell = EnsureDispatch("Wscript.Shell") docs = oshell.SpecialFolders("MyDocuments") directory = os.path.join(docs, "autosaves") os.makedirs(directory, exist_ok=True) return directory
def __init__(self): EngineBase.__init__(self) EnsureDispatch(self._recognizer_dispatch_name) EnsureDispatch("SAPI.SpVoice") self._recognizer = None self._speaker = None self._compiler = None self._recognition_observer_manager = Sapi5RecObsManager(self)
def PassProtect(Path, Pass): from win32com.client.gencache import EnsureDispatch xlApp = EnsureDispatch("Excel.Application") xlwb = xlApp.Workbooks.Open(Path) xlApp.DisplayAlerts = False xlwb.Visible = False xlwb.SaveAs(Path, Password=Pass) xlwb.Close() xlApp.Quit()
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 os.path.isfile(_accessdatasource): print("using JET database=", _accessdatasource) else: 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.dbVersion40 ) else: newdb = dbe.CreateDatabase( _accessdatasource, ";LANGID=0x0409;CP=1252;COUNTRY=0" ) newdb.Close() else: print(" ...copying test ACCESS db to " + _accessdatasource) mdbName = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "examples", "test.mdb") ) import shutil shutil.copy(mdbName, _accessdatasource) return _accessdatasource
def __init__(self): # EnsureDispatch("SAPI.SpSharedRecognizer") EnsureDispatch(SAPI_recognizer) EnsureDispatch("SAPI.SpVoice") # self._recognizer = Dispatch("SAPI.SpSharedRecognizer") self._recognizer = Dispatch(SAPI_recognizer) self._recognizer.AudioInputStream = Dispatch("SAPI.SpMMAudioIn") self._speaker = Dispatch("SAPI.SpVoice") self._compiler = Sapi5Compiler() self._recognition_observer_manager = None
class JRMCConfigureThreadWorker(eg.ThreadWorker): comInstance = None def Setup(self): self.comInstance = EnsureDispatch("MediaJukebox Application") def Finish(self): if self.comInstance: del self.comInstance def GetZoneInfo(self): zonesInstance = self.comInstance.GetZones() nZones = zonesInstance.GetNumberZones() names = [] for i in range(nZones): names.append(zonesInstance.GetZoneName(i)) return nZones, names def GetPlaylistInfo(self): playlistsInstance = self.comInstance.GetPlaylists() nPlaylists = playlistsInstance.GetNumberPlaylists() names = [] paths = [] ids = [] for i in range(nPlaylists): pl = playlistsInstance.GetPlaylist(i) paths.append(pl.Path) names.append(pl.Name) ids.append(pl.GetID()) #print "ID =",pl.GetID(),"Name =",pl.Name,"Path =",pl.Path groups = [] playlistsByGroup = {} playlistsByGroup["All"] = [] for i in range(nPlaylists): if len(paths[i]) > 0: fullpath = paths[i] + "\\" + names[i] else: fullpath = names[i] if fullpath in paths: groups.append(fullpath) playlistsByGroup[fullpath] = [] for i in range(nPlaylists): if len(paths[i]) > 0: fullpath = paths[i] + "\\" + names[i] else: fullpath = names[i] if fullpath not in paths: if len(paths[i]) > 0: playlistsByGroup[paths[i]].append(names[i]) playlistsByGroup["All"].append(names[i]) return playlistsByGroup, names, ids
def makemdb(testfolder): # following setup code borrowed from pywin32 odbc test suite # kindly contributed by Frank Millman. import tempfile import os _accessdatasource = tempfile.mktemp(suffix='.mdb', prefix='ado_test_', dir=testfolder) if os.path.isfile(_accessdatasource): os.unlink(_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 from System import Activator, Type # 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 update_html(self): xl = EnsureDispatch('Excel.Application') xl.DisplayAlerts = False wb = xl.Workbooks.Open(flowloger) try: wb.SaveAs(self.HTML_DOC_PATH, constants.xlHtml) except: xl.Workbooks.Close() xl.Quit() shutil.rmtree(self.HTML_DOC_PATH.split("\\GL_log.htm")[0]) os.makedirs(self.HTML_DOC_PATH.split("\\GL_log.htm")[0]) update_html() pass xl.Workbooks.Close() xl.Quit()
def __init__(self): EnsureModule('{EA433010-2BAC-43C4-857C-7AEAC4A8CCE0}', 0, 1, 0) EnsureModule('{F66684D7-AAFE-4A62-9156-FF7A7853F764}', 0, 1, 0) self.TheConnection = EnsureDispatch("ZOSAPI.ZOSAPI_Connection") print(self.TheConnection) self.TheApplication = self.TheConnection.CreateNewApplication() print(self.TheApplication) self.TheSystem = self.TheApplication.PrimarySystem print(self.TheSystem)
def run(self): global LastAlt global Mque global sendInfo pythoncom.CoInitialize() iTunes = EnsureDispatch("iTunes.Application") self.RMouseDown = False self.PosStart = None self.PosEnd = None print "Ready" while 1: command = Mque.get() if sendInfo == False and command[1] == 513: self.RMouseDown = True if sendInfo == False and self.RMouseDown == True and self.PosStart == None and command[1] == 512: self.PosStart = command[2] if sendInfo == False and self.RMouseDown == True and command[1] == 512: self.PosEnd = command[2] try: if sendInfo == False and self.RMouseDown == True and command[1] == 514: self.RMouseDown = False if self.PosStart != None and self.PosEnd != None: if self.PosStart[0] < self.PosEnd[0]: iTunes.NextTrack() elif self.PosStart[0] > self.PosEnd[0]: iTunes.BackTrack() else: pass else: iTunes.PlayPause() self.PosStart = None self.PosEnd = None if sendInfo == False and command[3] != 0: if command[3] > 0: iTunes.SoundVolume += 2 elif command[3] < 0: iTunes.SoundVolume -= 2 else: pass except pythoncom.com_error, e: print e Mque.task_done()
def setUp(self): 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 = os.path.join(tempfile.gettempdir(), "test_odbc.mdb") if os.path.isfile(self.db_filename): os.unlink(self.db_filename) # 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 RuntimeError, "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,) self.conn = odbc.odbc(conn_str) # And we expect a 'users' table for these tests. self.cur = self.conn.cursor() try: self.cur.execute("""drop table pywin32test_users""") except (odbc.error, dbi.progError): pass self.assertEqual( self.cur.execute("""create table pywin32test_users ( userid varchar(5), username varchar(25), bitfield bit, intfield integer, floatfield float, datefield date, )"""), -1)
def check_port_pids(): pids = [] WMI = GetObject('winmgmts:') WMI = EnsureDispatch(WMI._oleobj_) nestat_regex = re.compile("\s+(?P<type>TCP|UDP)\s+(0.0.0.0|127.0.0.1):(?P<port>[0-9]+)\s+[0-9.:]+\s+(?P<listen>LISTENING)\s+(?P<pid>[0-9]+)") proc = subprocess.Popen(['netstat', '-ano'],creationflags=0x08000000, stdout=subprocess.PIPE) output = proc.communicate()[0] proc.stdout.close() for port in output.split("\r\n"): if nestat_regex.search(port): pids.append(nestat_regex.search(port).groupdict()) for pid in pids: processes = WMI.ExecQuery('select * from Win32_Process where ProcessId = %s' % pid["pid"]) for process in processes: if process.Properties_("Name").Value not in ["svchost.exe","lsass.exe","wininit.exe", "System", "services.exe"]: if process.ExecMethod_('GetOwner').Properties_("User").Value == None: print "[VULN] Elevated process %s with pid %s on port %s %s" % (process.Properties_("Name").Value, pid["pid"], pid["port"], pid["type"]) if pid["type"] == "TCP": s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setblocking(1) s.settimeout(0.5) try: s.connect(("127.0.0.1", int(pid["port"]))) s.send("GET / HTTP/1.1\r\n\r\n") print "> [INFO] Port %s (%s) answer with banner \"%s\"" % (pid["port"], process.Properties_("Name").Value, s.recv(50).replace("\r\n"," ")) except Exception as e: print "> [INFO] Port %s (%s) won't answer to dummy packet" % (pid["port"], process.Properties_("Name").Value)
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 __init__(self, default_audio_source=0): Sapi5SharedEngine.__init__(self) # Also ensure the dispatch to InProcReco EnsureDispatch("SAPI.SpInProcRecognizer") self._audio_source_qualifier = default_audio_source
def Connect(): global NOTIFY, GATE #the below is required in order to establish the com-object links #that way you don't need to run makepy first EnsureModule('{98B8AE14-466F-11D6-A27B-00B0D0F3CCA6}', 0, 1, 0) GATE = EnsureDispatch('XTAPI.TTGate') NOTIFY = DispatchWithEvents('XTAPI.TTInstrNotify', InstrNotify)
def __init__(self, retain_dir=None): EngineBase.__init__(self) EnsureDispatch(self.recognizer_dispatch_name) EnsureDispatch("SAPI.SpVoice") self._recognizer = None self._speaker = None self._compiler = None self._recognition_observer_manager = Sapi5RecObsManager(self) self._timer_manager = ThreadedTimerManager(0.02, self) if isinstance(retain_dir, string_types) or retain_dir is None: self._retain_dir = retain_dir else: self._retain_dir = None self._log.error("Invalid retain_dir: %r" % retain_dir)
def main(): global ns ns = osbrain.run_nameserver() bob = osbrain.run_agent('Bob') Connect() bob.connect(Notify.addr, handler=log_message) ## pInstr = EnsureDispatch('XTAPI.TTInstrObj') ## pInstr.Exchange = 'TOCOM-B' ## pInstr.Product = 'RSS3' ## pInstr.Contract = '24Jun19' ## pInstr.ProdType = 'FUTURE' ## Notify.Subscribe(pInstr) mar19 = EnsureDispatch('XTAPI.TTInstrObj') apr19 = EnsureDispatch('XTAPI.TTInstrObj') may19 = EnsureDispatch('XTAPI.TTInstrObj') jun19 = EnsureDispatch('XTAPI.TTInstrObj') jul19 = EnsureDispatch('XTAPI.TTInstrObj') aug19 = EnsureDispatch('XTAPI.TTInstrObj') sep19 = EnsureDispatch('XTAPI.TTInstrObj') oct19 = EnsureDispatch('XTAPI.TTInstrObj') nov19 = EnsureDispatch('XTAPI.TTInstrObj') dec19 = EnsureDispatch('XTAPI.TTInstrObj') sub_tf(mar19, 'Mar19') sub_tf(apr19, 'Apr19') sub_tf(may19, 'May19') sub_tf(jun19, 'Jun19') sub_tf(jul19, 'Jul19') sub_tf(aug19, 'Aug19') sub_tf(sep19, 'Sep19') sub_tf(oct19, 'Oct19') sub_tf(nov19, 'Nov19') sub_tf(dec19, 'Dec19') Notify.UpdateFilter = 'Bid, Ask, Last, LastQty' for i in range(10): print('pumping...') pythoncom.PumpWaitingMessages() sleep(1.0) def qqm(): Gate.XTAPITerminate() ns.shutdown()
def __init__(self, servername='myserver.domain', **kwargs): """ @param servername: A string containing the historian server's URL or IP address @param username: A string containing the username. If one exists. @param password: A string containing the password. If one exists. """ # Only create a class instanace and don't try connecting if no servername is supplied if servername: try: #DispatchEx #=CreateObject("iHistorian_SDK.Server") or =New iHistorian_SDK.Server # -- Using comtypes libriary # from comtypes.client import CreateObject # Aquator = CreateObject("Aquator.Application") # Achieves early dispatch # http://timgolden.me.uk/python/win32_how_do_i/generate-a-static-com-proxy.html # http://stackoverflow.com/questions/170070/what-are-the-differences-between-using-the-new-keyword-and-calling-createobject self.ihApp = EnsureDispatch( 'iHistorian_SDK.Server') # Attach the server print "Connecting to: %s" % servername if not self._connect(servername, kwargs.get('Username'), kwargs.get('Password')): print "Could not connect to the server at: %s" % servername print self.ihApp.LastError raw_input("Press 'Enter' to exit") self.close() exit() except TypeError: print "\nCannot dispatch iHistorian_SDK COM object." print "Check that ihSDK.dll and ihAPI40.dll are present and GE iHistorian is installed." print "Use regsvr32 to register the DLLs" print "cd 'C:\Python27\Lib\site-packages\win32com\client' select iHistorian and py code is automatically generated" raw_input("Press 'Enter' to exit") exit() print "SCADA server Connection successful! There are currently %d users connected to the server" % ( self.num_of_connected_users()) else: # Dispatch and instanciate the server SDK without connecting to a server - useful for building an index of ihistorian constants self.ihApp = EnsureDispatch( 'iHistorian_SDK.Server') # Attach the server
def get_explorer_address_by_hwnd(hwnd=None): for w in EnsureDispatch("Shell.Application").Windows(): if hwnd is None or hwnd == w.HWnd: if w.LocationURL.startswith("file:///"): return w.LocationURL[8:].replace("/", "\\") # UNC 路径,如 file://Mac/.../... if w.LocationURL.startswith("file://"): return w.LocationURL[5:].replace("/", "\\") logging.warning("unknown address: " + w.LocationURL) return None
def send_email(to, subject, body): ''' docstring ''' try: outlook = Dispatch("Outlook.Application") mailitem = outlook.CreateItem(0) tostr = '' if type(to) is list: tostr = ';'.join(to).strip(';').strip().strip(';') else: tostr = to.strip() mailitem.To = tostr mailitem.Subject = subject mailitem.Body = body mailitem.Send() except Exception as e: print(e) traceback.print_exc()
def sendmail(): today_date = date.today() todays_date = str( today_date.day) + 'th ' + today_date.strftime('%B') + ' ' + str( today_date.year) + ', ' + today_date.strftime('%A') xl = EnsureDispatch('Excel.Application') wb = xl.Workbooks.Open(r'P:\imran-TEMS\BTFSL\BT Report.xlsx') ws = wb.Worksheets('Test Report') ws.Cells(8, 'R').Value = str( today_date.day) + 'th ' + today_date.strftime('%B') + ' ' + str( today_date.year) + ', ' + today_date.strftime('%A') wb.PublishObjects.Add(SourceType=constants.xlSourceRange, Filename=r'P:\imran-TEMS\BTFSL\BT Report.html', Sheet='Test Report', Source='$A$1:$AC$70', HtmlType=constants.xlHtmlStatic, DivID='xxx1') wb.PublishObjects(1).Publish(True) wb.Close(True) xl.Application.Quit() body_content = open(r'P:\imran-TEMS\BTFSL\BT Report.html').read() path_of_img = { 1: 'P:\imran-TEMS\dummy\Tems.png', 0: 'P:\imran-TEMS\dummy\westpaclogo.jpg' } count = 0 num = 0 while count < 2 and num < 50: pat = "BT%20Report_files/xxx1_image00" + str(num) + ".png" match = re.search(pat, body_content) body_content = re.sub(pat, path_of_img[count], body_content) num += 1 if match is None: continue count += 1 outlook = Dispatch('outlook.application') user_id = getpass.getuser() mail = outlook.CreateItem(0) #mail.To = "TEMS Service Desk <*****@*****.**>" #mail.BCC = "L096535;L099582;L098864;L092160;L064403;L100513;Sveum, Mikkal <*****@*****.**>; Baird, Russell <*****@*****.**>; Brinkman, Derek <*****@*****.**>;L062449;L066667;" mail.To = "L111185" mail.BCC = "L092160" mail.Subject = "BTSFL Test Environment Status(Automated) " + str( today_date.day) + 'th ' + today_date.strftime('%B') + " " + str( today_date.year) mail.HTMLbody = body_content mail.send os.remove("P:\imran-TEMS\BTFSL\BT Report.html")
def query (query_string, **command_properties): """Auxiliary function to serve as a quick-and-dirty wrapper round an ADO query """ command = EnsureDispatch ("ADODB.Command") command.ActiveConnection = connection () # # Add any client-specified ADO command properties. # NB underscores in the keyword are replaced by spaces. # # Examples: # "Cache_results" = False => Don't cache large result sets # "Page_size" = 500 => Return batches of this size # "Time Limit" = 30 => How many seconds should the search continue # for k, v in command_properties.items (): command.Properties (k.replace ("_", " ")).Value = v command.CommandText = query_string recordset, result = command.Execute () while not recordset.EOF: yield ADO_record (recordset) recordset.MoveNext ()
def TestGenerated(): # Create an instance of the server. from win32com.client.gencache import EnsureDispatch o = EnsureDispatch("PyCOMTest.PyCOMTest") TestCommon(o, True) counter = EnsureDispatch("PyCOMTest.SimpleCounter") TestCounter(counter, True) # XXX - this is failing in dynamic tests, but should work fine. i1, i2 = o.GetMultipleInterfaces() if not isinstance(i1, DispatchBaseClass) or not isinstance(i2, DispatchBaseClass): # Yay - is now an instance returned! raise error("GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2)) del i1 del i2 # Generated knows to only pass a 32bit int, so should fail. check_get_set_raises(OverflowError, o.GetSetInt, 0x80000000) check_get_set_raises(OverflowError, o.GetSetLong, 0x80000000) # Generated knows this should be an int, so raises ValueError check_get_set_raises(ValueError, o.GetSetInt, "foo") check_get_set_raises(ValueError, o.GetSetLong, "foo") # Pass some non-sequence objects to our array decoder, and watch it fail. try: o.SetVariantSafeArray("foo") raise error("Expected a type error") except TypeError: pass try: o.SetVariantSafeArray(666) raise error("Expected a type error") except TypeError: pass o.GetSimpleSafeArray(None) TestApplyResult(o.GetSimpleSafeArray, (None,), tuple(range(10))) resultCheck = tuple(range(5)), tuple(range(10)), tuple(range(20)) TestApplyResult(o.GetSafeArrays, (None, None, None), resultCheck) l=[] TestApplyResult(o.SetIntSafeArray, (l,), len(l)) l=[1,2,3,4] TestApplyResult(o.SetIntSafeArray, (l,), len(l)) ll=[1,2,3,0x100000000] TestApplyResult(o.SetLongLongSafeArray, (ll,), len(ll)) TestApplyResult(o.SetULongLongSafeArray, (ll,), len(ll)) # Tell the server to do what it does! TestApplyResult(o.Test2, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test3, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test4, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test5, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test6, (constants.WideAttr1,), constants.WideAttr1) TestApplyResult(o.Test6, (constants.WideAttr2,), constants.WideAttr2) TestApplyResult(o.Test6, (constants.WideAttr3,), constants.WideAttr3) TestApplyResult(o.Test6, (constants.WideAttr4,), constants.WideAttr4) TestApplyResult(o.Test6, (constants.WideAttr5,), constants.WideAttr5) o.SetParamProp(0, 1) if o.ParamProp(0) != 1: raise RuntimeError(o.paramProp(0)) # Make sure CastTo works - even though it is only casting it to itself! o2 = CastTo(o, "IPyCOMTest") if o != o2: raise error("CastTo should have returned the same object") # Do the connection point thing... # Create a connection object. progress("Testing connection points") o2 = win32com.client.DispatchWithEvents(o, RandomEventHandler) TestEvents(o2, o2) # and a plain "WithEvents". handler = win32com.client.WithEvents(o, RandomEventHandler) TestEvents(o, handler) progress("Finished generated .py test.")
class ContactsApp: def __init__(self): log.debug("ContactsApp::__init__") self.currentContact = None self.about_dialog = None self.hostHasGtkBuilder = False version=gtk.gtk_version if int(version[0]) >= 2 and int(version[1]) >= 12: self.hostHasGtkBuilder = True log.debug("Does host support GtkBuilder?: %s" % self.hostHasGtkBuilder) self.gladefile=GLADEFILE self.wTree=gtk.glade.XML(self.gladefile,"mainWindow") self.window = self.wTree.get_widget("mainWindow") self.window.maximize() self.notebook=self.wTree.get_widget("mainNotebook") self.statusbar = self.wTree.get_widget("statusbar") self.contactModelView=self.wTree.get_widget("contactsTreeView") # Color changing of background needs to be done on the uppermost widget - in our case the viewport self.contactDetailViewport=self.wTree.get_widget("summaryViewport") color = gtk.gdk.color_parse("white") self.contactDetailViewport.modify_bg(gtk.STATE_NORMAL,color) self.contactDetailVbox=self.wTree.get_widget("summaryVbox") self.contactDetailName=self.wTree.get_widget("summaryName") self.contactDetailPhoto=self.wTree.get_widget("summaryPhoto") self.contactDetailTable=self.wTree.get_widget("summaryTable") # Create the listStore model to use with the contactListView self.contactModel=gtk.ListStore(str,str) # (ContactId,FullName) self.populateWithAddressBookContacts() # Create a filter, from the model and set the TreeView to use it self.contactFilter=self.contactModel.filter_new() self.contactFilter.set_visible_column(1) #view=gtk.TreeView(filter) self.contactModelView.set_model(self.contactModel) self.contactModelView.set_enable_search(True) self.contactModelView.set_search_column(1) #self.contactModelView.set_filter(self.contactFilter) treeselection=self.contactModelView.get_selection() treeselection.connect('changed',self.on_contactsTreeView_selection_changed) col=contactDetails.createTreeViewColumn("Name",1) self.contactModelView.append_column(col) self.toolbar = self.wTree.get_widget("toolbar") # autoconnect => signal handlers are named class methods. eg. "on_mainWindow_destroy" self.wTree.signal_autoconnect(self) self.window.set_icon_name(gtk.STOCK_ORIENTATION_PORTRAIT) # set the window icon to the GTK "portrait" icon self.statusbar_cid = self.statusbar.get_context_id(APPNAME) # setup and initialize our statusbar # We're going to fire up the last contact Id on startup self.contactModelView.set_cursor(121,col) # Now show everything! self.window.show() def populateWithAddressBookContacts(self): if WINDOWS: self.populateWithWABContacts() else: self.populateWithEvolutionContacts() def populateWithWABContacts(self): ''' Appends all WAB contacts to the contactList using the WAB (id,name) as the contact (id,name) ''' log.debug("ContactsApp::populateWithWABContacts") self.addresses=EnsureDispatch("WABAccess.Session",bForDemand=0) def populateWithEvolutionContacts(self): ''' Appends all Evolution contacts to the contactList using the Evolution (id,name) as the contact (id,name) ''' # Zeth on pyevolution: http://commandline.org.uk/python/2007/dec/1/three-useful-python-bindings/ log.debug("ContactsApp::populateWithEvolutionContacts") self.addresses=evolution.ebook.open_addressbook('default') # This will show you all the available properties allContacts=self.addresses.get_all_contacts() contacts=[(cont.get_property('full-name').lower(),cont) for cont in allContacts] # Note the lowering... contacts.sort() # alphabetic sort in-place on contact names for (name,cont) in contacts: contId=cont.get_property('id') name=cont.get_property('full-name') self.contactModel.append((contId,name)) def displayVCardContact(self,contId,contFullName): ''' Displays corresponding vCard contact field details in the table in 'summaryViewport' ''' log.debug("displayVcardContact(%s,'%s')" % (contId,contFullName)) if self.currentContact and contId==self.currentContact[0]: log.debug("Attempting to show the same contact - moving on") return self.currentContact=(contId,contFullName) cont=self.getContactById(contId) vcf=cont.get_vcard_string() vcont=vobject.readOne(vcf) # Use Chandler vobject library to process Evolution vCard 3.0 format view,table=contactDetails.initContactDetailView(self) contactDetails.setupContactNameLabel(self,contFullName) try: if USE_VCARD_THUMBNAIL: image=contactDetails.vcardThumbnailToGtkImage(vcont.photo.value) else: image=cont.get_photo(80) # gtk.gdk.Pixbuf - you can pull out this photo into a GTKImage except: image=None contactDetails.setupContactThumbnail(self,image) contactDetails.populateVobjectContactDetailFields(table,vcont) view.show_all() # To now show the table def displayEvolutionContact(self,contId,contFullName): ''' Displays corresponding Evolution contact field details in the table in 'summaryViewport' ''' log.debug("displayEvolutionContact(%s,'%s')" % (contId,contFullName)) if self.currentContact and contId==self.currentContact[0]: log.debug("Attempting to show the same contact - moving on") return self.currentContact=(contId,contFullName) cont=self.getContactById(contId) # Now follows the display utility logic view,table=contactDetails.initContactDetailView(self) contactDetails.setupContactNameLabel(self,contFullName) image=cont.get_photo(80) # gtk.gdk.Pixbuf - you can pull out this photo into a GTKImage contactDetails.setupContactThumbnail(self,image) # Populate our table with attr-vals from contact. contactDetails.populateEvolutionContactDetailFields(table,cont) view.show_all() # To now show the table def editContact(self,contId,contFullName): log.debug("editContact(%s,'%s')" % (contId,contFullName)) def selectAndDisplayContact(self,contId,col=None): iter=self.contactModel.get_iter(contId) self.contactModelView.set_cursor(contId,col) contId,contFullName=self.contactModel.get(iter,0,1) if USE_VOBJECT_PARSER: self.displayVCardContact(contId,contFullName) else: self.displayEvolutionContact(contId,contFullName) def getContactById(self,contId): # NOTE: self.addresses[0].__doc__ gives you the supported properties return self.addresses.get_contact(contId) #--------------------------- Menubar signal handlers -------------------------- def on_about_menu_item_activate(self, menuitem, data=None): ''' Called when the user clicks the 'About' menu. We create a GtkAboutDialog. This dialog will NOT be modal but will be on top of the main application window.''' if self.about_dialog: self.about_dialog.present() return about_dialog=AboutDialog(self) self.about_dialog = about_dialog about_dialog.show() #--------------------------- Toolbar buttons signal handlers -------------------------- def on_button_add_clicked(self,widget,data=None): ''' User clicked to add a contact. This should launch a new contact dialog ''' # TODO: We would want to launch a dialog OR edit page of notebook here... log.debug("TBD") #contactId=self.id #contactFullName="Mickey Mouse %d" % self.id #self.contactModel.append((contactId,contactFullName)) def on_button_edit_clicked(self,widget,data=None): ''' User clicked to edit a contact. This should launch an edit contact dialog ''' log.debug("TBD") def on_button_delete_clicked(self,widget,data=None): ''' Use a modal verification dialog ''' contId,contFullName=self.currentContact messageDlg=ConfirmationDialog(self,"Are you sure you want to delete '%s'?" % contFullName) resp=messageDlg.run() if resp==gtk.RESPONSE_ACCEPT: log.debug("Delete '%s' now!" % contFullName) messageDlg.destroy() # destroy dialog either way def on_button_export_clicked(self,widget,data=None): ''' User clicked to export a contact. This should launch a new file dialog ''' if not self.currentContact: log.warning("No current contact set - returning") return contId,contFullName=self.currentContact cont=self.getContactById(contId) vcard=cont.get_vcard_string() log.debug("Current contact='%s'" % contFullName) export_dialog=ExportDialog(self,contFullName,vcard) export_dialog.show() def on_button_send_clicked(self,widget,data=None): ''' User clicked to export a contact. This should launch a Bluetooth device selection dialog ''' discoverer_dialog=BluetoothDevicesDialog(self) discoverer_dialog.show() #--------------------------- Contact list treeview signal handlers -------------------------- def on_contactsTreeView_selection_changed(self,selection): ''' IMPORTANT: This signal is associated with a gtk.TreeSelection not in Glade-3! ''' model, paths = selection.get_selected_rows() if paths and paths[0]: contId=paths[0][0] log.debug("on_contactsTreeView_selection_changed : %s" % contId) self.selectAndDisplayContact(contId) def on_contactsTreeView_row_activated(self,treeview,path,col,data=None): ''' Invoked on _selecting_ a different entry in treeview. Cue for launching an edit dialog/notebook tab ''' model,iter=treeview.get_selection().get_selected() contId,contFullName=model.get(iter,0,1) # Getting col 0 (uid) and col 1 (full name) self.editContact(contId,contFullName) def on_contactsTreeView_start_interactive_search(self,treeview,data=None): log.debug("on_contactsTreeView_start_interactive_search: %s" % data) #--------------------------- Main window signal handlers -------------------------- def on_mainWindow_destroy(self, widget, data=None): ''' When our window is destroyed, we want to break out of the GTK main loop. We do this by calling gtk_main_quit(). We could have also just specified gtk_main_quit as the handler in Glade!''' log.debug("ContactsApp::on_mainWindow_destroy") gtk.main_quit()
def populateWithWABContacts(self): ''' Appends all WAB contacts to the contactList using the WAB (id,name) as the contact (id,name) ''' log.debug("ContactsApp::populateWithWABContacts") self.addresses=EnsureDispatch("WABAccess.Session",bForDemand=0)
def run(self): global Kque global LastAlt global sendInfo pythoncom.CoInitialize() iTunes = EnsureDispatch("iTunes.Application") self.To_Delete = [] print "Ready" while 1: command = Kque.get() if command[2] > 0: LastAlt = command[0] sendInfo = False if command[0]-LastAlt > 200: sendInfo = True try: if command[1] == "P" and command[2] > 0: iTunes.PlayPause() elif command[1] == "Right" and command[2] > 0: iTunes.NextTrack() elif command[1] == "Left" and command[2] > 0: iTunes.BackTrack() elif command[1] == "Up" and command[2] > 0: iTunes.SoundVolume += 5 elif command[1] == "Down" and command[2] > 0: iTunes.SoundVolume -= 5 elif command[1] == "Oem_Minus" and command[2] > 0: iTunes.SoundVolume = 0 elif command[1] == "Oem_Plus" and command[2] > 0: iTunes.SoundVolume = 100 elif command[1] == "S" and command[2] > 0: MainPlaylist = iTunes.CurrentPlaylist if MainPlaylist.Shuffle == 1: MainPlaylist.Shuffle = 0 elif MainPlaylist.Shuffle == 0: MainPlaylist.Shuffle = 1 else: pass elif command[1] == "Finish" and command[2] > 0: while len(self.To_Delete) > 0: temp_l = iTunes.LibrarySource.Playlists.ItemByName(self.To_Delete.pop()) temp_l.Delete() elif command[1] == "R" and command[2] > 0: MainPlaylist = iTunes.CurrentPlaylist Kque.task_done() repeat = Kque.get() if repeat[1] == "1" and repeat[2] > 0: MainPlaylist.SongRepeat = 1 elif repeat[1] == "A" and repeat[2] > 0: MainPlaylist.SongRepeat = 2 elif repeat[1] == "N" and repeat[2] > 0: MainPlaylist.SongRepeat = 0 else: pass elif command[1] == "H" and command[2] > 0: print "Enter Playlist Name:" char_list = [] Kque.task_done() pressed_key = Kque.get() while pressed_key[2] > 0: char_list.append(pressed_key[1]) Kque.task_done() pressed_key = Kque.get() ret_string = "" Caps = False Shift = False for x in char_list: val = x.lower() if val not in ["space", "lshift", "rshift", "capital"]: if Shift == True: val = val.upper() Shift = False elif Caps == True: val = val.upper() else: pass ret_string += val elif val == "space": ret_string += " " elif val in ["lshift", "rshift"]: Shift = True elif val == "capital": if Caps == True: Caps = False elif Caps == False: Caps = True else: pass try: gotoPlaylist = iTunes.LibrarySource.Playlists.ItemByName(ret_string) gotoPlaylist.PlayFirstTrack() print "Playing Playlist: %s"% ret_string except: print "Playlist %s Not Found"% ret_string elif command[1] == "O" and command[2] > 0: Kque.task_done() repeat = Kque.get() Op = None if repeat[1] == "1" and repeat[2] > 0: Op = "1" elif repeat[1] == "2" and repeat[2] > 0: Op = "2" elif repeat[1] == "3" and repeat[2] > 0: Op = "3" else: pass print "Enter Char String" char_list = [] Kque.task_done() pressed_key = Kque.get() while pressed_key[2] > 0: char_list.append(pressed_key[1]) Kque.task_done() pressed_key = Kque.get() ret_string = "" Caps = False Shift = False for x in char_list: val = x.lower() if val not in ["space", "lshift", "rshift", "capital"]: if Shift == True: val = val.upper() Shift = False elif Caps == True: val = val.upper() else: pass ret_string += val elif val == "space": ret_string += " " elif val in ["lshift", "rshift"]: Shift = True elif val == "capital": if Caps == True: Caps = False elif Caps == False: Caps = True else: pass Liby = iTunes.LibraryPlaylist Tracks = Liby.Tracks if Op == "1": print "Scaning for artist: %s"% ret_string track_list = [] for track in Tracks: if track.Artist.lower() == ret_string.lower(): track_list.append(track) elif Op == "2": print "Scaning for album: %s"% ret_string track_list = [] for track in Tracks: if track.Album.lower() == ret_string.lower(): track_list.append(track) elif Op == "3": print "Scaning for Song Name: %s"% ret_string track_list = [] for track in Tracks: if track.Name.lower() == ret_string.lower(): track_list.append(track) else: pass if len(track_list) > 0: temp_list = iTunes.CreatePlaylist(ret_string) self.To_Delete.append(ret_string) temp_list = win32com.client.CastTo(temp_list, 'IITUserPlaylist') for track in track_list: temp_list.AddTrack(track) temp_list.PlayFirstTrack() print "Done" else: print "No Tracks Found" else: pass except pythoncom.com_error, e: print e Kque.task_done()
def TestGenerated(): # Create an instance of the server. from win32com.client.gencache import EnsureDispatch o = EnsureDispatch("PyCOMTest.PyCOMTest") counter = o.GetSimpleCounter() TestCounter(counter, 1) counter = EnsureDispatch("PyCOMTest.SimpleCounter") TestCounter(counter, 1) i1, i2 = o.GetMultipleInterfaces() if type(i1) != types.InstanceType or type(i2) != types.InstanceType: # Yay - is now an instance returned! raise error, "GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2) del i1 del i2 progress("Checking default args") rc = o.TestOptionals() if rc[:-1] != ("def", 0, 1) or abs(rc[-1]-3.14)>.01: print rc raise error, "Did not get the optional values correctly" rc = o.TestOptionals("Hi", 2, 3, 1.1) if rc[:-1] != ("Hi", 2, 3) or abs(rc[-1]-1.1)>.01: print rc raise error, "Did not get the specified optional values correctly" rc = o.TestOptionals2(0) if rc != (0, "", 1): print rc raise error, "Did not get the optional2 values correctly" rc = o.TestOptionals2(1.1, "Hi", 2) if rc[1:] != ("Hi", 2) or abs(rc[0]-1.1)>.01: print rc raise error, "Did not get the specified optional2 values correctly" progress("Checking var args") o.SetVarArgs("Hi", "There", "From", "Python", 1) if o.GetLastVarArgs() != ("Hi", "There", "From", "Python", 1): raise error, "VarArgs failed -" + str(o.GetLastVarArgs()) progress("Checking getting/passing IUnknown") if o.GetSetUnknown(o) != o: raise error, "GetSetUnknown failed" progress("Checking getting/passing IDispatch") if type(o.GetSetDispatch(o)) !=types.InstanceType: raise error, "GetSetDispatch failed" progress("Checking getting/passing IDispatch of known type") if o.GetSetInterface(o).__class__ != o.__class__: raise error, "GetSetDispatch failed" if o.GetSetVariant(4) != 4: raise error, "GetSetVariant (int) failed" if o.GetSetVariant("foo") != "foo": raise error, "GetSetVariant (str) failed" if o.GetSetVariant(o) != o: raise error, "GetSetVariant (dispatch) failed" for l in sys.maxint, sys.maxint+1, 1 << 65L: if o.GetSetVariant(l) != l: raise error, "GetSetVariant (long) failed" if o.TestByRefVariant(2) != 4: raise error, "TestByRefVariant failed" if o.TestByRefString("Foo") != "FooFoo": raise error, "TestByRefString failed" # Pass some non-sequence objects to our array decoder, and watch it fail. try: o.SetVariantSafeArray("foo") raise error, "Expected a type error" except TypeError: pass try: o.SetVariantSafeArray(666) raise error, "Expected a type error" except TypeError: pass o.GetSimpleSafeArray(None) TestApplyResult(o.GetSimpleSafeArray, (None,), tuple(range(10))) resultCheck = tuple(range(5)), tuple(range(10)), tuple(range(20)) TestApplyResult(o.GetSafeArrays, (None, None, None), resultCheck) l=[1,2,3,4] TestApplyResult(o.SetVariantSafeArray, (l,), len(l)) TestApplyResult(o.SetIntSafeArray, (l,), len(l)) l=[] TestApplyResult(o.SetVariantSafeArray, (l,), len(l)) TestApplyResult(o.SetIntSafeArray, (l,), len(l)) # Tell the server to do what it does! TestApplyResult(o.Test, ("Unused", 99), 1) # A bool function TestApplyResult(o.Test, ("Unused", -1), 1) # A bool function TestApplyResult(o.Test, ("Unused", 1==1), 1) # A bool function TestApplyResult(o.Test, ("Unused", 0), 0) TestApplyResult(o.Test, ("Unused", 1==0), 0) TestApplyResult(o.Test2, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test3, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test4, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test5, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test6, (constants.WideAttr1,), constants.WideAttr1) TestApplyResult(o.Test6, (constants.WideAttr2,), constants.WideAttr2) TestApplyResult(o.Test6, (constants.WideAttr3,), constants.WideAttr3) TestApplyResult(o.Test6, (constants.WideAttr4,), constants.WideAttr4) TestApplyResult(o.Test6, (constants.WideAttr5,), constants.WideAttr5) TestConstant("ULongTest1", 0xFFFFFFFFL) TestConstant("ULongTest2", 0x7FFFFFFFL) TestConstant("LongTest1", -0x7FFFFFFFL) TestConstant("LongTest2", 0x7FFFFFFFL) TestConstant("UCharTest", 255) TestConstant("CharTest", -1) # 'Hello Loraine', but the 'r' is the "Registered" sign (\xae) TestConstant("StringTest", u"Hello Lo\xaeaine") now = pythoncom.MakeTime(time.gmtime(time.time())) later = pythoncom.MakeTime(time.gmtime(time.time()+1)) TestApplyResult(o.EarliestDate, (now, later), now) try: import datetime now = datetime.datetime.now() expect = pythoncom.MakeTime(now) TestApplyResult(o.EarliestDate, (now, now), expect) except ImportError: pass # py 2.2 - no datetime assert o.DoubleString("foo") == "foofoo" assert o.DoubleInOutString("foo") == "foofoo" o.LongProp = 3 if o.LongProp != 3 or o.IntProp != 3: raise error, "Property value wrong - got %d/%d" % (o.LongProp,o.IntProp) o.LongProp = o.IntProp = -3 if o.LongProp != -3 or o.IntProp != -3: raise error, "Property value wrong - got %d/%d" % (o.LongProp,o.IntProp) check = 3 *10 **9 o.ULongProp = check if o.ULongProp != check: raise error, "Property value wrong - got %d (expected %d)" % (o.ULongProp, check) # currency. pythoncom.__future_currency__ = 1 if o.CurrencyProp != 0: raise error, "Expecting 0, got %r" % (o.CurrencyProp,) try: import decimal except ImportError: import win32com.decimal_23 as decimal for val in ("1234.5678", "1234.56", "1234"): o.CurrencyProp = decimal.Decimal(val) if o.CurrencyProp != decimal.Decimal(val): raise error, "%s got %r" % (val, o.CurrencyProp) v1 = decimal.Decimal("1234.5678") TestApplyResult(o.DoubleCurrency, (v1,), v1*2) TestApplyResult(o.DoubleCurrencyByVal, (v1,), v1*2) v2 = decimal.Decimal("9012.3456") TestApplyResult(o.AddCurrencies, (v1, v2), v1+v2) o.SetParamProp(0, 1) if o.ParamProp(0) != 1: raise RuntimeError, o.paramProp(0) # Do the connection point thing... # Create a connection object. progress("Testing connection points") sessions = [] o = win32com.client.DispatchWithEvents( o, RandomEventHandler) o._Init() try: for i in range(3): session = o.Start() sessions.append(session) time.sleep(.5) finally: # Stop the servers for session in sessions: o.Stop(session) o._DumpFireds() progress("Finished generated .py test.")
def test_win32com(self): # EnsureDispatch is case-sensitive from win32com.client.gencache import EnsureDispatch d = EnsureDispatch("TestDispServerLib.TestDispServer") self.assertEqual(d.eval("3.14"), 3.14) self.assertEqual(d.eval("1 + 2"), 3) self.assertEqual(d.eval("[1 + 2, 'foo', None]"), (3, 'foo', None)) self.assertEqual(d.eval2("3.14"), 3.14) self.assertEqual(d.eval2("1 + 2"), 3) self.assertEqual(d.eval2("[1 + 2, 'foo', None]"), (3, 'foo', None)) d.eval("__import__('comtypes.client').client.CreateObject('MSScriptControl.ScriptControl')") server_id = d.eval("id(self)") self.assertEqual(d.id, server_id) self.assertEqual(d.name, "spam, spam, spam") d.SetName("foo bar") self.assertEqual(d.name, "foo bar") d.name = "blah" self.assertEqual(d.name, "blah")
def TestGenerated(): # Create an instance of the server. from win32com.client.gencache import EnsureDispatch o = EnsureDispatch("PyCOMTest.PyCOMTest") counter = o.GetSimpleCounter() TestCounter(counter, 1) counter = EnsureDispatch("PyCOMTest.SimpleCounter") TestCounter(counter, 1) i1, i2 = o.GetMultipleInterfaces() if not isinstance(i1, DispatchBaseClass) or not isinstance(i2, DispatchBaseClass): # Yay - is now an instance returned! raise error("GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2)) del i1 del i2 progress("Checking default args") rc = o.TestOptionals() if rc[:-1] != ("def", 0, 1) or abs(rc[-1]-3.14)>.01: print rc raise error("Did not get the optional values correctly") rc = o.TestOptionals("Hi", 2, 3, 1.1) if rc[:-1] != ("Hi", 2, 3) or abs(rc[-1]-1.1)>.01: print rc raise error("Did not get the specified optional values correctly") rc = o.TestOptionals2(0) if rc != (0, "", 1): print rc raise error("Did not get the optional2 values correctly") rc = o.TestOptionals2(1.1, "Hi", 2) if rc[1:] != ("Hi", 2) or abs(rc[0]-1.1)>.01: print rc raise error("Did not get the specified optional2 values correctly") progress("Checking var args") o.SetVarArgs("Hi", "There", "From", "Python", 1) if o.GetLastVarArgs() != ("Hi", "There", "From", "Python", 1): raise error("VarArgs failed -" + str(o.GetLastVarArgs())) progress("Checking getting/passing IUnknown") if o.GetSetUnknown(o) != o: raise error("GetSetUnknown failed") progress("Checking getting/passing IDispatch") if not isinstance(o.GetSetDispatch(o), DispatchBaseClass): raise error("GetSetDispatch failed") progress("Checking getting/passing IDispatch of known type") if o.GetSetInterface(o).__class__ != o.__class__: raise error("GetSetDispatch failed") if o.GetSetVariant(4) != 4: raise error("GetSetVariant (int) failed") if o.GetSetVariant("foo") != "foo": raise error("GetSetVariant (str) failed") if o.GetSetVariant(o) != o: raise error("GetSetVariant (dispatch) failed") # We want to explicitly test > 32 bits. py3k has no 'maxint' and # 'maxsize+1' is no good on 64bit platforms as its 65 bits! big = 2147483647 # sys.maxint on py2k for l in big, big+1, 1 << 65: if o.GetSetVariant(l) != l: raise error("GetSetVariant (long) failed") if o.TestByRefVariant(2) != 4: raise error("TestByRefVariant failed") if o.TestByRefString("Foo") != "FooFoo": raise error("TestByRefString failed") # Pass some non-sequence objects to our array decoder, and watch it fail. try: o.SetVariantSafeArray("foo") raise error("Expected a type error") except TypeError: pass try: o.SetVariantSafeArray(666) raise error("Expected a type error") except TypeError: pass o.GetSimpleSafeArray(None) TestApplyResult(o.GetSimpleSafeArray, (None,), tuple(range(10))) resultCheck = tuple(range(5)), tuple(range(10)), tuple(range(20)) TestApplyResult(o.GetSafeArrays, (None, None, None), resultCheck) l=[1,2,3,4] TestApplyResult(o.SetVariantSafeArray, (l,), len(l)) TestApplyResult(o.SetIntSafeArray, (l,), len(l)) ll=[1,2,3,0x100000000] TestApplyResult(o.SetLongLongSafeArray, (ll,), len(ll)) TestApplyResult(o.SetULongLongSafeArray, (ll,), len(ll)) # check we can pass ints as a VT_UI1 TestApplyResult(o.SetBinSafeArray, (l,), len(l)) # and binary TestApplyResult(o.SetBinSafeArray, (str2memory('foo\0bar'),), 7) l=[] TestApplyResult(o.SetVariantSafeArray, (l,), len(l)) TestApplyResult(o.SetIntSafeArray, (l,), len(l)) # Tell the server to do what it does! TestApplyResult(o.Test, ("Unused", 99), 1) # A bool function TestApplyResult(o.Test, ("Unused", -1), 1) # A bool function TestApplyResult(o.Test, ("Unused", 1==1), 1) # A bool function TestApplyResult(o.Test, ("Unused", 0), 0) TestApplyResult(o.Test, ("Unused", 1==0), 0) TestApplyResult(o.Test2, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test3, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test4, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test5, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test6, (constants.WideAttr1,), constants.WideAttr1) TestApplyResult(o.Test6, (constants.WideAttr2,), constants.WideAttr2) TestApplyResult(o.Test6, (constants.WideAttr3,), constants.WideAttr3) TestApplyResult(o.Test6, (constants.WideAttr4,), constants.WideAttr4) TestApplyResult(o.Test6, (constants.WideAttr5,), constants.WideAttr5) TestConstant("ULongTest1", ensure_long(0xFFFFFFFF)) TestConstant("ULongTest2", ensure_long(0x7FFFFFFF)) TestConstant("LongTest1", ensure_long(-0x7FFFFFFF)) TestConstant("LongTest2", ensure_long(0x7FFFFFFF)) TestConstant("UCharTest", 255) TestConstant("CharTest", -1) # 'Hello Loraine', but the 'r' is the "Registered" sign (\xae) TestConstant("StringTest", u"Hello Lo\xaeaine") if issubclass(pywintypes.TimeType, datetime.datetime): # For now *all* times passed must be tz-aware. now = win32timezone.now() # but conversion to and from a VARIANT loses sub-second... now = now.replace(microsecond=0) later = now + datetime.timedelta(seconds=1) TestApplyResult(o.EarliestDate, (now, later), now) else: # old PyTime object now = pythoncom.MakeTime(time.gmtime(time.time())) later = pythoncom.MakeTime(time.gmtime(time.time()+1)) TestApplyResult(o.EarliestDate, (now, later), now) # But it can still *accept* tz-naive datetime objects... now = datetime.datetime.now() expect = pythoncom.MakeTime(now) TestApplyResult(o.EarliestDate, (now, now), expect) assert o.DoubleString("foo") == "foofoo" assert o.DoubleInOutString("foo") == "foofoo" o.LongProp = 3 if o.LongProp != 3 or o.IntProp != 3: raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp)) o.LongProp = o.IntProp = -3 if o.LongProp != -3 or o.IntProp != -3: raise error("Property value wrong - got %d/%d" % (o.LongProp,o.IntProp)) check = 3 *10 **9 o.ULongProp = check if o.ULongProp != check: raise error("Property value wrong - got %d (expected %d)" % (o.ULongProp, check)) # currency. pythoncom.__future_currency__ = 1 if o.CurrencyProp != 0: raise error("Expecting 0, got %r" % (o.CurrencyProp,)) try: import decimal except ImportError: import win32com.decimal_23 as decimal for val in ("1234.5678", "1234.56", "1234"): o.CurrencyProp = decimal.Decimal(val) if o.CurrencyProp != decimal.Decimal(val): raise error("%s got %r" % (val, o.CurrencyProp)) v1 = decimal.Decimal("1234.5678") TestApplyResult(o.DoubleCurrency, (v1,), v1*2) TestApplyResult(o.DoubleCurrencyByVal, (v1,), v1*2) v2 = decimal.Decimal("9012.3456") TestApplyResult(o.AddCurrencies, (v1, v2), v1+v2) o.SetParamProp(0, 1) if o.ParamProp(0) != 1: raise RuntimeError(o.paramProp(0)) # Do the connection point thing... # Create a connection object. progress("Testing connection points") sessions = [] o = win32com.client.DispatchWithEvents( o, RandomEventHandler) o._Init() try: for i in range(3): session = o.Start() sessions.append(session) time.sleep(.5) finally: # Stop the servers for session in sessions: o.Stop(session) o._DumpFireds() progress("Finished generated .py test.")