Пример #1
0
 def _import_puffin_dlls(self):
     print("Importing Puffin DLLs ...")
     clr.AddReferenceToFileAndPath(
         "Puffin\\Puffin.Core\\bin\\Debug\\netstandard2.0\\Puffin.Core.dll")
     clr.AddReferenceToFileAndPath(
         "Puffin\\Puffin.Infrastructure.MonoGame\\Bin\\Debug\\netstandard2.0\\Puffin.Infrastructure.MonoGame.dll"
     )
Пример #2
0
def get_enums():
    list_enum_byte = [0]
    list_enum_sbyte = [1]
    list_enum_ushort = [0]
    list_enum_short = [1]
    list_enum_uint = [0]
    list_enum_int = [1]
    list_enum_ulong = [0]
    list_enum_long = [1]

    if is_cli:
        import clr
        import sys
        clr.AddReferenceToFileAndPath(sys.exec_prefix + "/IronPythonTest.dll")
        from IronPythonTest import DaysByte, DaysInt, DaysLong, DaysSByte, DaysShort, DaysUInt, DaysULong, DaysUShort
        list_enum_byte = [DaysByte.None]
        list_enum_sbyte = [DaysSByte.Mon]
        list_enum_ushort = [DaysUShort.None]
        list_enum_short = [DaysShort.Mon]
        list_enum_uint = [DaysUInt.None]
        list_enum_int = [DaysInt.Mon]
        list_enum_ulong = [DaysULong.None]
        list_enum_long = [DaysLong.Mon]

    return merge_lists(
        list_enum_byte,
        list_enum_sbyte,
        list_enum_ushort,
        list_enum_short,
        list_enum_uint,
        list_enum_int,
        list_enum_ulong,
        list_enum_long,
    )
Пример #3
0
def test_compiled_code():
    if System.Environment.GetEnvironmentVariable('DLR_SaveAssemblies'):
        # The SaveAssemblies option is not compatible with saving code to disk
        print '... skipping test if DLR_SaveAssemblies is set...'
        return

    import clr

    pyil = os.path.join(testpath.temporary_dir, 'test.pyil')

    # make sure we can compile
    clr.CompileModules(pyil,
                       os.path.join(testpath.public_testdir, 'test_class.py'))

    # make sure we can compile multiple files
    clr.CompileModules(pyil,
                       os.path.join(testpath.public_testdir, 'test_class.py'),
                       os.path.join(testpath.public_testdir, 'test_slice.py'))

    clr.AddReferenceToFileAndPath(pyil)
    import nt

    # and make sure we can run some reasonable sophisticated code...
    System.IO.File.Move(os.path.join(testpath.public_testdir, 'test_class.py'),
                        'old_test_class.py')
    try:
        import test_class
        Assert(test_class.test_oldstyle_getattr.__doc__ != '')
    finally:
        System.IO.File.Move(
            'old_test_class.py',
            os.path.join(testpath.public_testdir, 'test_class.py'))
Пример #4
0
    def LoadLfso(self, version):
        lfso_modules = self._loaded_modules['LFSO']
        module = None
        lib_name = None

        if version in lfso_modules.keys() and lfso_modules[version] != {}:
            module = lfso_modules[version]
        else:
            try:
                #get the dll path and library name
                dll_path = self._args.LFSO_Paths[version]
                lib_name = 'LFSO{}Lib'.format(version.translate(None, '.'))

                #loads the LFSO reference and add it to the loaded modules list
                #tries to load from GAC first
                try:
                    clr.AddReference("Interop." + lib_name)
                    module = __import__(lib_name)
                    lfso_modules[version] = module
                except:
                    clr.AddReferenceToFileAndPath(dll_path)
                    module = __import__(lib_name)
                    lfso_modules[version] = module
            except Exception:
                print 'Laserfiche Server Object v{} could not be found. Please check your environment.py file'.format(
                    version)

        #if a module was found set it as the new default
        if module != None:
            if self._sdk is None:
                self._sdk = {'type': 'LFSO', 'module': {'LFSO': module}}
            else:
                self._sdk['module']['LFSO'] = module
        return module
