def init_chariot(self):
     """
     Chariot线程,初始化Chariot后,进入Chariot测试循环
     """
     # 获取GUI信息
     chariot_protocol = self.dict_config_items.get('flow_protocol')
     chariot_tcp_script = self.dict_config_items.get('tcp_script')
     chariot_udp_script = self.dict_config_items.get('udp_script')
     chariot_num = self.dict_config_items.get('flow_count')
     chariot_time = self.dict_config_items.get('flow_time')
     mode = ['TX', 'RX', 'TX+RX']
     chariot_flow_mode = mode[self.dict_config_items.get('test_mode')]
     chariot_script_path = join(abspath(dirname(dirname(__file__))), 'resource6.70')
     self.chariot_ip1 = self.dict_config_items.get("local_endpoint")
     self.chariot_ip2 = self.dict_config_items.get("remote_endpoint")
     try:
         CoInitialize()
         self.chariot_obj = Chariot()
         ret = self.chariot_obj.init_chariot()
         self.logger(u"Chariot初始化成功")
         while self.start_state:
             self._chariot_fun_loop(chariot_flow_mode, chariot_protocol, chariot_time, chariot_num, chariot_tcp_script,
                                    chariot_udp_script)
     finally:
         self.logger(u'Chariot控制线程结束')
         del self.chariot_obj
         self.start_state = False
    def run(self):
        try:
            CoInitialize()

            self.c = wmi.WMI()
            self.watcher = self.c.Win32_SystemConfigurationChangeEvent.watch_for(
            )  #called before devicechangeevent
        except:
            eventQueue.put(("Status", 'devices', "Error: WMI Error"))
            eventQueue.put(
                ("Log", "Unable to start device monitor: WMI error"))
            return
        eventQueue.put(("Status", 'devices', "Active"))

        self.running = True
        while self.running == True:
            try:
                event = self.watcher(timeout_ms=2000)
            except wmi.x_wmi_timed_out:
                continue
            eventHandle(
                'E_DEVICE',
                "Device Monitor (%s)" % str(deviceMessages[event.EventType]))

        CoUninitialize()
        eventQueue.put(("Status", 'devices', "Not Running"))
    def run(self):
        try:
            CoInitialize()

            #this code repeated in lw-gui; put it in a function somewhere
            c = wmi.WMI()
            networkAdapters = c.Win32_NetworkAdapter(PhysicalAdapter=True)

            guidDict = {}
            for ad in networkAdapters:
                guidDict[ad.Name] = ad.GUID

            self.c = wmi.WMI(moniker="//./root/WMI")
            self.watcher = self.c.MSNdis_StatusMediaConnect.watch_for()
        except:
            eventQueue.put(("Status", 'netAdaptersIn', 'Connect: WMI Error'))
            return

        eventQueue.put(("Status", 'netAdaptersIn', 'Connect: Active'))
        self.running = True
        while self.running == True:
            try:
                event = self.watcher(timeout_ms=2000)
            except wmi.x_wmi_timed_out:
                continue
            if event.InstanceName in guidDict.keys() and \
                guidDict[event.InstanceName] in fileconfig.config.get('TRIGGERS','adapterConGUIDS').split(';'):
                eventHandle(
                    'E_NET_CABLE_IN',
                    "net adapter '%s' gained connection" % event.InstanceName)

        CoUninitialize()
        eventQueue.put(("Status", 'netAdaptersIn', 'Connect: Not Running'))
Beispiel #4
0
 def __init__(self):
     try:
         CoInitialize()
         self.hamon = wmi.WMI(namespace="root\OpenHardwareMonitor")
         self.initialized = True
     except Exception as e:
         self._err ("Error: Hardware monitor not installed.\nPlease install Hardware Monitor and restart the application.")
 def __init__(self):
     if utils.is_admin():
         CoInitialize()
         self.yfValues = win32com.client.Dispatch('YFExpertPlus.YFValues')
         self.yfValuesList = win32com.client.Dispatch('YFExpertPlus.YFValueList')
         self.hts_result = HTSResult()
     else:
         raise ValueError('Not Admin')
Beispiel #6
0
    def __init__(self, excelFile):
        '''
		Parameters
		file: str, excel file
		'''

        CoInitialize()
        self.excelCOM = DispatchEx('Excel.Application')
        self.excelBook = self.excelCOM.Workbooks.Open(excelFile)
Beispiel #7
0
 def start(self):
     # must delete PID if it exists and stop rsyncd.exe
     self.kill_rsyncd()
     try:
         CoInitialize()
         shell = Dispatch("WScript.Shell")
         shell.Run(r"\BackupPC\backuppc.cmd > C:\BackupPC\file.out")
     except Exception as e:
         self.output(e)
     self.output("starting")
