Example #1
0
 def __init__(self, pi_server='UPPICOLL'):
     try:
         self.pi_srv = Dispatch('PISDK.PISDK').Servers(pi_server)
         self.pi_timeformat = Dispatch('PITimeServer.PITimeFormat')
         print('PI Server set to', pi_server)
     except:
         raise
Example #2
0
def getCollection():
    """Returns an XSICollection object."""

    newCollection = Dispatch("XSI.Collection")
    newCollection.Unique = True

    return newCollection
Example #3
0
def rm_rubric(pdffile):
    '''remove the pages associated with the rubric stored in the pdf

    '''
    # if there is a rubric it is stored here
    rubricfile = get_info(pdffile, 'rubric')
    #print rubricfile, os.path.exists(rubricfile)
    if rubricfile == '':
        # no rubric stored.
        print 'no rubric found'
        return True

    # get number of pages in pdffile
    pddoc1 = pddoc
    pddoc1.Open(os.path.abspath(pdffile))
    N1 = pddoc1.GetNumPages()

    pddoc2 = Dispatch("AcroExch.PDDoc")
    pddoc2.Open(os.path.abspath(rubricfile))
    N2 = pddoc2.GetNumPages()

    #print N1, N2
    pddoc1.DeletePages(N1 - N2, N1 - 1)
    set_info(pdffile, 'rubric', '')
    pddoc1.Save(1, os.path.abspath(pdffile))
    pddoc1.Close()
    pddoc2.Close()
    return True
Example #4
0
def getCollection():
    """Returns an XSICollection object."""

    newCollection = Dispatch("XSI.Collection")
    newCollection.Unique = True

    return newCollection
Example #5
0
        def test_win32com_dyndispatch(self):
            # dynamic Dispatch is case-IN-sensitive
            from win32com.client.dynamic import Dispatch
            d = Dispatch("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')")

            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))

            server_id = d.eval("id(self)")
            self.assertEqual(d.id, server_id)
            self.assertEqual(d.ID, server_id)

            self.assertEqual(d.Name, "spam, spam, spam")
            self.assertEqual(d.nAME, "spam, spam, spam")

            d.SetName("foo bar")
            self.assertEqual(d.Name, "foo bar")
Example #6
0
def add_rubric(pdffile, rubricfile, force=False):
    src1 = os.path.abspath(pdffile)
    src2 = os.path.abspath(rubricfile)

    # We do not want to add rubrics more than once
    if get_info(src1, 'rubric') == rubricfile and not force:
        return True

    pddoc1 = pddoc
    pddoc2 = Dispatch("AcroExch.PDDoc")

    pddoc1.Open(src1)
    N1 = pddoc1.GetNumPages()

    pddoc2.Open(src2)
    N2 = pddoc2.GetNumPages()

    # Insert rubric after last page of the other doc. pages start at 0
    pddoc1.InsertPages(N1 - 1, pddoc2, 0, N2, 0)
    pddoc1.Save(1, src1)
    pddoc1.Close()
    pddoc2.Close()

    # store rubric so we know it is added
    set_info(pdffile, 'rubric', src2)
    return True
def tt():
    # import os
    import winerror
    from win32com.client.dynamic import Dispatch, ERRORS_BAD_CONTEXT

    ERRORS_BAD_CONTEXT.append(winerror.E_NOTIMPL)

    my_dir = r"D:\AllDowns"
    my_pdf = "gpgp.pdf"

    os.chdir(my_dir)
    src = os.path.abspath(my_pdf)

    try:
        AvDoc = Dispatch("AcroExch.AVDoc")

        if AvDoc.Open(src, ""):
            pdDoc = AvDoc.GetPDDoc()
            jsObject = pdDoc.GetJSObject()
            jsObject.SaveAs(os.path.join(my_dir, 'output_example.jpeg'),
                            "com.adobe.acrobat.jpeg")

    except Exception as e:
        print(str(e))

    finally:
        AvDoc.Close(True)

        jsObject = None
        pdDoc = None
        AvDoc = None
Example #8
0
def doTestEngine(engine, echoer):
    # Now call into the scripts IDispatch
    from win32com.client.dynamic import Dispatch
    ob = Dispatch(engine.GetScriptDispatch())
    try:
        ob.hello("Goober")
    except pythoncom.com_error, exc:
        print "***** Calling 'hello' failed", exc
        return
