def Setup(self, plugin, eventHandler): self.plugin = plugin self.eventHandler = eventHandler self.comInstance = DispatchWithEvents( 'X10net.X10Control.1', eventHandler )
class Realtime: def __init__(self, res, callback): self._res = res self._instance = DispatchWithEvents('XA_DataSet.XAReal', _RealtimeHandler) self._instance.LoadFromResFile(f'/Res/{res}.res') self._instance.callback = callback self.subscribed_keys = [] def subscribe(self, key=None): if key in self.subscribed_keys: print(f'{self._res}는 이미 {key} 데이터를 수신 중입니다.') return None if key: self._instance.SetFieldData('InBlock', meta_res[self._res]['input']['InBlock']['fields'][0]['name'], key) self._instance.AdviseRealData() self.subscribed_keys.append(key) def unsubscirbe(self, key=None): if key is None: self._instance.UnadviseRealData() else: if key not in self.subscribed_keys: raise ValueError(f'{self._res}는 {key} 데이터를 수신하고 있지 않습니다.') self._instnace.UnadviseRealDataWithKey(key) @staticmethod def listen(delay=.01): while True: PumpWaitingMessages() time.sleep(delay)
def OnConnection(self, application, connectMode, addin, custom): print "OnConnection", application, connectMode, addin, custom # ActiveExplorer may be none when started without a UI (eg, WinCE synchronisation) activeExplorer = application.ActiveExplorer() if activeExplorer is not None: bars = activeExplorer.CommandBars toolbar = bars.Item("Menu Bar") item_lista = toolbar.Controls.Add(Type=constants.msoControlButton, Temporary=True) item_lista = self.menubarButton = DispatchWithEvents( item_lista, AboutEvent) item_lista.Caption = "Impulzia" item_lista.Enabled = True #TODO: Create a Openerp Bar toolbar = bars.Item("Standard") # Sync button in toolbar item = toolbar.Controls.Add(Type=constants.msoControlButton, Temporary=True) item = self.toolbarButton = DispatchWithEvents(item, ButtonEvent) item.Caption = "Syncronization" item.TooltipText = "Click to sync with openerp" item.Enabled = True # Getting Messages and contacts events inbox = application.Session.GetDefaultFolder(constants.olFolderInbox) self.inboxItems = DispatchWithEvents(inbox.Items, FolderEvent) contacts = application.Session.GetDefaultFolder( constants.olFolderContacts) self.contactsItems = DispatchWithEvents(contacts.Items, ContactsEvent)
def Setup(self, plugin, eventHandler): """ This will be called inside the thread at the beginning. """ self.plugin = plugin self.eventHandler = eventHandler self.comobj_yard = DispatchWithEvents(YARD_CLSID, self.eventHandler)
class YardWorkerThread(eg.ThreadWorker): """ Handles the COM interface in a thread of its own """ comobj_yard = None plugin = None eventHandler = None @eg.LogItWithReturn def Setup(self, plugin, eventHandler): """ This will be called inside the thread at the beginning. """ self.plugin = plugin self.eventHandler = eventHandler self.comobj_yard = DispatchWithEvents(YARD_CLSID, self.eventHandler) @eg.LogIt def Finish(self): """ This will be called inside the thread when it finishes. It will even be called if the thread exits through an exception. """ if self.comobj_yard: self.comobj_yard.close() del self.comobj_yard
def OnConnection(self, application, connectMode, addin, custom): # ActiveExplorer may be none when started without a UI (eg, WinCE synchronisation) activeExplorer = application.ActiveExplorer() if activeExplorer is not None: bars = activeExplorer.CommandBars menu_bar = bars.Item("Menu Bar") tools_menu = menu_bar.Controls(5) tools_menu = CastTo(tools_menu, "CommandBarPopup") item = tools_menu.Controls.Add(Type=constants.msoControlButton, Temporary=True) # Hook events for the item item = self.menu_bar_Button = DispatchWithEvents(item, ButtonEvent) item.Caption = "OpenERP Configuration" item.TooltipText = "Click to configure OpenERP" item.Enabled = True toolbar = bars.Item("Standard") item = toolbar.Controls.Add(Type=constants.msoControlButton, Temporary=True) # Hook events for the item item = self.toolbarButton = DispatchWithEvents(item, ArchiveEvent) item.Caption = "Archive to OpenERP" item.TooltipText = "Click to archive to OpenERP" item.Enabled = True
def __init__(self, res, callback): self._res = res self._instance = DispatchWithEvents('XA_DataSet.XAReal', _RealtimeHandler) self._instance.LoadFromResFile(f'/Res/{res}.res') self._instance.callback = callback self.subscribed_keys = []
def init_cv(cd="C:\\CVUSER"): """ Initializes a CODE V COM session. """ # Try connecting try: cv = DispatchWithEvents("CodeV.Application", ICVApplicationEvents) cv.StartingDirectory = cd cv.StartCodeV() return cv # Otherwise show error except pythoncom.com_error as error: print("---------") args = error.args for a in args: print(a) print(error.strerror) stop_cv(cv)
def __init__(self): self.event = DispatchWithEvents("XA_Session.XASession", XASessionEvents) self.com = self.event._obj_ self.event.parent = proxy(self) self.observer = None self.observers = [] self.data = None self.flag = False pass
def run(self): self.evt_handler = ButtonEvent cbcMyBar = self.xl_app.CommandBars.Add(Name="Transition Add-in conf", Position=constants.msoBarTop, MenuBar=constants .msoBarTypeNormal, Temporary=True) btnMyButton = cbcMyBar.Controls.Add(Type=constants.msoControlButton, Parameter="Greetings") btnMyButton = DispatchWithEvents(btnMyButton, self.evt_handler) btnMyButton.Style = constants.msoButtonIconAndCaptionBelow btnMyButton.BeginGroup = True btnMyButton.Caption = "&Transition config" btnMyButton.TooltipText = "Launch Transition config panel" btnMyButton.Width = "34" btnMyButton.FaceID = 1713 btnMyButton.xlApp = self.xl_app cbcMyBar.Visible = True print(self.name, "addin plugged. Waiting for events...") # Main loop while self.ask_quit is False: win32event.WaitForSingleObject(btnMyButton.event, 1000) #Does dialog still running ? if btnMyButton.dialog is not None: #check if the dialog still running (Poll() return None) if btnMyButton.dialog.poll() is None: btnMyButton.dialog.terminate() self.xl_app = None
def TestExcel(): class ExcelEvents: def OnNewWorkbook(self, wb): if type(wb) != types.InstanceType: raise RuntimeError("The transformer doesnt appear to have translated this for us!") self.seen_events["OnNewWorkbook"] = None def OnWindowActivate(self, wb, wn): if type(wb) != types.InstanceType or type(wn) != types.InstanceType: raise RuntimeError("The transformer doesnt appear to have translated this for us!") self.seen_events["OnWindowActivate"] = None def OnWindowDeactivate(self, wb, wn): self.seen_events["OnWindowDeactivate"] = None def OnSheetDeactivate(self, sh): self.seen_events["OnSheetDeactivate"] = None def OnSheetBeforeDoubleClick(self, Sh, Target, Cancel): if Target.Column % 2 == 0: print("You can double-click there...") else: print("You can not double-click there...") # This function is a void, so the result ends up in # the only ByRef - Cancel. return 1 class WorkbookEvents: def OnActivate(self): print("workbook OnActivate") def OnBeforeRightClick(self, Target, Cancel): print("It's a Worksheet Event") e = DispatchWithEvents("Excel.Application", ExcelEvents) e.seen_events = {} e.Visible = 1 book = e.Workbooks.Add() book = DispatchWithEvents(book, WorkbookEvents) print("Have book", book) # sheet = e.Worksheets(1) # sheet = DispatchWithEvents(sheet, WorksheetEvents) print("Double-click in a few of the Excel cells...") print("Press any key when finished with Excel, or wait 10 seconds...") if not _WaitForFinish(e, 10): e.Quit() if not _CheckSeenEvents(e, ["OnNewWorkbook", "OnWindowActivate"]): sys.exit(1)
def OnConnection(self, application, connectMode, addin, custom): print "OnConnection", application, connectMode, addin, custom try: self.appHostApp = application cbcMyBar = self.appHostApp.CommandBars.Add( Name="PythonBar", Position=constants.msoBarTop, MenuBar=constants.msoBarTypeNormal, Temporary=True) btnMyButton = cbcMyBar.Controls.Add( Type=constants.msoControlButton, Parameter="Greetings") btnMyButton = self.toolbarButton = DispatchWithEvents( btnMyButton, ButtonEvent) btnMyButton.Style = constants.msoButtonCaption btnMyButton.BeginGroup = True btnMyButton.Caption = "&Python" btnMyButton.TooltipText = "Python rules the World" btnMyButton.Width = "34" cbcMyBar.Visible = True except pythoncom.com_error, (hr, msg, exc, arg): print "The Excel call failed with code %d: %s" % (hr, msg) if exc is None: print "There is no extended error information" else: wcode, source, text, helpFile, helpId, scode = exc print "The source of the error is", source print "The error message is", text print "More info can be found in %s (id=%d)" % (helpFile, helpId)
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, com_module): self.event = DispatchWithEvents(com_module, XARealEvents) self.com = self.event._obj_ self.event.parent = proxy(self) self.observer = None self.observers = [] self.RecvMsg = None pass
def __init__(self): clsid = '{F2303261-4969-11D1-B305-00805F815CBF}' progid = 'Bloomberg.Data.1' print 'connecting to BBCom........' print 'getting historical data.....' blp = DispatchWithEvents(clsid, get_historical_data) blp.GetHistoricalData('AAPL US Equity', 1, entity, start, end, Results = Empty) blp.AutoRelease = False blp.Flush() end_time = time() + 1 while 1: PumpWaitingMessages() if end_time < time(): print 'timed out' break
def OnConnection(self, application, connectMode, addin, custom): print("OnConnection", application, connectMode, addin, custom) # ActiveExplorer may be none when started without a UI (eg, WinCE synchronisation) activeExplorer = application.ActiveExplorer() if activeExplorer is not None: bars = activeExplorer.CommandBars toolbar = bars.Item("Standard") item = toolbar.Controls.Add(Type=constants.msoControlButton, Temporary=True) # Hook events for the item item = self.toolbarButton = DispatchWithEvents(item, ButtonEvent) item.Caption = "Python" item.TooltipText = "Click for Python" item.Enabled = True # And now, for the sake of demonstration, setup a hook for all new messages inbox = application.Session.GetDefaultFolder(constants.olFolderInbox) self.inboxItems = DispatchWithEvents(inbox.Items, FolderEvent)
def TestWord(): class WordEvents: def OnDocumentChange(self): self.seen_events["OnDocumentChange"] = None def OnWindowActivate(self, doc, wn): self.seen_events["OnWindowActivate"] = None def OnQuit(self): self.seen_events["OnQuit"] = None stopEvent.set() w = DispatchWithEvents("Word.Application", WordEvents) w.seen_events = {} w.Visible = 1 w.Documents.Add() print "Press any key when finished with Word, or wait 10 seconds..." if not _WaitForFinish(w, 10): w.Quit() if not _CheckSeenEvents(w, ["OnDocumentChange", "OnWindowActivate"]): sys.exit(1)
def __init__(self, com_module): gencache.EnsureModule("859343F1-08FD-11D4-8231-00105A7C4F8C", 0, 1, 0) gencache.EnsureModule("9C31B76A-7189-49A3-9781-3C6DD6ED5AD3", 0, 1, 0) gencache.EnsureModule("1F7D5E5A-05AB-4236-B6F3-3D383B09203A", 0, 1, 0) gencache.EnsureModule("2DA9C35C-FE59-4A32-A942-325EE8A6F659", 0, 1, 0) self.event = DispatchWithEvents(com_module, CpEvent) self.com = self.event._obj_ self.event.parent = proxy(self) self.observers = [] pass
def TestConnection(dbname): # Create the ADO connection object, and link the event # handlers into it c = DispatchWithEvents("ADODB.Connection", ADOEvents) # Initiate the asynchronous open dsn = "Driver={Microsoft Access Driver (*.mdb)};Dbq=%s" % dbname user = "******" pw = "manager" c.Open(dsn, user, pw, constants.adAsyncConnect) # Sit in a loop, until our event handler (above) sets the # "finished" flag or we time out. end_time = time.clock() + 10 while time.clock() < end_time: # Pump messages so that COM gets a look in pythoncom.PumpWaitingMessages() if not finished: print("XXX - Failed to connect!")
def Connect(): global NotifyTF, NotifySPRD, 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') NotifyTF = DispatchWithEvents('XTAPI.TTInstrNotify', InstrNotify) NotifyTF.gen_agent('agentTF', 'channelTF') print('Connected...') NotifySPRD = DispatchWithEvents('XTAPI.TTInstrNotify', InstrNotify) NotifySPRD.gen_agent('agentSPRD', 'channelSPRD') print(' Connected Spreads...')
def init_bbg_session(): global session global rfd if not bbg_imports: logging.info('Call to BBG but could not load the imports') return False; try: if session is None: session = DispatchWithEvents('blpapicom.ProviderSession.1', SessionEvents) # Start a Session session.Start() if not session.OpenService('//blp/refdata'): print 'Failed to opent service' raise Exception # event loop session.continueLoop = True rfd = session.GetService('//blp/refdata') return True except com_error as error: logging.info('Failed to init BBG: {0}'.format(error[1])) return False
def __init__(self): clsid = '{F2303261-4969-11D1-B305-00805F815CBF}' progid = 'Bloomberg.Data.1' print 'connecting to BBCom........' print 'getting historical data.....' blp = DispatchWithEvents(clsid, get_historical_data) for sym in list: global tick tick = sym self.get(blp, sym)
def execute_request(request): session = DispatchWithEvents('blpapicom.ProviderSession.1', ResponseHandler) session.Start() try: svcname = request.get_bbg_service_name() if not session.OpenService(svcname): raise Exception('failed to open service %s' % svcname) svc = session.GetService(svcname) asbbg = request.get_bbg_request(svc, session) session.SendRequest(asbbg) session.do_init(request) while session.waiting: PumpWaitingMessages() session.has_deferred_exception and session.raise_deferred_exception() request.has_exception and request.raise_exception() return request finally: session.Stop() session.do_cleanup()
def __init__(self,com_cp_str): try : self.__received_evt_ch = cxChannel() except cxError as e : raise e except : raise cxError(0xFFFFFFFF,'general','unknown error','') try : self.com_cp = DispatchWithEvents( com_cp_str,\ cxCybosBaseWithEvent.cxEvent ) except pythoncom.com_error, (hr, msg, exc, arg) : raise cxError(hr,'COM',msg,'check whether cybos plus running or not')
def Setup(self, plugin): """This will be called inside the thread at the beginning.""" self.plugin = plugin class SubEventHandler(EventHandler): thread = self TriggerEvent = self.plugin.TriggerEvent self.EventHandler = SubEventHandler self.phoner = None self.events = None self.phoner = Dispatch("Phoner.CPhoner") self.events = DispatchWithEvents(self.phoner, self.EventHandler)
def initialize(password=None, delay=1): CybosPlus.CpCybos = DispatchWithEvents('CpUtil.CpCybos', EventDisconnectHandler) CybosPlus.CpStockCode = Dispatch('CpUtil.CpStockCode') CybosPlus.CpCodeMgr = Dispatch("CpUtil.CpCodeMgr") CybosPlus.CpTdUtil = Dispatch("CpTrade.CpTdUtil") CybosPlus.CpTradeAccPortfolio = Dispatch("CpTrade.CpTd6033") CybosPlus.CpTradeAccBalanceBuy = Dispatch("CpTrade.CpTdNew5331A") CybosPlus.CpTradeAccBalanceSell = Dispatch("CpTrade.CpTdNew5331B") CybosPlus.CpTradeCashOrder = Dispatch("CpTrade.CpTd0311") CybosPlus.CpTradeChangePrice = Dispatch("CpTrade.CpTd0313") CybosPlus.CpTradeCancelOrder = Dispatch("CpTrade.CpTd0314") CybosPlus.CpTradeOrderStatus = Dispatch("CpTrade.CpTd5341") CybosPlus.StockChart = Dispatch("CpSysDib.StockChart") CybosPlus.MarketEye = Dispatch("CpSysDib.MarketEye") CybosPlus.trade_init(password, delay)
class X10ThreadWorker(eg.ThreadWorker): comInstance = None plugin = None eventHandler = None def Setup(self, plugin, eventHandler): self.plugin = plugin self.eventHandler = eventHandler self.comInstance = DispatchWithEvents('X10net.X10Control.1', eventHandler) def Finish(self): if self.comInstance: self.comInstance.Close() del self.comInstance
def TestExcel(): class ExcelEvents: def OnNewWorkbook(self, wb): if type(wb) != types.InstanceType: raise RuntimeError( "The transformer doesnt appear to have translated this for us!" ) self.seen_events["OnNewWorkbook"] = None def OnWindowActivate(self, wb, wn): if type(wb) != types.InstanceType or type( wn) != types.InstanceType: raise RuntimeError( "The transformer doesnt appear to have translated this for us!" ) self.seen_events["OnWindowActivate"] = None def OnWindowDeactivate(self, wb, wn): self.seen_events["OnWindowDeactivate"] = None def OnSheetDeactivate(self, sh): self.seen_events["OnSheetDeactivate"] = None def OnSheetBeforeDoubleClick(self, Sh, Target, Cancel): if Target.Column % 2 == 0: print("You can double-click there...") else: print("You can not double-click there...") # This function is a void, so the result ends up in # the only ByRef - Cancel. return 1 class WorkbookEvents: def OnActivate(self): print("workbook OnActivate") def OnBeforeRightClick(self, Target, Cancel): print("It's a Worksheet Event") e = DispatchWithEvents("Excel.Application", ExcelEvents) e.seen_events = {} e.Visible = 1 book = e.Workbooks.Add() book = DispatchWithEvents(book, WorkbookEvents) print("Have book", book) # sheet = e.Worksheets(1) # sheet = DispatchWithEvents(sheet, WorksheetEvents) print("Double-click in a few of the Excel cells...") print("Press any key when finished with Excel, or wait 10 seconds...") if not _WaitForFinish(e, 10): e.Quit() if not _CheckSeenEvents(e, ["OnNewWorkbook", "OnWindowActivate"]): sys.exit(1)
class EVO: def __init__(self): self.system = DispatchWithEvents('EVOAPI.System',EVOSystemEvents) def logon(self): self.system.Logon(WorkTableSettings.username,WorkTableSettings.password,0,WorkTableSettings.isRealRobot) while (self.system.GetStatus() & EVOConstants.STATUS_LOADING == EVOConstants.STATUS_LOADING): time.sleep(1) print "Ready" def logoff(self): self.system.Logoff() def shutdown(self): self.logoff() self.system.Shutdown() def prepareScript(self,scriptName): self.scriptID = self.system.PrepareScript(scriptName) def startScript(self,scriptName): self.scriptID = self.system.PrepareScript(scriptName) self.system.Initialize() time.sleep(5) #TODO: add correct while loop self.system.StartScript(self.scriptID,0,0) time.sleep(2) #TODO: add correct loop def startInteractive(self): self.startScript("InteractiveScript")
class ExplorerWithEvents(ObjectWithEvents): def Init(self, explorers_collection): dbg_print('ExplorerWithEvents:Init') self.have_setup_ui = False self.event_handlers = [] ObjectWithEvents.Init(self, explorers_collection) def SetupUI(self): # find Help->About Outlook menu aboutOutlook = self.CommandBars.FindControl( Type=constants.msoControlButton, Id=927) if aboutOutlook is None: return popup = aboutOutlook.Parent if popup is None: return # Add Help->About Clamwin menu item child = self._AddControl(popup, constants.msoControlButton, ButtonEvent, (HelpAbout, ), Caption="&About ClamWin Free Antivirus", TooltipText="Shows the ClamWin About Box", Enabled=True, Visible=True, Tag="ClamWin.About") self.have_setup_ui = True def _AddControl( self, parent, # who the control is added to control_type, # type of control to add. events_class, events_init_args, # class/Init() args **item_attrs): # extra control attributes. assert item_attrs.has_key('Tag'), "Need a 'Tag' attribute!" image_fname = None if 'image' in item_attrs: image_fname = item_attrs['image'] del item_attrs['image'] tag = item_attrs["Tag"] item = self.CommandBars.FindControl(Type=control_type, Tag=tag) if item is None: # Now add the item itself to the parent. try: item = parent.Controls.Add(Type=control_type, Temporary=True) except pythoncom.com_error, e: print "FAILED to add the toolbar item '%s' - %s" % (tag, e) return if image_fname: # Eeek - only available in derived class. assert control_type == constants.msoControlButton but = CastTo(item, "_CommandBarButton") SetButtonImage(but, image_fname) # Set the extra attributes passed in. for attr, val in item_attrs.items(): setattr(item, attr, val) # didn't previously set this, and it seems to fix alot of problem - so # we set it for every object, even existing ones. item.OnAction = "<!" + OutlookAddin._reg_progid_ + ">" # Hook events for the item, but only if we haven't already in some # other explorer instance. if events_class is not None and tag not in self.collection.button_event_map: item = DispatchWithEvents(item, events_class) item.Init(*events_init_args) # We must remember the item itself, else the events get disconnected # as the item destructs. self.collection.button_event_map[tag] = item return item
def _DoNewObject(self, obj): obj = DispatchWithEvents(obj, self.classWithEvents) obj.Init(self) self.objects.append(obj) return obj
def query(res, send, cont=False, timeout=10): """ Query 요청 @arg res[str]`t1102` 사용할 res 파일명 @arg send[dict] 전송할 데이터 { 'Block1': [{'Field1': 'Value1', 'Field2': 'Value2'}, {...}, {...}], 'Block2': {'Field3': 'Value3', 'Field4': 'Value4'} } 단일 InBlock의 경우에는 아래와 같이 간단한 형식도 입력받음 {'Field1': 'Value1', 'Field2': 'Value2'} @arg cont[*bool=False] 연속조회 여부 @arg timeout[*int=10] 서버 응답 최대 대기 시간, -1인 경우 infinite time """ # res 파일 로드 _query = DispatchWithEvents('XA_DataSet.XAQuery', _QueryHandler) _query.init(res) if not cont: # 전송 현황 업데이트 if not res in _query_status: _query_status[res] = [] while _query_status[res] and _query_status[res][-1] + 1 < time.time(): _query_status[res].pop() # 초당 전송 횟수를 고려 tr_count_per_sec = _query.GetTRCountPerSec(res) if len(_query_status[res]) >= tr_count_per_sec: delay = max(_query_status[res][-1] + 1.05 - time.time(), 0) time.sleep(delay) # 기간(10분)당 전송 횟수를 고려 # TODO : 10분 제한이 걸리면 blocking state 진입 tr_count_limit = _query.GetTRCountLimit(res) while tr_count_limit and _query.GetTRCountRequest(res) >= tr_count_limit: time.sleep(1) _query = DispatchWithEvents('XA_DataSet.XAQuery', _QueryHandler) _query.init(res) # simplified 된 input를 받았을 경우 send_first_value = list(send.values())[0] if not ( isinstance (send_first_value, list) or isinstance (send_first_value, dict) ): send = { '{}InBlock'.format(res): send } # 전송할 데이터를 설정 for block in send.keys(): if isinstance(send[block], dict): for (k, v) in send[block].items(): _query.set_data(block, k, v) elif isinstance(send[block], list): for i in range(len(send[block])): for (k, v) in send[block][i].items(): _query.set_data(block, k, v, i) else: raise ValueError('알 수 없는 형태의 데이터입니다') else: time.sleep(0.05) # 데이터 요청 _query.Request(cont) now = time.time() if not cont: _query_status[res].insert(0, now) _query.waiting = True while _query.waiting: if timeout >= 0 and now + timeout < time.time(): _query.waiting = False raise TimeoutError('Query Timeout') PumpWaitingMessages() return _query.response
""" self.waiting = False if code == '0000': logger.info('[*] 로그인 성공') else: logger.warning('[*] 로그인 실패 : {}'.format(msg)) def OnDisconnect(self): """ 서버와의 연결이 끊어졌을 때 실행되는 함수 """ self.waiting = False logger.info('[*] 서버와의 연결이 끊어졌습니다') _session = DispatchWithEvents('XA_Session.XASession', _SessionHandler) def login( server=None, username=None, password=None, ): """ 로그인 """ # 기존에 연결되어 있는 서버가 있으면, 연결을 끊는다 if _session.IsConnected(): _session.DisconnectServer() # 로그인 시 필요한 정보를 입력받는다 login_server = (server or input('[*] 접속 서버 ((r)eal / (D)emo / (a)ce) : ')).lower()[:1] login_server = {
def execute_request(request): session = DispatchWithEvents('blpapicom.ProviderSession.1', ResponseHandler) session.Start() try: svcname = request.get_bbg_service_name() if not session.OpenService(svcname): raise Exception('failed to open service %s' % svcname) svc = session.GetService(svcname) asbbg = request.get_bbg_request(svc, session) session.SendRequest(asbbg) session.do_init(request) while session.waiting: PumpWaitingMessages() session.has_deferred_exception and session.raise_deferred_exception( ) request.has_exception and request.raise_exception() return request finally: session.Stop() session.do_cleanup()
def __init__(self, AddInSiteObject): self._app = Dispatch(AddInSiteObject).Application self._ApplicationEvents = DispatchWithEvents( self._app.ApplicationEvents, ApplicationEvents)