Пример #5
0
def test_cp24113():
    import os
    from iptest.process_util import run_vbc
    from iptest.assert_util import testpath

    cp24113_vb_filename = testpath.temporary_dir + r"\cp24113_vb_module.vb"
    f = open(cp24113_vb_filename, "w")
    f.writelines(cp24113_vb_snippet)
    f.close()

    cp24113_vb_dllname = testpath.temporary_dir + r"\cp24113_vb_dll"
    run_vbc("/target:library /out:%s %s" %
            (cp24113_vb_dllname, cp24113_vb_filename))
    clr.AddReferenceToFileAndPath(cp24113_vb_dllname)
    import CodePlex24113

    class TestObj(object):
        Prop = None

        def __getitem__(self, key):
            return key

        def __setitem__(self, key, item):
            self.Prop = item

    to = TestObj()
    AreEqual(to.Prop, None)
    AreEqual(CodePlex24113.cp24113(to), "abc")
    AreEqual(to.Prop, "hi")
    def test_cp24113(self):
        import clr
        import os

        cp24113_vb_filename = os.path.join(self.temporary_dir,
                                           "cp24113_vb_module.vb")
        f = open(cp24113_vb_filename, "w")
        f.writelines(cp24113_vb_snippet)
        f.close()

        cp24113_vb_dllname = os.path.join(self.temporary_dir, "cp24113_vb_dll")
        self.run_vbc("/target:library /out:%s %s" %
                     (cp24113_vb_dllname, cp24113_vb_filename))
        clr.AddReferenceToFileAndPath(cp24113_vb_dllname)
        import CodePlex24113

        class TestObj(object):
            Prop = None

            def __getitem__(self, key):
                return key

            def __setitem__(self, key, item):
                self.Prop = item

        to = TestObj()
        self.assertEqual(to.Prop, None)
        self.assertEqual(CodePlex24113.cp24113(to), "abc")
        self.assertEqual(to.Prop, "hi")
Пример #7
0
 def load_iron_python_dll(self):
     #When assemblies are installed into the GAC, we should not expect
     #IronPython.dll to exist alongside IronPython.dll
     if os.path.exists(os.path.join(sys.prefix, "IronPython.dll")):
         clr.AddReferenceToFileAndPath(os.path.join(sys.prefix, "IronPython.dll"))
     else:
         clr.AddReference("IronPython")
Пример #8
0
    def DatabaseExists(self, configuration):
        clr.AddReferenceToFileAndPath(configuration.NpgsqlLocation)
        import Npgsql

        exists = False

        connection = Npgsql.NpgsqlConnection()
        connection.ConnectionString = "Server=%s;Port=5432;User ID=%s;Password=%s;SSL=True;Sslmode=Require;Database=postgres" % (
            configuration.Server, configuration.UserName,
            configuration.Password)

        try:
            connection.Open()

            try:
                command = connection.CreateCommand()

                command.CommandText = "select * from pg_database where datname = N'%s'" % (
                    configuration.Name)

                exists = command.ExecuteScalar()

                if exists != None:
                    exists = True

            except Exception, detail:
                print detail
                command.Dispose()
                raise

            else:
Пример #9
0
def test_load_order_modfile():
    fileName = path_combine(testpath.temporary_dir, "loadOrderMod.py")
    dllName = path_combine(testpath.temporary_dir, "loadOrderMod.dll")
    write_to_file(fileName, "def f(): return 'hello'")
    clr.CompileModules(dllName, fileName)
    write_to_file(fileName, "def f(): return 'bonjour'")
    clr.AddReferenceToFileAndPath(dllName)
    import loadOrderMod
    AreEqual(loadOrderMod.f(), 'hello')