Example #9
0
File: api.py Project: stnoah1/mcb
 def regenerate(self, mdl):
     try:
         self.session.SetConfigOption("regen_failure_handling",
                                      "resolve_mode")
         instrs = Dispatch('pfcls.pfcRegenInstructions')
         regen_instructions = instrs.Create(False, True, None)
         mdl.Regenerate(regen_instructions)
     except Exception:
         raise CreoWrapperError("Model failed to regenerate")
Example #10
0
def doTestEngine(engine, echoer):    
  # Now call into the scripts IDispatch
  from win32com.client.dynamic import Dispatch
  ob = Dispatch(engine.GetScriptDispatch())
  try:
    ob.hello("Goober")
  except pythoncom.com_error, exc:
    print "***** Calling 'hello' failed", exc
    return
Example #11
0
 def _TestEngine(self, engineName, code, expected_exc = None):
   echoer = Test()
   model = {
     'test' : util.wrap(echoer),
     }
   site = MySite(model)
   engine = site._AddEngine(engineName)
   try:
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
     engine.AddCode(code)
     engine.Start()
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED)
     self.failUnless(not echoer.fail_called, "Fail should not have been called")
     # Now call into the scripts IDispatch
     ob = Dispatch(engine.GetScriptDispatch())
     try:
       ob.hello("Goober")
       self.failUnless(expected_exc is None,
                       "Expected %r, but no exception seen" % (expected_exc,))
     except pythoncom.com_error:
       if expected_exc is None:
         self.fail("Unexpected failure from script code: %s" % (site.exception_seen,))
       if expected_exc not in site.exception_seen[2]:
         self.fail("Could not find %r in %r" % (expected_exc, site.exception_seen[2]))
       return
     self.assertEqual(echoer.last, "Goober")
 
     self.assertEqual(str(ob.prop), "Property Value")
     ob.testcollection()
     self.failUnless(not echoer.fail_called, "Fail should not have been called")
 
     # Now make sure my engines can evaluate stuff.
     result = engine.eParse.ParseScriptText("1+1", None, None, None, 0, 0, axscript.SCRIPTTEXT_ISEXPRESSION)
     self.assertEqual(result, 2)
     # re-initialize to make sure it transitions back to initialized again.
     engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
     engine.Start()
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED)
     
     # Transition back to initialized, then through connected too.
     engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
     engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED)
     engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
   
     engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED)
     engine.SetScriptState(axscript.SCRIPTSTATE_DISCONNECTED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_DISCONNECTED)
   finally:
     engine.Close()
     engine = None
     site = None
Example #12
0
    def __enter__(self):
        self.init_win32com()
        print("Trying to form connection")
        self.models = []
        self.asyncconn = Dispatch('pfcls.pfcAsyncConnection')
        self.conn = self.asyncconn.Connect(None, None, None, None)
        self.session = self.conn.Session
        print("Connection formed")

        return self
Example #13
0
 def _TestEngine(self, engineName, code, bShouldWork = 1):
   echoer = Test()
   model = {
     'test' : util.wrap(echoer),
     }
   try:
     try:
       site = MySite(model)
       engine = site._AddEngine(engineName)
       _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
       engine.AddCode(code)
       engine.Start()
       _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED)
     finally:
       if bShouldWork:
         self.failUnless(not site.seen_exception, "Script site should not have seen an exception")
       else:
         self.failUnless(site.seen_exception, "Script site should have seen an exception")
     self.failUnless(not echoer.fail_called, "Fail should not have been called")
     # Now call into the scripts IDispatch
     from win32com.client.dynamic import Dispatch
     ob = Dispatch(engine.GetScriptDispatch())
     ob.hello("Goober")
     self.assertEqual(echoer.last, "Goober")
 
     self.assertEqual(str(ob.prop), "Property Value")
     ob.testcollection()
     self.failUnless(not echoer.fail_called, "Fail should not have been called")
 
     # Now make sure my engines can evaluate stuff.
     result = engine.eParse.ParseScriptText("1+1", None, None, None, 0, 0, axscript.SCRIPTTEXT_ISEXPRESSION)
     self.assertEqual(result, 2)
     # re-initialize to make sure it transitions back to initialized again.
     engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
     engine.Start()
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED)
     
     # Transition back to initialized, then through connected too.
     engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
     engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED)
     engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
   
     engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED)
     engine.SetScriptState(axscript.SCRIPTSTATE_DISCONNECTED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_DISCONNECTED)
   finally:
     engine.Close()
     engine = None
     site = None
