Exemplo n.º 1
0
 def coinit(threading=None):
     """
 @param  threading  bool or None
 """
     if threading is None:  # The same as STA
         pythoncom.CoInitialize()  # this function returns None
     elif threading:  # Multi-thread apartment (MTA)
         pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
     else:  # Single thread apartment (STA)
         pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
def testGatan():
    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
    camera = None
    try:
        camera = win32com.client.dynamic.Dispatch('TecnaiCCD.GatanCamera')
    except pythoncom.com_error, e:
        pass
Exemplo n.º 3
0
    def update_thread_handler(self) -> None:
        logging.info("update_thread_handler start")
        try:
            pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)

            asyncio.set_event_loop_policy(
                asyncio.WindowsProactorEventLoopPolicy())
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            self.async_loop = loop
            self.update_message_queue = asyncio.Queue(loop=self.async_loop)
            self.send_message_queue = asyncio.Queue(loop=self.async_loop)
            self.ready_to_send = asyncio.Event(loop=self.async_loop)

            # Following call can cause deadlock if mainthread is not pumping Windows message.
            self.SetCallbackThread()

            update_msg_coro = self._update_msg_handler()
            send_msg_coro = self._send_msg_handler()
            loop.run_until_complete(
                asyncio.gather(update_msg_coro, send_msg_coro))
            loop.close()
        except Exception as e:
            logging.error("update_thread_handler: {}".format(repr(e)))
        finally:
            pythoncom.CoUninitialize()
Exemplo n.º 4
0
def saytext(text):
    if root and config_var['Settings']['voice'] == "yes":
        try:
            pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
            speak.Speak(text)
        except Exception as e:
            print(e)
Exemplo n.º 5
0
        def _get_process_by_pid(pid):
            import win32api
            import win32con
            import pywintypes
            import win32com.client
            import pythoncom

            pythoncom.CoInitializeEx(0)
            mgmt = win32com.client.GetObject('winmgmts:')

            # Get all processes with the given PID
            process_list = mgmt.ExecQuery(
                "SELECT * from Win32_Process where ProcessId = {pid}".format(
                    pid=pid))
            if process_list:
                try:
                    # Get process
                    proc = win32api.OpenProcess(
                        win32con.PROCESS_QUERY_INFORMATION
                        | win32con.PROCESS_VM_READ, False, pid)
                    return proc

                except pywintypes.error:
                    return None

            pythoncom.CoUninitialize()
Exemplo n.º 6
0
        def _get_process_by_name(ps_name):
            import win32api
            import win32con
            import pywintypes
            import win32com.client
            import pythoncom

            pythoncom.CoInitializeEx(0)
            mgmt = win32com.client.GetObject('winmgmts:')

            # Get all processes with the given name
            process_list = mgmt.ExecQuery(
                "SELECT * from Win32_Process where Caption = '{ps_name}'".
                format(ps_name=ps_name))
            if process_list:
                # Get the process PID (if there are many, select the first one)
                pid = process_list[0].Properties_('ProcessId').Value
                try:
                    # Get the process
                    proc = win32api.OpenProcess(
                        win32con.PROCESS_QUERY_INFORMATION
                        | win32con.PROCESS_VM_READ, False, pid)
                    return proc

                except pywintypes.error as e:
                    if e.winerror == PARAM_INCORRECT_ERRNO:
                        return None
                    else:
                        raise
            pythoncom.CoUninitialize()
Exemplo n.º 7
0
    def initialize(self):
        pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)

        try:
            self.camera = win32com.client.Dispatch('CAMC4.Camera')
        except pywintypes.com_error, e:
            raise RuntimeError('failed to initialize interface CAMC4.Camera')
Exemplo n.º 8
0
    def __init__(self, voice=None, rate=SP_DEF_SETTING, vol=SP_DEF_SETTING):
        """
        Constructor for SPVoice
        @param voice: The voice description of the starting voice
        or None for the default voice
        @parm rate the reading speed an int
        pass SP_DEF_SETTING for the system default
        @param vol reading volume a non-negitve int
        ditto for the default
        """
        pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
        self.sp_voice = win32com.client.Dispatch('Sapi.SpVoice')

        # Build the voice_table now or we'll keep rebuilding it
        # every time we set the voice. We take a slight hit on
        # startup. However the overall performence gain is
        # more than worth the extra 1.2s of startup time
        self.voice_table = {}
        voice_licom = self.sp_voice.GetVoices()
        for i in range(voice_licom.Count):
            vt = voice_licom.Item(i)
            self.voice_table[vt.GetDescription()] = vt

        if rate != SP_DEF_SETTING:
            self.sp_voice.Rate = rate
        if voice is not None:
            self.sp_voice.Voice = self.voice_table[voice]
            # This will not catch an exception for an invalid voice
            # yet. TODO after beta
        if vol != SP_DEF_SETTING:
            self.sp_voice.Volume = vol
        ## comply with my interface
        self.purge = False