Beispiel #8
0
    def __init__(self, aspenFile):
        '''
		Parameters
		file: str, excel file
		'''

        CoInitialize()
        self.file = aspenFile
        self.COM = DispatchEx('Apwn.Document')
        self.COM.InitFromArchive2(self.file)
 def run(self):
     args = self.args
     CoInitialize()
     if args[0] == 1:
         self.stats.generateStandardReport(args[1], args[2], args[3],
                                           args[4], args[5], args[6],
                                           args[7], args[8])
     elif args[0] == 2:
         self.stats.generatePGReport(args[1], args[2], args[3], args[4],
                                     args[5], args[6], args[7], args[8])
     self.status = 2
Beispiel #10
0
def createShortcut(fileName):
    try:
        CoInitialize()
        winscript = Dispatch("wscript.shell")
        link = join(Desktop, fileName.replace('.exe', '.lnk'))
        if isfile(link):
            remove(link)
        shortcut = winscript.CreateShortcut(link)
        shortcut.TargetPath = '\"{0}\"'.format(join(installPath, fileName))
        shortcut.Save()
    except Exception as err:
        showerror('ERROR', str(err))
Beispiel #11
0
def PPTtoPDF(inputFileName, outputFileName, formatType=32):
    CoInitialize()
    powerpoint = win32com.client.Dispatch("Powerpoint.Application")
    # powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    powerpoint.Visible = 1

    if outputFileName[-3:] != 'pdf':
        outputFileName = outputFileName + ".pdf"
        print(outputFileName)
    deck = powerpoint.Presentations.Open(inputFileName)
    deck.SaveAs(outputFileName, formatType)  # formatType = 32 for ppt to pdf
    deck.Close()
    powerpoint.Quit()
 def begin_session(self):
     try:
         CoInitialize()
         self.request_processor = Dispatch('QBXMLRP2.RequestProcessor')
         self.request_processor.OpenConnection2(self.application_id,
                                                self.application_name,
                                                self.connection_type)
         self.session = self.request_processor.BeginSession(
             self.company_file_name, constants.qbFileOpenDoNotCare)
     except com_error, error:
         self.close_by_force()
         raise QuickBooksError(
             'Could not start QuickBooks COM interface: %s' % error)
Beispiel #13
0
    def run(self):
        self.running = True
        self.file_list = []
        self.update_progressbar.emit(0)
        self.clear_textarea.emit()
        self.update_textarea.emit("Relinking Files in {}\n".format(self.path),
                                  self.colors[0])
        for root, file in self.excel_files(self.path):
            self.file_list.append(os.path.join(root, file))
            self.update_statusbar.emit('Files Found ' +
                                       str(len(self.file_list)))
            if not self.running:
                self.update_statusbar.emit('Canceled')
                return
        self.update_statusbar.emit('Scanning Completed ' +
                                   str(len(self.file_list)) + ' Files Found')
        total_files = len(self.file_list)
        current_count = 0
        CoInitialize()
        self.excel = ExcelDocument(visible=False)
        self.update_statusbar.emit('Starting Excel')
        for file in self.file_list:
            current_count += 1
            self.update_progressbar.emit(
                int(float(current_count) / total_files * 100))
            self.update_statusbar.emit('Relinking %d of %d' %
                                       (current_count, total_files))
            self.excel.display_alerts(False)
            self.excel.open(file, updatelinks=3)
            color = 0
            color += (self.do_search(xlValues) * 1)
            color += (self.do_search(xlFormulas) * 2)
            if color > 0:
                self.do_replace()
            self.update_textarea.emit(file[len(self.path) + 1:],
                                      self.colors[color])
            sleep(2)  # give it some time to work it's magic
            self.excel.save()
            self.excel.close()
            if not self.running:
                break

        self.excel.quit()
        CoUninitialize()
        if current_count == total_files:
            self.update_statusbar.emit('Completed')
            self.update_progressbar.emit(100)
        else:
            self.update_statusbar.emit('Canceled')

        self.sleep(1)
    def run(self):
        CoInitialize()
        self.c = wmi.WMI()
        self.watcher = self.c.Win32_VolumeChangeEvent.watch_for()

        self.running = True
        while self.running == True:
            try:
                event = self.watcher(timeout_ms=2000)
            except wmi.x_wmi_timed_out:
                continue
            eventHandle(
                'E_DEVICE', "Volume Monitor (Drive: '%s' Event: '%s')" %
                (str(event.DriveName), str(deviceMessages[event.EventType])))

        CoUninitialize()