Пример #10
0
def test_cached_types():
    import clr
    from System import IComparable, IFormattable, ICloneable
    import IronPythonTest

    cwd = os.getcwd()
    os.chdir(testpath.temporary_dir)

    # basic sanity test that we can compile...
    clr.CompileSubclassTypes('test', (object, ))
    clr.CompileSubclassTypes('test', object)
    clr.CompileSubclassTypes('test', object, str, int, long, float, complex)
    clr.CompileSubclassTypes('test', (object, IComparable[()]))
    clr.CompileSubclassTypes('test', (object, IComparable[()]),
                             (str, IComparable[()]))

    # build an unlikely existing type and make sure construction gives us
    # back the correct type.
    clr.CompileSubclassTypes(
        'cached_type_dll', (object, IComparable[()], IFormattable, ICloneable))
    asm = System.Reflection.Assembly.LoadFrom(
        os.path.join(testpath.temporary_dir, 'cached_type_dll.dll'))
    clr.AddReference(asm)

    class x(object, IComparable[()], IFormattable, ICloneable):
        pass

    a = x()
    AreEqual(clr.GetClrType(x).Assembly, asm)

    # collect all types that are available in IronPythonTest and
    # pre-gen them, then run test_inheritance to make sure it all works.
    types = []
    queue = [IronPythonTest]
    while queue:
        cur = queue.pop()
        for name in dir(cur):
            attr = getattr(cur, name)
            if type(attr) is type:
                clrType = clr.GetClrType(attr)
                if clrType.IsEnum or clrType.IsSealed or clrType.IsValueType or clrType.ContainsGenericParameters:
                    continue
                types.append(attr)
            elif type(attr) == type(IronPythonTest):
                queue.append(attr)

    clr.CompileSubclassTypes('InheritanceTypes', *types)
    clr.AddReferenceToFileAndPath(
        os.path.join(testpath.temporary_dir, 'InheritanceTypes.dll'))
    import test_inheritance

    #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=21892
    # verify that GetSubclassedTypes round trips with clr.CompileSubclassTypes
    clr.CompileSubclassTypes('finaltest', *clr.GetSubclassedTypes())
    clr.AddReference('finaltest')

    os.chdir(cwd)
Пример #11
0
 def load_iron_python_dll():
     import clr
     from System.IO import File
     #When assemblies are installed into the GAC, we should not expect
     #IronPython.dll to exist alongside IronPython.dll
     if File.Exists(path_combine(sys.prefix, "IronPython.dll")):
         clr.AddReferenceToFileAndPath(path_combine(sys.prefix, "IronPython.dll"))
     else:
         clr.AddReference("IronPython")
Пример #12
0
def load_ironpython_test(*args):
    _add_reference_to_dlr_core()
    clr.AddReference("Microsoft.Scripting")
    clr.AddReference("Microsoft.Dynamic")
    clr.AddReference("IronPython")

    if args:
        return clr.LoadAssemblyFromFileWithPath(_iron_python_test_dll)
    else:
        clr.AddReferenceToFileAndPath(_iron_python_test_dll)
Пример #13
0
 def test_load_order_modfile(self):
     import clr
     fileName = os.path.join(self.temporary_dir,"loadOrderMod.py")
     dllName = os.path.join(self.temporary_dir,"loadOrderMod.dll")
     self.write_to_file(fileName, "def f(): return 'hello'")
     clr.CompileModules(dllName, fileName)
     self.write_to_file(fileName, "def f(): return 'bonjour'")
     clr.AddReferenceToFileAndPath(dllName)
     import loadOrderMod
     self.assertEqual(loadOrderMod.f(), 'hello')
Пример #14
0
def test_overwrite():    
    write_to_file(path_combine(testpath.temporary_dir, "overwrite.py"), "def foo(): return 'bar'")
    dllFile = path_combine(testpath.temporary_dir, "overwrite.dll")
    clr.CompileModules(dllFile, path_combine(testpath.temporary_dir, "overwrite.py"))
    write_to_file(path_combine(testpath.temporary_dir, "overwrite1.py"), "def foo(): return 'boo'")
    clr.CompileModules(dllFile, path_combine(testpath.temporary_dir, "overwrite1.py"))
    clr.AddReferenceToFileAndPath(dllFile)
    
    import overwrite1
    AreEqual(overwrite1.foo(), 'boo')