Exemplo n.º 9
0
 def __init__(self, readz):
     pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
     self.readz = readz
     self.acquired_points = []
     self.Vreal = []
     self.Vimag = []
     self.Vsig = []
     self.Vdc = []
     self.Ireal = []
     self.Iimag = []
     self.Isig = []
     self.Idc = []
     self.Zreal = []
     self.Zimag = []
     self.Zsig = []
     self.Zfreq = []
     self.Imod = []
     self.Iphz = []
     self.Vmod = []
     self.Vphz = []
     self.Zmod = []
     self.Zphz = []
     self.Gain = []
     self.VNoise = []
     self.INoise = []
     self.IENoise = []
     self.IERange = []
Exemplo n.º 10
0
    def run(self):
        try:
            pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
            #tts = DispatchWithEvents("SAPI.SpVoice.1", SpeechEvents)
            tts = Dispatch('SAPI.SpVoice')
        except:
            self.plugin.PrintError(self.plugin.text.errorCreate)
            return
        vcs = tts.GetVoices()
        voices = [(voice.GetDescription(), voice) for voice in vcs]
        tmp = [item[0] for item in voices]
        ix = tmp.index(self.voiceName) if self.voiceName in tmp else 0
        tts.Voice = voices[ix][1]

        devs = tts.GetAudioOutputs()
        devices = [(dev.GetDescription(), dev) for dev in devs]
        tmp = [item[0] for item in devices]
        ix = tmp.index(self.device) if self.device in tmp else 0
        tts.AudioOutput = devices[ix][1]

        tts.Rate = self.rate
        tts.Volume = self.volume
        tts.Speak(self.text, 0)
        suffix = self.plugin.text.suffix if self.suff == "" else "%s.%s" % (
            self.plugin.text.suffix, self.suff)
        self.plugin.TriggerEvent(suffix)
    def convert(self):
        try:
            # initialize COM for multi-threading, ignoring any errors
            # when someone else has already initialized differently.
            pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
        except pythoncom.com_error:
            pass

        word = Dispatch("Word.Application")
        word.Visible = 0
        word.DisplayAlerts = 0
        doc = word.Documents.Open(self.fullname)
        # Let's set up some html saving options for this document
        doc.WebOptions.RelyOnCSS = 1
        doc.WebOptions.OptimizeForBrowser = 1
        doc.WebOptions.BrowserLevel = 0  # constants.wdBrowserLevelV4
        doc.WebOptions.OrganizeInFolder = 0
        doc.WebOptions.UseLongFileNames = 1
        doc.WebOptions.RelyOnVML = 0
        doc.WebOptions.AllowPNG = 1
        # And then save the document into HTML
        doc.SaveAs(FileName="%s.htm" % (self.fullname),
                   FileFormat=8)  # constants.wdFormatHTML)

        # TODO -- Extract Metadata (author, title, keywords) so we
        # can populate the dublin core
        # Converter will need to be extended to return a dict of
        # possible MD fields

        doc.Close()
Exemplo n.º 12
0
    def Connect(self):
        #connect to TEMScripting wrapper
        self.Scope = win32com.client.Dispatch('TEMScripting.Instrument')
        pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
        if self.debug: print("Connected to microscope")

        #connect to TIA
        self.TIA = win32com.client.Dispatch("ESVision.Application")
        if self.debug: print("Connected to TIA")

        #get aliases
        self.Acq = self.Scope.Acquisition
        self.Proj = self.Scope.Projection
        self.Ill = self.Scope.Illumination
        self.Stage = self.Scope.Stage

        #Get the default state values
        self.ACQIMAGECORRECTION_DEFAULT = win32com.client.constants.AcqImageCorrection_Default
        self.ACQIMAGECORRECTION_UNPROCESSED = win32com.client.constants.AcqImageCorrection_Unprocessed

        self.ACQIMAGESIZE_FULL = win32com.client.constants.AcqImageSize_Full
        self.ACQIMAGESIZE_HALF = win32com.client.constants.AcqImageSize_Half
        self.ACQIMAGESIZE_QUARTER = win32com.client.constants.AcqImageSize_Quarter

        self.ACQIMAGEFILEFORMAT_TIFF = win32com.client.constants.AcqImageFileFormat_TIFF
        self.ACQIMAGEFILEFORMAT_JPG = win32com.client.constants.AcqImageFileFormat_JPG
        self.ACQIMAGEFILEFORMAT_PNG = win32com.client.constants.AcqImageFileFormat_PNG

        #get the mode, ensure set up
        mode = self.Scope.InstrumentModeControl.InstrumentMode
        if mode == 0: self.TEMMODE()
        if mode == 1: self.STEMMODE()