Beispiel #15
0
def convert_word_to_pdf(docx_path, pdf_path):
    """
    将word文档转换成pdf文件
    """
    CoInitialize()
    word = gencache.EnsureDispatch('Word.Application')
    word.Visible = 0
    word.DisplayAlerts = 0
    try:
        doc = word.Documents.Open(docx_path, ReadOnly=1)
        doc.ExportAsFixedFormat(
            pdf_path,
            constants.wdExportFormatPDF,
            Item=constants.wdExportDocumentWithMarkup,
            CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
    except Exception, e:
        print(e)
Beispiel #16
0
def _start_excel():
    """Launches Excel. There is no need to call this directly,
    the Excel functions call it when necessary.

    Example:
    >>> my_excel_app = _start_excel()
    >>> my_excel_app
    <COMObject Excel.Application>

    """

    global xlApp
    CoInitialize()
    if xlApp is None:
        xlApp = win32com.client.DispatchEx('Excel.Application')
        xlApp.Visible = 0
    return xlApp
Beispiel #17
0
 def __init__(self, config):
     CoInitialize()
     SAPbobsCOM = __import__(config['DIAPI'], globals(), locals(), [], -1)
     self.constants = SAPbobsCOM.constants
     self.company = company = SAPbobsCOM.Company()
     company.Server = config['SERVER']
     company.DbServerType = getattr(self.constants, config['DBSERVERTYPE'])
     company.LicenseServer = config['LICENSE_SERVER']
     company.CompanyDB = config['COMPANYDB']
     company.UserName = config['B1USERNAME']
     company.Password = config['B1PASSWORD']
     #company.language = getattr(self.constants, config['LANGUAGE'])
     company.UseTrusted = config['USE_TRUSTED']
     result = company.Connect()
     if result != 0:
         raise Exception("Not connected to COM %" % result)
     print('Connected to COM')
 def run(self):
     CoInitialize()
     self.c = wmi.WMI()
     self.watcher = self.c.Win32_LogicalDisk.watch_for(
         "creation")  #deletion too?
     self.running = True
     while self.running == True:
         try:
             event = self.watcher(timeout_ms=2000)
         except wmi.x_wmi_timed_out:
             continue
         #if event.DriveType in disksOfInterest:
         eventHandle(
             'E_DEVICE',
             "Logical disk creation (Drive Name: '%s', Drive type: '%s')" %
             (event.DeviceID, event.Description))
     CoUninitialize()
    def _split_helper(split_key, split_wait_time):

        if not Splitter.wsh:
            print('WSH for splitter not initialized')
            CoInitialize()
            Splitter.wsh = Dispatch("WScript.Shell")

        if split_wait_time > 0:
            time.sleep(split_wait_time)

        active_hwnd = win32gui.GetForegroundWindow()
        Splitter.wsh.AppActivate(
            Splitter.splitting_program)  # select LiveSplit application
        Splitter.wsh.SendKeys(split_key)
        win32gui.SetForegroundWindow(active_hwnd)
        print('Program:' + Splitter.splitting_program + '\nKey sent:' +
              split_key)
Beispiel #20
0
    def _open(self, filename):
        excel_pathname = os.path.abspath(filename)  # excel requires abspath
        if not os.path.exists(excel_pathname):
            raise IOError('No such excel file: %s', filename)

        CoInitialize()
        try:
            # Using DispatchEx to start new Excel instance, to not interfere with
            # one already possibly running on the desktop
            self.app = win32com.client.DispatchEx('Excel.Application')
            self.app.Visible = 0
        except:
            raise OSError('Failed to start Excel')

        try:
            self.workbook = self.app.Workbooks.Open(excel_pathname, ReadOnly=True)
        except:
            self.close()
            raise IOError('Failed to open %s'%filename)
Beispiel #21
0
def WorkerThread(object_stream):
    # First step - initialize COM
    CoInitialize() # Single-threaded.
    # Unmarshal the IDispatch object.
    object = CoGetInterfaceAndReleaseStream(
        object_stream, IID_IDispatch)
    # The object we get back is a PyIDispatch, rather
    # than a friendly Dispatch instance, so we convert
    # to a usable object.
    object = Dispatch(object)
    this_id = GetCurrentThreadId()
    that_id = object.GetCurrentThreadId()
    message = "Thread is %d, and object is on thread %d" % \
                                     (this_id, that_id)
    print message
    # Be a good citizen and finalize COM, but
    # first remove our object references.
    object = None
    CoUninitialize()
Beispiel #22
0
    def __init__(self):
        if utils.is_admin():
            CoInitialize()
            self.handler = win32com.client.Dispatch(
                'YFExpertPlus.YFRequestData')
            self.event_handler = win32com.client.WithEvents(
                self.handler, RequestEventHandler)
            self.event_handler.client = self.handler

            self.handler.ComInit()
            self.handler.GSComInit(0)

            print('Start Init request data handler!')
            while not self.event_handler.is_connect:
                PumpWaitingMessages()
                time.sleep(0.5)

            self.hts_result = HTSResult()
            print('Init request data handler!')

        else:
            raise ValueError('Not Admin')
Beispiel #23
0
def tts(update, context):
    filename = datetime.now().strftime("%d%m%y-%H%M%S%f")
    reply = update.message.reply_to_message
    if reply is None:
        text = "".join(context.args)
    elif reply.text is not None:
        text = reply.text
    else:
        return
    if len(text) == 0:
        update.message.reply_text("Type in some text ^^")
        return
    update.message.chat.send_action(ChatAction.RECORD_AUDIO)
    CoInitialize()
    speak = comtypes.client.CreateObject("SAPI.SpVoice")
    filestream = comtypes.client.CreateObject("SAPI.spFileStream")
    filestream.open(path + filename + ".ogg", 3, False)
    speak.AudioOutputStream = filestream
    speak.Speak(text)
    filestream.close()
    CoUninitialize()
    with open(path + filename + ".ogg", "rb") as speech:
        update.message.reply_voice(speech, quote=False)
    os.remove(path + filename + ".ogg")
Beispiel #24
0
    def _reboot_server(system_info, failed_servers):
        """
        This function is executed by each thread which is created by parent thread "reboot_servers".
        Based on type of host opens connection to host and executes reboot command on each.
        Then waits for the server to shutdown and come up again.
        """

        logger.debug("rebooting_server:%s" % (system_info['host']))

        if system_info['type'] in ('LINUX', 'VMWARE'):
            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(system_info['host'],
                               username=system_info['username'],
                               password=system_info['password'])
                stdin, stdout, stderr = client.exec_command('reboot')
                client.close()
            except:
                print "unable to reboot %s" % (system_info['host'])
                failed_servers.append(system_info['host'])
                return -1

        elif system_info['type'] in ('WINDOWS'):
            try:
                CoInitialize(
                )  #Needs to be called when making multiple windows connections from a thread using wmi module
                connection = wmi.WMI(system_info['host'],
                                     user=system_info['username'],
                                     password=system_info['password'])
                (pid, status) = connection.Win32_Process.Create(
                    CommandLine="shutdown -r", CurrentDirectory='.')
                print pid, status, " from %s" % (system_info['host'])
            except Exception as ex:
                if ex.com_error:
                    failed_servers.append(system_info['host'])
                print "Unable to reboot %s" % (system_info['host'])
            except wmi.x_wmi:
                failed_servers.append(system_info['host'])
                print "Your Username and Password for %s are wrong." % (
                    system_info['host'])
                return -1
            except:
                failed_servers.append(system_info['host'])
                print "Unable to reboot %s" % (system_info['host'])
                return -1

        # Wait for server to be down
        timeout = 300
        while True:
            timeout -= 1
            response = os.system("ping -n 1 %s > nul 2>&1" %
                                 (system_info['host']))
            if response == 0:
                if timeout <= 0:
                    failed_servers.append(system_info['host'])
                    logger.debug(
                        "%s failed to reboot after issuing reboot command" %
                        (system_info['host']))
                    return -1
            else:
                break
            time.sleep(1)

        timeout = 600
        # Wait for server to be up
        while True:
            timeout -= 1
            response = os.system("ping -n 1 %s > nul 2>&1" %
                                 (system_info['host']))
            if response != 0:
                if timeout <= 0:
                    failed_servers.append(system_info['host'])
                    logger.debug("%s failed to come up after reboot" %
                                 (system_info['host']))
                    return -1
            else:
                break
            time.sleep(1)
        return 0
Beispiel #25
0
 def Subscribe(self, _type=None, code=None):
     if _type and code: self.SetInputValue(_type, code)
     self.com.SubscribeLatest()
     CoInitialize()
     pass
Beispiel #26
0
 def factory():
     from pythoncom import CoInitialize
     CoInitialize()
     return win32com.client.Dispatch(self.settings.com_object)
Beispiel #27
0
def email_outlook_trigger_monitor():
    t.sleep(15)

    while True:
        range(10000)
        t.sleep(
            randrange((round(email_outlook_sleep / 2)), email_outlook_sleep))

        if EmailOutlookTrigger.objects.filter(activated=True).exists():
            break

    CoInitialize()
    email_outlook = win32.dynamic.Dispatch('Outlook.Application')

    while True:
        range(10000)
        t.sleep(
            randrange((round(email_outlook_sleep / 2)), email_outlook_sleep))

        if os.path.exists("logs\\error_log.txt"):
            break

        try:
            email_outlook_trigger_monitor_evaluate(email_outlook)

        except EmailOutlookDispatchException:
            print(
                "Connection to Outlook lost, attempting to restart monitoring..."
            )

            try:
                email_outlook.Application.Quit()
            except:
                pass

            email_outlook = None
            del email_outlook

            CoUninitialize()

            email_outlook_trigger_monitor()

        except:
            with open("logs\\error_log.txt", 'a') as f:
                try:
                    f.write(traceback.format_exc())
                    print(traceback.format_exc())
                except:
                    pass
            break

        if not EmailOutlookTrigger.objects.filter(activated=True).exists():
            try:
                email_outlook.Application.Quit()
            except:
                pass

            email_outlook = None
            del email_outlook

            CoUninitialize()

            email_outlook_trigger_monitor()

    try:
        email_outlook.Application.Quit()
    except:
        pass

    email_outlook = None
    del email_outlook

    CoUninitialize()
Beispiel #28
0
    def download(self):
        self.builder.get_object('DownloadStatusLabel').config(
            text="Obtaining latest release...")

        def reporthook(blocknum, blocksize, totalsize):
            self.builder.get_object('DownloadStatusLabel').config(
                text="Downloading...")

            readsofar = blocknum * blocksize
            if totalsize > 0:
                percent = readsofar * 1e2 / totalsize
                self.builder.create_variable('double:download_progress').set(
                    percent)
                self.builder.get_object('DownloadRatio').config(
                    # text='{:.1} %'.format(percent)
                    text="{:.1f} / {:.1f} MB".format(readsofar /
                                                     1048576, totalsize /
                                                     1048576))

                if readsofar >= totalsize:  # near the end
                    self.builder.get_object('DownloadStatusLabel').config(
                        text="Download complete")
                    self.builder.get_object('RetryButton').config(
                        state=DISABLED)
            else:  # total size is unknown
                pass

        try:
            repoURL = urlopen(self.settings['app_repo_url'] + '/.setupdata')
            data = repoURL.read()
            encoding = repoURL.info().get_content_charset('utf-8')
            latestSetupData = loads(data.decode(encoding))

            try:  # download
                filehandle, _ = urlretrieve(
                    url=latestSetupData['app_repo_url'] +
                    latestSetupData['latest_windows_dist_url'],
                    reporthook=reporthook)

                try:  # install
                    self.builder.get_object('InstallStatusLabel').config(
                        text="Installing...")
                    ZipFile(filehandle).extractall(
                        self.settings['install_path'])
                    if self.settings['create_shortcut']:
                        CoInitialize()
                        appPath = '{}\\{}\\{}.exe'.format(
                            self.settings['install_path'],
                            self.settings['app_name'],
                            self.settings['app_name'])
                        self.createShortcut(path=os.path.join(
                            desktop(),
                            self.settings['app_name'].replace('_', ' ') +
                            '.lnk'),
                                            target=appPath,
                                            wDir='{}\\{}'.format(
                                                self.settings['install_path'],
                                                self.settings['app_name']),
                                            icon=appPath)
                    self.builder.get_object('InstallStatusLabel').config(
                        text="Installation complete!")
                    self.builder.get_object('FinishButton').config(
                        state=NORMAL)
                except:
                    messagebox.showwarning(
                        title='{} Setup Wizard'.format(
                            self.settings['app_name']),
                        message=
                        'Setup is unable to install additional files. Please try again.'
                    )
            except:
                messagebox.showwarning(
                    title='{} Setup Wizard'.format(self.settings['app_name']),
                    message=
                    'Setup is unable to download additional files. Please make sure that you have an internet connection, then click Retry.'
                )
        except:
            messagebox.showwarning(
                title='{} Setup Wizard'.format(self.settings['app_name']),
                message=
                'An unexpected error occured. Setup wizard is unable to obtain additional files. Click Retry.'
            )
Beispiel #29
0
 def process(self):
     CoInitialize()
     self._running = True
     while self._running:
         time.sleep(0.1)
         PumpWaitingMessages()
Beispiel #30
0
 def AdviseRealData(self):
     self.com.AdviseRealData()
     CoInitialize()
     pass