Example #14
0
class AVDoc:

    def __init__(self, file, pddoc=None):
        if pddoc is None:
            self.avdoc = Dispatch("AcroExch.AVDoc")
        else:
            self.avdoc = pddoc
        self.file = file

    # Open
    # Opens a file. A new instance of AcroExch.AVDoc must be created for each displayed PDF file.
    #
    # Note:An application must explicitly close any AVDoc that it opens by calling AVDoc.Close (the destructor for the
    # AcroExch.AVDoc class does not call AVDoc.Close).
    #
    # Syntax
    # VARIANT_BOOL Open(BSTR szFullPath, BSTR szTempTitle);
    #
    # Parameters
    # szFullPath
    #
    # The full path of the file to open.
    #
    # szTempTitle
    #
    # An optional title for the window in which the file is opened. If szTempTitle is NULL or the empty string,
    # it is ignored. Otherwise, szTempTitle is used as the window title.
    #
    # Returns
    # -1 if the file was opened successfully, 0 otherwise.
    def open(self, temp_title=""):
        return self.avdoc.Open(self.file, temp_title)

    # Close
    # Closes a document. You can close all open AVDoc objects by calling App.CloseAllDocs.
    #
    # To reuse an AVDoc object, close it with AVDoc.Close, then use the AVDoc object’s LPDISPATCH for
    # AVDoc.OpenInWindow.
    #
    # Syntax
    # VARIANT_BOOL Close(long bNoSave);
    #
    # Parameters
    # bNoSave
    #
    # If a positive number, the document is closed without saving it. If 0 and the document has been modified,
    # the user is asked whether or not the file should be saved.
    #
    # Returns
    # Always returns -1, even if no document is open.
    def close_doc(self, no_save=0):
        return self.avdoc.Close(no_save)
Example #15
0
File: api.py Project: stnoah1/mcb
    def set_parameter(self, mdl, param_name, value):
        param = self.get_param_obj(mdl, param_name)

        modelitem = Dispatch('pfcls.MpfcModelItem')
        # create boolean if param is not float
        if isinstance(value, bool):
            val = modelitem.CreateBoolParamValue(value)
        elif isinstance(value, (float, int)):
            val = modelitem.CreateDoubleParamValue(value)
        else:
            raise CreoWrapperError("Invalid value type")

        param.SetScaledValue(val, None)
Example #16
0
class OOoComPreviewer(ooutils.OOoImagePreviewer):
    def __init__(self):
        super(OOoComPreviewer, self).__init__()
        self.service_man = Dispatch('com.sun.star.ServiceManager')
        self.service_man._FlagAsMethod("Bridge_GetStruct")
        self.desktop = self.service_man.CreateInstance(
            'com.sun.star.frame.Desktop')

    def make_prop(self, name, value):
        prop = self.service_man.Bridge_GetStruct(
            'com.sun.star.beans.PropertyValue')
        prop.Name = name
        prop.Value = value
        return prop
Example #17
0
File: api.py Project: stnoah1/mcb
 def __init__(self, creo_exe_path, no_graphic_op=True, no_input_op=True):
     pythoncom.CoInitialize()
     self.model = None
     self.models = []
     self.creo_exe_path = creo_exe_path
     self.no_graphic_op = ' -g:no_graphics' if no_graphic_op else ''
     self.no_input_op = ' -i:rpc_input' if no_input_op else ''
     print("Trying to form connection")
     self.asyncconn = Dispatch('pfcls.pfcAsyncConnection')
     print("Asyncconn worked")
     self.conn = self.asyncconn.Start(
         f"{self.creo_exe_path}{self.no_graphic_op}{self.no_input_op}", ".")
     print("Connection formed")
     self.session = self.conn.Session
     print("Session started")
     self.session.SetConfigOption("mass_property_calculate", "automatic")
     print("Connection formed")