Exemplo n.º 13
0
            def initThread(self):
                # This must be called at the beginning of any thread that uses COM
                import pythoncom
                pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)

                # Invoke superclass's initThread.  This enables multiple plug-ins
                # to each have their own initThread get called.
                self.__class__.__bases__[0].initThread(self)
def get_tecnaiccd():
        if client_module.tecnaiccd is None:
                if com_module == 'win32com':
                        pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
                        client_module.tecnaiccd = client_module.dynamic.Dispatch('TecnaiCCD.GatanCamera.2')
                elif com_module == 'comtypes':
                        client_module.tecnaiccd = client_module.CreateObject('TecnaiCCD.GatanCamera.2')
        return client_module.tecnaiccd
Exemplo n.º 15
0
def getallworddocs():
    pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
    myWord = win32com.client.Dispatch('Word.Application')
    DOCS = []
    for i in range(1, myWord.Documents.Count + 1):
        WORDDOC = myWord.Documents.Item(i)
        DOCS.append(WORDDOC.Path + "\\" + WORDDOC.Name)
    return DOCS
Exemplo n.º 16
0
def gamry_error_decoder(e):
    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
    if isinstance(e, comtypes.COMError):
        hresult = 2**32+e.args[0]
        if hresult & 0x20000000:
            return GamryCOMError('0x{0:08x}: {1}'.format(2**32+e.args[0], e.args[1]))
    pythoncom.CoUninitialize() # Windows shit
    return e
Exemplo n.º 17
0
    def __init__( self ):
        pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
        try:
            self.word = win32com.client.Dispatch( "Word.Application" )
        except:
            Info("Cannot launch win32com.client.Dispatch(\"Word.Application\"), check if word and pywin32 module are correcty installed", 3)

        self.word.Visible = 0
Exemplo n.º 18
0
 def __init__(self, mode="Potentiostat", which_one=0):
     pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
     self.devices=client.CreateObject('GamryCOM.GamryDeviceList',clsctx=comtypes.CLSCTX_LOCAL_SERVER)
     # print self.devices.EnumSections()
     # Unfortunately it is necessary to sleep for 10 seconds after initializing the
     # device list.  Results with-out this sleep are somewhat unpredictable.
     time.sleep(10) # Another demonstration how immature this ugly interface is programmed
     self.pstat=client.CreateObject('GamryCOM.GamryPstat',clsctx=comtypes.CLSCTX_LOCAL_SERVER)
     self.pstat.Init(self.devices.EnumSections()[which_one]) # grab pstat selected
     time.sleep(10)
     self.pstat.Open()
     time.sleep(1)
     #self.pstat.SetCell(0) # 0=off 1=on
     #self.pstat.SetCell(GamryCOM.CellOff)
     #self.pstat.SetCtrlMode(1) # 0=Galvanostat (amp=const), 1=Potentiostat (volts=const), 2=Zero Resistance Ammeter 3=Frequency response analyser
     self.mode = mode
     if self.mode == "Potentiostat":
         self.pstat.SetCtrlMode(GamryCOM.PstatMode)
         print "Potentiostatic mode selected"
     elif self.mode == "Galvanostat":
         self.pstat.SetCtrlMode(GamryCOM.GstatMode)
         print "Galvanostatic mode selected"
     #self.pstat.SetStability(GamryCOM.StabilityFast) # 0=Fast 1=medfast 2=norm 3=slow
     #self.pstat.SetStability(2) # 0=Fast 1=medfast 2=norm 3=slow
     #self.pstat.SetCASpeed(GamryCOM.CASpeedMedFast) # use medfast ???
     self.pstat.SetSenseSpeedMode(1) # TRUE
     #self.pstat.SetConvention(1) # 0=cathodic 1=anodic
     self.pstat.SetGround(0) # 0=Float 1=Earth
     #self.pstat.SetIchRange(3.0)
     #self.pstat.SetIchRangeMode(0) # False
     #self.pstat.SetIchFilter(5.0)
     #self.pstat.SetVchRange(3.0)
     #self.pstat.SetVchRangeMode(0) # False
     #self.pstat.SetIchOffsetEnable(1) # True
     #self.pstat.SetVchOffsetEnable(1) # True
     #self.pstat.SetVchFilter(5.0)
     #self.pstat.SetAchRange(3.0)
     #self.pstat.SetIERangeLowerLimit() # NIL
     #self.pstat.SetIERange(0.03)
     #self.pstat.SetIERangeMode(0) # False
     #self.pstat.SetAnalogOut(0.0)
     #self.pstat.SetVoltage(0.0) # DCvoltage
     #self.pstat.SetPosFeedEnable(0) # False
     time.sleep(1)
     self.pstat.SetCell(GamryCOM.CellOn)
     time.sleep(1)
     self.readz=client.CreateObject('GamryCOM.GamryReadZ',clsctx=comtypes.CLSCTX_LOCAL_SERVER)
     self.readz.Init(self.pstat)
     self.readzsink = GamryReadZEvents(self.readz)
     self.connection = client.GetEvents(self.readz, self.readzsink)
     self.frequency_values = []
     self.wait_time_after_each_measurement = 5
     self.cycle_max = 10
     self.interrupt = False # Variable which makes it possible to stop a running measurement
     #self.setup_impedance_measurement()
     pythoncom.CoUninitialize() # Windows shit
     return