Пример #15
0
 def test_overwrite(self):
     import clr
     self.write_to_file(os.path.join(self.temporary_dir, "overwrite.py"), "def foo(): return 'bar'")
     dllFile = os.path.join(self.temporary_dir, "overwrite.dll")
     clr.CompileModules(dllFile, os.path.join(self.temporary_dir, "overwrite.py"))
     self.write_to_file(os.path.join(self.temporary_dir, "overwrite1.py"), "def foo(): return 'boo'")
     clr.CompileModules(dllFile, os.path.join(self.temporary_dir, "overwrite1.py"))
     clr.AddReferenceToFileAndPath(dllFile)
     
     import overwrite1
     self.assertEqual(overwrite1.foo(), 'boo')
Пример #16
0
    def DropDatabase(self, configuration):
        clr.AddReferenceToFileAndPath(configuration.NpgsqlLocation)
        import Npgsql

        if not self.DatabaseExists(configuration):
            return

        for hook in configuration.Hooks:

            if hook.BeforeDrop is True:

                try:
                    arguments = '%s "%s"' % (hook.Arguments,
                                             configuration.ConnectionString)
                    DeployUtilities.RunExternalCommand(hook.Executable,
                                                       arguments)

                except System.ComponentModel.Win32Exception:
                    print 'Could not open "%s".' % (hook.Executable)
                    raise

                else:
                    print 'Ran hook [%s %s "%s"]' % (
                        hook.Executable, hook.Arguments,
                        configuration.ConnectionString)

        connection = Npgsql.NpgsqlConnection()
        connection.ConnectionString = "Server=%s;Port=5432;User ID=%s;Password=%s;SSL=True;Sslmode=Require;Database=postgres" % (
            configuration.Server, configuration.UserName,
            configuration.Password)

        try:
            connection.Open()

            try:
                command = connection.CreateCommand()

                commandText = []
                commandText.append('drop database "%s"' % (configuration.Name))

                command.CommandText = ''.join(commandText)

                command.ExecuteNonQuery()

                print 'Dropping database %s on %s' % (configuration.Name,
                                                      configuration.Server)

            except System.Exception, e:
                print e
                command.Dispose()
                raise

            else:
Пример #17
0
    def load_iron_python_test(*args):
        import clr

        AddReferenceToDlrCore()
        clr.AddReference("Microsoft.Scripting")
        clr.AddReference("Microsoft.Dynamic")
        clr.AddReference("IronPython")

        if args: 
            return clr.LoadAssemblyFromFileWithPath(testpath.iron_python_test_dll)
        else: 
            clr.AddReferenceToFileAndPath(testpath.iron_python_test_dll)
Пример #18
0
def compileCode(name, *codeArr):
    inputFiles = []
    counter = 0
    for code in codeArr:
        inputFile = path_combine(testpath.temporary_dir, name + ("" if counter == 0 else str(counter)) + ".py")
        write_to_file(inputFile, code)
        inputFiles.append(inputFile)
        counter+=1
    dllFile = path_combine(testpath.temporary_dir, name + ".dll")
    clr.CompileModules(dllFile, mainModule=inputFiles[0], *inputFiles)
    delete_files(*inputFiles)
    clr.AddReferenceToFileAndPath(dllFile)