Example #18
0
 def run(self):  # runnable for doing the work
     pythoncom.CoInitialize()  # needed for doing CO objects in threads
     self.connected = 0  # set connection flag for stick itself
     self.counter = 0
     while True:  # main loop for stick thread
         self.signalWeatherConnected.emit(
             self.connected)  # send status to GUI
         if self.connected == 1:  # differentiate between dome connected or not
             if self.counter == 0:  # jobs once done at the beginning
                 self.getStatusOnce()  # task once
             if self.counter % 2 == 0:  # all tasks with 200 ms
                 self.getStatusFast()  # polling the mount status Ginfo
             if self.counter % 20 == 0:  # all tasks with 3 s
                 self.getStatusMedium()  # polling the mount
             if self.counter % 300 == 0:  # all task with 1 minute
                 self.getStatusSlow()  # slow ones
             self.counter += 1  # increasing counter for selection
             time.sleep(.1)
         else:
             try:
                 if self.driverName == '':
                     self.connected = 2
                 else:
                     self.ascom = Dispatch(self.driverName)  # load driver
                     self.ascom.connected = True
                     self.connected = 1  # set status to connected
                     self.logger.debug(
                         'run            -> driver chosen:{0}'.format(
                             self.driverName))
             except Exception as e:  # if general exception
                 if self.driverName != '':
                     self.logger.error(
                         'run Weather    -> general exception: {0}'.format(
                             e))  # write to logger
                 if self.driverName == '':
                     self.connected = 2
                 else:
                     self.connected = 0  # run the driver setup dialog
             finally:  # still continua and try it again
                 pass  # needed for continue
             time.sleep(1)  # wait for the next cycle
     self.ascom.Quit()
     pythoncom.CoUninitialize()  # needed for doing COm objects in threads
     self.terminate()  # closing the thread at the end
Example #19
0
 def test():
     project = Dispatch("Mga.MgaProject")
     project.Open("MGA=" + "CyPhyML.mga")
     import sys
     sys.stdin.readline()
     metaint = Dispatch("MGA.Interpreter.MetaInterpreter")
     metaint.InvokeEx(project, None, Dispatch("Mga.MgaFCOs"), 128)
     exit(1)
Example #20
0
    def set_parameter(self, mdl, param_name, value):
        param = mdl.GetParam(param_name)

        try:
            paramvalue = param.value
        except AttributeError:
            raise CreoWrapperError("Parameter {} not found".format(param_name))


        modelitem = Dispatch('pfcls.MpfcModelItem')
        #create boolean if param is not float
        if isinstance(value, bool):
            val = modelitem.CreateBoolParamValue(value)
        elif isinstance(value, (float, int)):
            val = modelitem.CreateDoubleParamValue(value)
        else:
            raise CreoWrapperError("Invalid value type")

        param.SetScaledValue(val, None)
Example #21
0
 def _excel_dispatch(self):
     """
     A private method that launches Excel.
     This keeps a counter of the number of ExcelSpreadsheet objects
     that are running.
     """
     if ExcelSpreadsheet_win32com._excel_app_ctr == 0:
         ExcelSpreadsheet_win32com._excel_app_ptr = Dispatch(
             'Excel.Application')
     ExcelSpreadsheet_win32com._excel_app_ctr += 1
     return ExcelSpreadsheet_win32com._excel_app_ptr
Example #22
0
def doTestEngine(engine, echoer):    
  # Now call into the scripts IDispatch
  from win32com.client.dynamic import Dispatch
  ob = Dispatch(engine.GetScriptDispatch())
  try:
    ob.hello("Goober")
  except pythoncom.com_error as exc:
    print("***** Calling 'hello' failed", exc)
    return
  if echoer.last != "Goober":
    print("***** Function call didnt set value correctly", repr(echoer.last))
    
  if str(ob.prop) != "Property Value":
    print("***** Property Value not correct - ", repr(ob.prop))

  ob.testcollection()

  # Now make sure my engines can evaluate stuff.
  result = engine.eParse.ParseScriptText("1+1", None, None, None, 0, 0, axscript.SCRIPTTEXT_ISEXPRESSION)
  if result != 2:
    print("Engine could not evaluate '1+1' - said the result was", result)