Exemplo n.º 19
0
 def close(self):
     self.interrupt = True
     time.sleep(7)
     self.pstat.SetCell(GamryCOM.CellOff)
     pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
     del self.connection
     self.pstat.Close()
     pythoncom.CoUninitialize() # Windows shit
     return
 def __init__(self):
         robotserver.RobotServer.__init__(self)
         if pythoncom is None:
                 self.communication = FakeCommunication()
         else:
                 pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
                 self.communication = win32com.client.Dispatch('RobotCommunications.Signal')
         initialstatus = [(attr,None) for attr in robotattrs]
         self.status = dict(initialstatus)
Exemplo n.º 21
0
def get_kompas_api5():
    module = gencache.EnsureModule("{0422828C-F174-495E-AC5D-D31014DBBE87}", 0,
                                   1, 0)  # import KompasAPI5 module
    pythoncom.CoInitializeEx(0)  # necessary for pythoncom in django !!!
    api = module.KompasObject(
        Dispatch("Kompas.Application.5")._oleobj_.QueryInterface(
            module.KompasObject.CLSID, pythoncom.IID_IDispatch))
    const = gencache.EnsureModule("{2CAF168C-7961-4B90-9DA2-701419BEEFE3}", 0,
                                  1, 0).constants  # import Kompas 3D constants
    return module, api, const
Exemplo n.º 22
0
 def ffms_init():
     if not getattr(pythoncom, "_initialized", False):
         try:
             pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
         except pythoncom.error:
             pass
         else:
             pythoncom._initialized = True
             atexit.register(ffms_uninit)
     FFMS_Init(0, USE_UTF8_PATHS)
Exemplo n.º 23
0
 def about_program(self):
     pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
     myWord = win32com.client.DispatchEx('Word.Application')
     print(os.getcwd())
     script_dir = os.path.dirname(os.path.realpath('__file__'))
     rel_path = 'Help_File.docx'
     abs_file_path = os.path.join(script_dir, rel_path)
     print(abs_file_path)
     #wordfile = r"C:\Users\joy\Documents\Python Scripts\Twitter\Help_File.docx"
     myDoc = myWord.Documents.Open(abs_file_path, False, False, True)
Exemplo n.º 24
0
    def __init__(self):
        if Debug == True:
            print 'from CM class'

        tem.TEM.__init__(self)
        self.correctedstage = True
        pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
        self.CMLIB = cmlib.CMLIB()

        self.magnifications = []
        self.mainscreenscale = 44000.0 / 50000.0
Exemplo n.º 25
0
    def __init__( self, worksheet_name, cell_location):
        pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
        self.worksheet_name = worksheet_name
        self.cell_location = cell_location

        try:
            self.excel = win32com.client.Dispatch("Excel.Application")
        except:
            Info("Cannot launch win32com.client.Dispatch(\"Excel.Application\"), check if word and pywin32 module are correcty installed", 3)
        self.excel.Visible = 0
        self.excel.DisplayAlerts = 0