def AddBatchRvtUtilAssemblyReference():
    try:
        clr.AddReference(BATCH_RVT_UTIL_ASSEMBLY_NAME)
    except IOException, e:  # Can occur if PyRevit is installed. Need to use AddReferenceToFileAndPath() in this case.
        batchRvtScriptHostAssembly = GetExistingLoadedAssembly(
            BATCH_RVT_SCRIPT_HOST_ASSEMBLY_NAME)
        clr.AddReference(batchRvtScriptHostAssembly)
        from BatchRvt.ScriptHost import ScriptHostUtil
        environmentVariables = ScriptHostUtil.GetEnvironmentVariables()
        batchRvtFolderPath = ScriptHostUtil.GetBatchRvtFolderPath(
            environmentVariables)
        clr.AddReferenceToFileAndPath(
            Path.Combine(batchRvtFolderPath, BATCH_RVT_UTIL_ASSEMBLY_NAME))
Пример #20
0
 def compileCode(self, name, *codeArr):
     import clr
     inputFiles = []
     counter = 0
     for code in codeArr:
         inputFile = os.path.join(self.temporary_dir, name + ("" if counter == 0 else str(counter)) + ".py")
         self.write_to_file(inputFile, code)
         inputFiles.append(inputFile)
         counter+=1
     dllFile = os.path.join(self.temporary_dir, name + ".dll")
     clr.CompileModules(dllFile, mainModule=inputFiles[0], *inputFiles)
     self.delete_files(*inputFiles)
     clr.AddReferenceToFileAndPath(dllFile)
Пример #21
0
def init(func):
    global _INSTANCE
    if _INSTANCE is None:

        #clr.AddReferenceToFile("TK_NodalEditor.dll")
        clr.AddReferenceToFileAndPath(
            r"Z:\Toonkit\RnD\Oscar\src\NodalEditor\NodalTester\bin\Debug\TK_NodalEditor.dll"
        )
        from TK.NodalEditor import Sharpy

        _INSTANCE = Sharpy()

    return func
Пример #22
0
 def CreateToolWindow(self, TypeName, AssemblyPath, GuidStr, Caption):
     try:
         clr.AddReferenceToFileAndPath(AssemblyPath)
         assemblyFileName = Path.GetFileName(AssemblyPath)
         asm = Assembly.Load(assemblyFileName)
         id = System.Guid(GuidStr)
         sGuid = "{%s}" % id.ToString()
         window = self.Control.UIController.CreateToolWindow(
             TypeName, asm.Location, Caption, id,
             self.Control.AddInInstance.DTE, self.Control.AddInInstance)
     except System.Exception, e:
         self.ShowMessage("Error in CreateToolWindow(%s, %s, %s): %s" %
                          (TypeName, AssemblyPath, GuidStr, repr(e)))
Пример #23
0
def compilePackage(packageName, codeDict):
    packagePath = path_combine(testpath.temporary_dir, packageName)
    ensure_directory_present(packagePath)
    fileList = []
    for fileName, code in codeDict.iteritems():
        filePath = path_combine(packagePath, fileName)
        ensure_directory_present(Path.GetDirectoryName(filePath))
        write_to_file(filePath, code)
        fileList.append(filePath)
    dllFile = path_combine(testpath.temporary_dir, packageName + ".dll")
    clr.CompileModules(dllFile, mainModule=fileList[0], *fileList)
    delete_files(*fileList)
    clr.AddReferenceToFileAndPath(dllFile)
Пример #24
0
def add_references_from_path(path, libs_list):
    """
    Adding references to c# libs.
    :param path: name of subfolder with libs (%project_folder%\path)
    :param libs_list: a list of libs that we want to add to references
    :return: none
    """
    lib_path = concatenate_win_path(
        os.path.dirname(__file__),
        path)  # here we get windows path to folder with libs
    for lib in libs_list:
        clr.AddReferenceToFileAndPath(concatenate_win_path(
            lib_path, lib))  # and here we adding all needed c# libs