Example #23
0
 def setupDriver(self):
     try:
         self.chooser = Dispatch('ASCOM.Utilities.Chooser')
         self.chooser.DeviceType = 'Telescope'
         self.driverName = self.chooser.Choose(self.driverName)
         self.logger.debug('setupDriverMoun-> driver chosen:{0}'.format(
             self.driverName))
         if self.driverName == 'ASCOM.FrejvallGM.Telescope':
             self.driver_real = True
         else:
             self.driver_real = False
         self.connected = False  # run the driver setup dialog
     except Exception as e:  # general exception
         self.app.messageQueue.put(
             'Driver Exception in setupMount')  # write to gui
         self.logger.error(
             'setupDriver Mount -> general exception:{0}'.format(
                 e))  # write to log
         self.connected = False  # set to disconnected
     finally:  # won't stop the program, continue
         return
Example #24
0
def update_core(upstream_rev):
    subprocess.check_call('git checkout {} CyPhyML-core.xme'.format(upstream_rev), shell=True)
    project = Dispatch("Mga.MgaProject")
    project.Create("MGA=" + "CyPhyML-core.mga", "MetaGME")
    import_xme(project, "CyPhyML-core.xme")


    do_mods(project, core_mods)

    project.Save()

    dumper = Dispatch("Mga.MgaDumper")
    dumper.DumpProject(project, "CyPhyML-core.xme")
    project.Close(True)
Example #25
0
 def setupDriver(self):  #
     try:
         self.chooser = Dispatch('ASCOM.Utilities.Chooser')
         self.chooser.DeviceType = 'Dome'
         self.driverName = self.chooser.Choose(self.driverName)
         self.logger.debug('setupDriverDome -> driver chosen:{0}'.format(
             self.driverName))
         if self.driverName == '':
             self.connected = 2
         else:
             self.connected = 0  # run the driver setup dialog
     except Exception as e:  # general exception
         self.app.messageQueue.put(
             'Driver Exception in setupDome')  # write to gui
         self.logger.error(
             'setupDriverDome -> general exception:{0}'.format(
                 e))  # write to log
         if self.driverName == '':
             self.connected = 2
         else:
             self.connected = 0  # run the driver setup dialog
     finally:  # continue to work
         pass  # python necessary
Example #26
0
 def _TestEngine(self, engineName, code, expected_exc = None):
   echoer = Test()
   model = {
     'test.py' : util.wrap(echoer),
     }
   site = MySite(model)
   engine = site._AddEngine(engineName)
   try:
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
     engine.AddCode(code)
     engine.Start()
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED)
     self.failUnless(not echoer.fail_called, "Fail should not have been called")
     # Now call into the scripts IDispatch
     ob = Dispatch(engine.GetScriptDispatch())
     try:
       ob.hello("Goober")
       self.failUnless(expected_exc is None,
                       "Expected %r, but no exception seen" % (expected_exc,))
     except pythoncom.com_error:
       if expected_exc is None:
         self.fail("Unexpected failure from script code: %s" % (site.exception_seen,))
       if expected_exc not in site.exception_seen[2]:
         self.fail("Could not find %r in %r" % (expected_exc, site.exception_seen[2]))
       return
     self.assertEqual(echoer.last, "Goober")
 
     self.assertEqual(str(ob.prop), "Property Value")
     ob.testcollection()
     self.failUnless(not echoer.fail_called, "Fail should not have been called")
 
     # Now make sure my engines can evaluate stuff.
     result = engine.eParse.ParseScriptText("1+1", None, None, None, 0, 0, axscript.SCRIPTTEXT_ISEXPRESSION)
     self.assertEqual(result, 2)
     # re-initialize to make sure it transitions back to initialized again.
     engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
     engine.Start()
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_STARTED)
     
     # Transition back to initialized, then through connected too.
     engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
     engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED)
     engine.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_INITIALIZED)
   
     engine.SetScriptState(axscript.SCRIPTSTATE_CONNECTED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_CONNECTED)
     engine.SetScriptState(axscript.SCRIPTSTATE_DISCONNECTED)
     _CheckEngineState(site, engineName, axscript.SCRIPTSTATE_DISCONNECTED)
   finally:
     engine.Close()
     engine = None
     site = None
Example #27
0
    def open_file(self, path):
        options = Dispatch('pfcls.pfcRetrieveModelOptions')
        o = options.Create()
        file = Dispatch('pfcls.pfcModelDescriptor')

        # VBAPI fails if it is given a creo file with the version number appended
        path = re.sub(r"\.prt(\.[0-9]+)", ".prt", path)

        f = file.CreateFromFilename(path)
        self.models.append(self.session.RetrieveModelWithOpts(f, o))
        self.session.OpenFile(f)