Exemplo n.º 26
0
def saveword(File=None):
    pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
    #myWord = win32com.client.DispatchEx('Word.Application')
    myWord = win32com.client.Dispatch('Word.Application')
    myWord.Visible = True
    #from pyPdf import PdfFileWriter, PdfFileReader
    #import shutil

    #scan = PdfFileReader(file())
    #doc = PdfFileReader(file())
    #page1 = scan.getPage(0)
    #output = PdfFileWriter()

    #odczytanie otwartego dokumentu worda:
    if File == "":
        File = None
    if not File == None:
        WORDDOC = myWord.Documents.Open(File)
    else:
        WORDDOC = myWord.Documents.Item(1)
    NAME = WORDDOC.Name
    PATH = WORDDOC.Path
    PDF_NAME = PATH + "\\" + NAME[:NAME.rindex(".")] + ".pdf"
    PDF_NAME_2 = PATH + "\\2_" + NAME[:NAME.rindex(".")] + ".pdf"
    PDF_NAME_1 = PATH + "\\1_" + NAME[:NAME.rindex(".")] + ".pdf"
    #print PDF_NAME
    #raw_input()
    MESSAGE = ""
    if not check_write(os.path.dirname(PDF_NAME)):
        MESSAGE = "Katalog tylko do odczytu"
        print MESSAGE
        return False, MESSAGE
    elif not os.path.isfile(PDF_NAME):
        print("zapisanie jako pdf...")
        WORDDOC.ExportAsFixedFormat(OutputFileName=PDF_NAME,
                                    ExportFormat=17,
                                    OpenAfterExport=False,
                                    OptimizeFor=0,
                                    Range=0,
                                    From=1,
                                    To=1,
                                    Item=0,
                                    IncludeDocProps=True,
                                    KeepIRM=True,
                                    CreateBookmarks=0,
                                    DocStructureTags=True,
                                    BitmapMissingFonts=True,
                                    UseISO19005_1=False)
        return True, PDF_NAME
    else:
        MESSAGE = "plik pdf juz istnieje!"
        print(MESSAGE)
        return False, MESSAGE
Exemplo n.º 27
0
def excel(excelfile, psfile, printer):
    pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
    myExcel = win32com.client.DispatchEx('Excel.Application')
    myExcel.Application.AskToUpdateLinks = 0
    Excel = myExcel.Workbooks.Open(excelfile, 0, False, 2)
    Excel.Saved = 1
    Excel.PrintOut(1, 5000, 1, False, printer, True, False, psfile)
    Excel.Close()
    myExcel.Quit()
    del myExcel
    del Excel
    pythoncom.CoUninitialize()
Exemplo n.º 28
0
    def run(self):
        Pref.running = True

        try:
            pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
        except pythoncom.com_error:
            pass

        self.view.set_status('SasIOM', "%s" % ('SasIOM:///RUNNING'))
        Pref.objSAS.LanguageService.Submit(Pref.program)

        sublime.set_timeout(lambda: self.on_done(), 0)
Exemplo n.º 29
0
 def perform_impedance_measurement(self, start_frequency, end_frequency, amplitude, num_points_per_decade=10):
     # Filter out line frequency 50Hz 100Hz and 200Hz afterwards
     frequency_values_generated = np.logspace(int(np.log10(start_frequency)),int(np.log10(end_frequency)),int(num_points_per_decade)*int(np.log10(end_frequency/start_frequency)))     
     frequency_values_without_50Hz = [float(i+4.5) if np.absolute(i-50)<1.0 else i for i in frequency_values_generated]
     frequency_values_without_100Hz = [float(i+2.5) if np.absolute(i-100)<1.0 else i for i in frequency_values_without_50Hz]
     frequency_values_without_200Hz = [float(i+1.5) if np.absolute(i-200)<0.8 else i for i in frequency_values_without_100Hz]
     self.frequency_values = frequency_values_without_200Hz
     pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
     for single_frequency in self.frequency_values:
         if not self.interrupt:
             self.perform_single_measurement(single_frequency,amplitude)
     pythoncom.CoUninitialize() # Windows shit
     return
Exemplo n.º 30
0
def get_kompas_api7():
    module = gencache.EnsureModule("{69AC2981-37C0-4379-84FD-5DD2F3C0A520}", 0,
                                   1, 0)  # import KompasAPI7 module
    print("2.1")
    pythoncom.CoInitializeEx(0)  # necessary for pythoncom in django !!!
    api = module.IKompasAPIObject(
        Dispatch("Kompas.Application.7")._oleobj_.QueryInterface(
            module.IKompasAPIObject.CLSID, pythoncom.IID_IDispatch))
    print("2.2")
    const = gencache.EnsureModule("{75C9F5D0-B5B8-4526-8681-9903C567D2ED}", 0,
                                  1, 0).constants  # import Kompas constants
    print("2.3")
    return module, api, const