def setup(rhino_version):
    """
    Loads the RhinoCommon and Grasshopper libraries based on the desired/installed Rhino version.
    Also loads the HoneyBadgerRuntime dll since it was somehow not working when imported above (maybe needs the Rhino dlls loaded first?)..
    """
    global GH_AssemblyInfo
    clr.AddReferenceToFileAndPath(
        os.path.join(os.path.expandvars("${PROGRAMFILES}"),
                     "Rhino {v}".format(v=rhino_version), "Plug-ins",
                     "Grasshopper", "Grasshopper.dll"))
    clr.AddReferenceToFileAndPath(
        os.path.join(os.path.expandvars("${PROGRAMFILES}"),
                     "Rhino {v}".format(v=rhino_version), "System",
                     "RhinoCommon.dll"))
    from Grasshopper.Kernel import GH_AssemblyInfo

    global HoneyBadgerRuntimeInfo, HoneyBadgerValueList

    hbrt_path = os.path.join(
        os.path.dirname(os.path.normpath(os.path.abspath(__file__))),
        "honey-badger-runtime", "bin", "honey-badger-runtime.dll")
    clr.AddReferenceToFileAndPath(hbrt_path)
    from HoneyBadgerRuntime import HoneyBadgerValueList, HoneyBadgerRuntimeInfo
Пример #26
0
 def compilePackage(self, packageName, codeDict):
     import clr
     packagePath = os.path.join(self.temporary_dir, packageName)
     self.ensure_directory_present(packagePath)
     fileList = []
     for fileName, code in codeDict.items():
         filePath = os.path.join(packagePath, fileName)
         self.ensure_directory_present(os.path.dirname(filePath))
         self.write_to_file(filePath, code)
         fileList.append(filePath)
     dllFile = os.path.join(self.temporary_dir, packageName + ".dll")
     clr.CompileModules(dllFile, mainModule=fileList[0], *fileList)
     self.delete_files(*fileList)
     clr.AddReferenceToFileAndPath(dllFile)
Пример #27
0
    def BuildDatabase(self, configuration):
        clr.AddReferenceToFileAndPath(configuration.NpgsqlLocation)
        import Npgsql

        if self.DatabaseExists(configuration):
            return

        connection = Npgsql.NpgsqlConnection()
        connection.ConnectionString = "Server=%s;Port=5432;User ID=%s;Password=%s;SSL=True;Sslmode=Require;Database=postgres" % (
            configuration.Server, configuration.UserName,
            configuration.Password)

        commands = []
        command = []

        command.append("create database \"%s\" encoding 'UTF8'" %
                       (configuration.Name))
        commands.append(''.join(command))
        command[:] = []

        builder = System.Text.StringBuilder()

        builder.Length = 0

        commands.append(builder.ToString())

        try:
            connection.Open()

            for command in commands:
                try:
                    dbCommand = connection.CreateCommand()
                    dbCommand.CommandText = command
                    dbCommand.ExecuteNonQuery()

                except Exception, detail:
                    dbCommand.Dispose()
                    raise

                else:
                    dbCommand.Dispose()

        except:
            raise

        else:
            print 'Creating database %s on %s' % (configuration.Name,
                                                  configuration.Server)
            connection.Close()
Пример #28
0
def git_tfs_release_notes(repo_path):
    libgit2sharp_version = '0.14.1.0'
    semver_version = '1.0.5'

    nuget_install('LibGit2Sharp', '-Version', libgit2sharp_version,
                  '-OutputDirectory', base_dir, '-Verbosity', 'quiet')
    nuget_install('semver', '-Version', semver_version, '-OutputDirectory',
                  base_dir, '-Verbosity', 'quiet')
    clr.AddReferenceToFileAndPath(
        os.path.join(base_dir, 'LibGit2Sharp.' + libgit2sharp_version, 'lib',
                     'net35', 'LibGit2Sharp.dll'))
    clr.AddReferenceToFileAndPath(
        os.path.join(base_dir, 'semver.' + semver_version, 'lib', 'net40',
                     'Semver.dll'))
    import LibGit2Sharp
    import Semver
    with LibGit2Sharp.Repository(repo_path) as repo:
        tags = list(repo.Tags)
        latest_version_tag = max(
            tags,
            key=lambda x: Semver.SemVersion.Parse(x.Name)) if tags else None
        commit_filter = LibGit2Sharp.CommitFilter()
        commit_filter.Since = repo.Head
        commit_filter.Until = latest_version_tag

        workitem_ids = set()
        for commit in repo.Commits.QueryBy(commit_filter):
            for match in re.finditer(r'#(\d+)', commit.Message):
                workitem_ids.add(int(match.group(1)))

        rows = []
        if latest_version_tag:
            rows.append('Since %s' % latest_version_tag.Name)
        rows.extend(
            ['* %d %s' % (x, tfs_get_workitem_title(x)) for x in workitem_ids])
        return '\n'.join(rows)