Example #28
0
def connect_to_PIserver_by_SDK():
    PL = Dispatch("PISDK.PISDK")
    print("PISDK Version:", PL.PISDKVersion)
    print("Known Server List")
    print("-----------------")

    for server in PL.Servers:
        if server.Name == PL.Servers.DefaultServer.Name:
            print("{0}\t:: DEFAULT::".format(server.Name))
        else:
            print(server.Name)
        tag = server.PIPoints("sinusoid")
        # or tag = server.PIPoints.Item("sinusoid")
        print("\t", tag.PointAttributes("tag").Value)
        print("\t", tag.Data.Snapshot.Value)
        timestamp = time.localtime(tag.Data.Snapshot.TimeStamp.UTCseconds)
        print("\t", time.asctime(timestamp))
Example #29
0
File: api.py Project: stnoah1/mcb
    def open_file(self, path):
        options = Dispatch('pfcls.pfcRetrieveModelOptions')
        o = options.Create()
        file = Dispatch('pfcls.pfcModelDescriptor')

        # VBAPI fails if it is given a creo file with the version number appended
        path = re.sub(r"\.prt(\.[0-9]+)", ".prt", path)

        f = file.CreateFromFilename(path)
        self.model = self.session.RetrieveModelWithOpts(f, o)
        self.models.append(self.model)
        self.session.SetConfigOption("regen_failure_handling",
                                     "no_resolve_mode")
        self.session.OpenFile(f)
        return self.model
Example #30
0
 def server_connection(self):
     """
     Allows the connection to the PIserver using PI SDK via pywin32.
     :param server_name: The name of the PIserver
     :return: server object
     """
     pl = Dispatch("PISDK.PISDK")
     # Find the wished server in the list of registered servers:
     registered_servers = list()
     for server in pl.Servers:
         if self.server_name == "default":
             if server.Name == pl.Servers.DefaultServer.Name:
                 # print("{0}\t:: Connected ::".format(server.Name))
                 return server
         else:
             if server.Name == self.server_name:
                 # print("{0}\t:: Connected ::".format(server.Name))
                 return server
         registered_servers.append(server.Name)
     print("No existe servidor registrado con el nombre: {0} \n"
           "Los servidores registrados son: {1}".format(
               self.server_name, registered_servers))
     return None
Example #31
0
    def loadCoreClient(self):
        """Loads the Fabric Engine Core Client"""

        if self.client == None:
            Profiler.getInstance().push("loadCoreClient")

            try:
                imp.find_module('cmds')
                host = 'Maya'
            except ImportError:
                try:
                    imp.find_module('sipyutils')
                    host = 'Softimage'
                except ImportError:
                    host = 'Python'

            if host == "Python":
                self.client = FabricEngine.Core.createClient()

            elif host == "Maya":
                contextID = cmds.fabricSplice('getClientContextID')
                if contextID == '':
                    cmds.fabricSplice('constructClient')
                    contextID = cmds.fabricSplice('getClientContextID')

                # Pull out the Splice client.
                self.client = FabricEngine.Core.createClient({"contextID": contextID})

            elif host == "Softimage":
                from win32com.client.dynamic import Dispatch
                si = Dispatch("XSI.Application").Application
                contextID = si.fabricSplice('getClientContextID')
                if contextID == '':
                    si.fabricSplice('constructClient')
                    contextID = si.fabricSplice('getClientContextID')

                # Pull out the Splice client.
                self.client = FabricEngine.Core.createClient({"contextID": contextID})

            self.loadExtension('Math')

            # krakenDir = os.environ['KRAKEN_PATH']
            # self.client.DFG.host.addPresetDir('', 'Kraken', os.path.join(krakenDir, 'CanvasPresets'))

            Profiler.getInstance().pop()
Example #32
0
def doTestEngine(engine, echoer):
    # Now call into the scripts IDispatch
    from win32com.client.dynamic import Dispatch
    ob = Dispatch(engine.GetScriptDispatch())
    try:
        ob.hello("Goober")
    except pythoncom.com_error as exc:
        print("***** Calling 'hello' failed", exc)
        return
    if echoer.last != "Goober":
        print("***** Function call didnt set value correctly", repr(echoer.last))

    if str(ob.prop) != "Property Value":
        print("***** Property Value not correct - ", repr(ob.prop))

    ob.testcollection()

    # Now make sure my engines can evaluate stuff.
    result = engine.eParse.ParseScriptText("1+1", None, None, None, 0, 0, axscript.SCRIPTTEXT_ISEXPRESSION)
    if result != 2:
        print("Engine could not evaluate '1+1' - said the result was", result)
Example #33
0
class Dome(QtCore.QThread):
    # signals for communication to main Thread / GUI
    logger = logging.getLogger(__name__)
    signalDomeConnected = QtCore.pyqtSignal([int], name='domeConnected')
    signalDomPointer = QtCore.pyqtSignal([float], name='domePointer')

    def __init__(self, app):
        super().__init__()
        self.app = app
        self.connected = 2
        self.ascom = None  # placeholder for ascom driver object
        self.chooser = None  # placeholder for ascom chooser object
        self.driverName = ''  # driver object name
        self.slewing = False
        self.counter = 0

    def run(self):  # runnable for doing the work
        pythoncom.CoInitialize()  # needed for doing CO objects in threads
        self.connected = 0  # set connection flag for stick itself
        self.counter = 0
        while True:  # main loop for stick thread
            self.signalDomeConnected.emit(self.connected)  # send status to GUI
            if self.connected == 1:  # differentiate between dome connected or not
                if self.counter == 0:  # jobs once done at the beginning
                    self.getStatusOnce()  # task once
                if self.counter % 2 == 0:  # all tasks with 200 ms
                    self.getStatusFast()  # polling the mount status Ginfo
                if self.counter % 20 == 0:  # all tasks with 3 s
                    self.getStatusMedium()  # polling the mount
                if self.counter % 300 == 0:  # all task with 1 minute
                    self.getStatusSlow()  # slow ones
                self.counter += 1  # increasing counter for selection
                time.sleep(.1)
            else:
                try:
                    if self.driverName == '':
                        self.connected = 2
                    else:
                        self.ascom = Dispatch(self.driverName)  # load driver
                        self.ascom.connected = True
                        self.connected = 1  # set status to connected
                        self.logger.debug(
                            'run            -> driver chosen:{0}'.format(
                                self.driverName))
                except Exception as e:  # if general exception
                    if self.driverName != '':
                        self.logger.error(
                            'run Dome       -> general exception: {0}'.format(
                                e))  # write to logger
                    if self.driverName == '':
                        self.connected = 2
                    else:
                        self.connected = 0  # run the driver setup dialog
                finally:  # still continua and try it again
                    pass  # needed for continue
                time.sleep(1)  # wait for the next cycle
        self.ascom.Quit()
        pythoncom.CoUninitialize()  # needed for doing COm objects in threads
        self.terminate()  # closing the thread at the end

    def __del__(self):  # remove thread
        self.wait()  #

    def getStatusFast(self):
        self.slewing = self.ascom.Slewing
        self.signalDomPointer.emit(self.ascom.Azimuth)

    def getStatusMedium(self):
        pass

    def getStatusSlow(self):
        pass

    def getStatusOnce(self):
        pass

    def setupDriver(self):  #
        try:
            self.chooser = Dispatch('ASCOM.Utilities.Chooser')
            self.chooser.DeviceType = 'Dome'
            self.driverName = self.chooser.Choose(self.driverName)
            self.logger.debug('setupDriverDome -> driver chosen:{0}'.format(
                self.driverName))
            if self.driverName == '':
                self.connected = 2
            else:
                self.connected = 0  # run the driver setup dialog
        except Exception as e:  # general exception
            self.app.messageQueue.put(
                'Driver Exception in setupDome')  # write to gui
            self.logger.error(
                'setupDriverDome -> general exception:{0}'.format(
                    e))  # write to log
            if self.driverName == '':
                self.connected = 2
            else:
                self.connected = 0  # run the driver setup dialog
        finally:  # continue to work
            pass  # python necessary
Example #34
0
 def __init__(self, value=None):
     if value is not None:
         self.rect = value
     else:
         self.rect = Dispatch("AcroExch.Rect")
Example #35
0
 def __init__(self, point=None):
     if point is None:
         self.point = Dispatch("AcroExch.Point")
     else:
         self.point = point
def USDPointsOperator_Init(in_ctxt):
    o_dict = Dispatch("Scripting.Dictionary")
    o_dict["is_init"] = False
    in_ctxt.UserData = o_dict
    return True