Пример #29
0
    def LoadRA(self, version, module_name):
        ra_modules = self._loaded_modules['RepositoryAccess']
        module_whitelist = [
            'RepositoryAccess', 'DocumentServices', 'ClientAutomation'
        ]
        module = None

        if version in ra_modules.keys(
        ) and module_name in ra_modules[version].keys():
            module = ra_modules[version][module_name]
        else:
            try:
                if module_name == 'ClientAutomation':
                    dll_path = r'{}\ClientAutomation.dll'.format(
                        self._args.RepositoryAccess_Paths[version])
                else:
                    dll_path = r'{}\Laserfiche.{}.dll'.format(
                        self._args.RepositoryAccess_Paths[version],
                        module_name)
                namespace = 'Laserfiche.{}'.format(module_name)

                try:
                    if module_name == 'ClientAutomation':
                        clr.AddReference(module_name)
                    else:
                        clr.AddReference(namespace)
                    module = __import__(namespace)
                except:
                    # Add reference and import target module
                    clr.AddReferenceToFileAndPath(dll_path)
                    module = __import__(namespace)

                temp = ra_modules[version] if len(
                    ra_modules[version].keys()) != 0 else {}
                temp[module_name] = module
                ra_modules[version] = temp

            except KeyError:
                print 'Repository Access v{} could not be found. Please check your environment.py file'.format(
                    version)

        #if a module was found set it as the new default
        if module != None:
            self._sdk = {'type': 'RA', 'module': module}

        return module
Пример #30
0
def import_openstudio():
    """Import the OpenStudio SDK into the Python environment.

    Returns:
        The OpenStudio NameSpace with all of the modules, classes and methods
        of the OpenStudio SDK.

    Usage:

    .. code-block:: python

        from ladybug_rhino.openstudio import import_openstudio, dump_osm
        OpenStudio = import_openstudio()

        # create a new OpenStudio model from scratch
        os_model = OpenStudio.Model()
        space_type = OpenStudio.SpaceType(os_model)

        # save the Model to an OSM
        osm_path = 'C:/path/to/model.osm'
        osm = dump_osm(os_model, osm_path)
    """
    try:  # first see if OpenStudio has already been loaded
        import OpenStudio
        return OpenStudio
    except ImportError:
        # check to be sure that the OpenStudio CSharp folder has been installed
        compatibility_url = 'https://github.com/ladybug-tools/lbt-grasshopper/wiki/' \
            '1.4-Compatibility-Matrix'
        in_msg = 'Download and install the version of OpenStudio listed in the ' \
            'Ladybug Tools compatibility matrix\n{}.'.format(compatibility_url)
        assert folders.openstudio_path is not None, \
            'No OpenStudio installation was found on this machine.\n{}'.format(in_msg)
        assert folders.openstudio_csharp_path is not None, \
            'No OpenStudio CSharp folder was found in the OpenStudio installation ' \
            'at:\n{}'.format(os.path.dirname(folders.openstudio_path))
        _copy_openstudio_lib()

        # add the OpenStudio DLL to the Common Language Runtime (CLR)
        os_dll = os.path.join(folders.openstudio_csharp_path, 'OpenStudio.dll')
        clr.AddReferenceToFileAndPath(os_dll)
        if folders.openstudio_csharp_path not in sys.path:
            sys.path.append(folders.openstudio_csharp_path)
        import OpenStudio
        return OpenStudio