Python clr.AddReferenceToFileAndPath() Examples

The following are 21 code examples of clr.AddReferenceToFileAndPath(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module clr , or try the search function .
Example #1
Source File: test_compiler.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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.iteritems():
            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)
        
############################ Tests ################################################### 
Example #2
Source File: test_compiler.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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.iteritems():
            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)
        
############################ Tests ################################################### 
Example #3
Source File: ipunittest.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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) 
Example #4
Source File: batch_rvt_util.py    From RevitBatchProcessor with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #5
Source File: test_compiler.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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') 
Example #6
Source File: test_compiler.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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) 
Example #7
Source File: test_ipyc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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')) 
Example #8
Source File: testdata.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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 os
        import sys
        clr.AddReferenceToFileAndPath(os.path.join(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,
        ) 
Example #9
Source File: test_clrload.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_addreferencetofileandpath_conflict(self):
        """verify AddReferenceToFileAndPath picks up the path specified, not some arbitrary assembly somewhere in your path already"""
        code1 = """
    using System;

    public class CollisionTest {
        public static string Result(){
            return "Test1";
        }
    }
    """

        code2 = """
    using System;

    public class CollisionTest {
        public static string Result(){
            return "Test2";
        }
    }
    """
        import clr
        tmp = self.temporary_dir

        test1_cs, test1_dll = os.path.join(tmp, 'test1.cs'), os.path.join(tmp, 'CollisionTest.dll')
        test2_cs, test2_dll = os.path.join(tmp, 'test2.cs'), os.path.join(sys.prefix, 'CollisionTest.dll')

        self.write_to_file(test1_cs, code1)
        self.write_to_file(test2_cs, code2)

        self.assertEqual(self.run_csc("/nologo /target:library /out:" + test2_dll + ' ' + test2_cs), 0)
        self.assertEqual(self.run_csc("/nologo /target:library /out:" + test1_dll + ' ' + test1_cs), 0)

        clr.AddReferenceToFileAndPath(test1_dll)
        import CollisionTest
        self.assertEqual(CollisionTest.Result(), "Test1")

    #TODO:@skip("multiple_execute") 
Example #10
Source File: test_clrload.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_negative_assembly_names(self):
        import clr
        self.assertRaises(IOError, clr.AddReferenceToFileAndPath, os.path.join(self.test_dir, 'this_file_does_not_exist.dll'))
        self.assertRaises(IOError, clr.AddReferenceToFileAndPath, os.path.join(self.test_dir, 'this_file_does_not_exist.dll'))
        self.assertRaises(IOError, clr.AddReferenceToFileAndPath, os.path.join(self.test_dir, 'this_file_does_not_exist.dll'))
        self.assertRaises(IOError, clr.AddReferenceByName, 'bad assembly name', 'WellFormed.But.Nonexistent, Version=9.9.9.9, Culture=neutral, PublicKeyToken=deadbeefdeadbeef, processorArchitecture=6502')
        self.assertRaises(FileNotFoundError if is_netcoreapp21 else SystemError, clr.AddReference, 'this_assembly_does_not_exist_neither_by_file_name_nor_by_strong_name')

        self.assertRaises(TypeError, clr.AddReference, 35)

        for method in [
            clr.AddReference,
            clr.AddReferenceToFile,
            clr.AddReferenceToFileAndPath,
            clr.AddReferenceByName,
            clr.AddReferenceByPartialName,
            clr.LoadAssemblyFromFileWithPath,
            clr.LoadAssemblyFromFile,
            clr.LoadAssemblyByName,
            clr.LoadAssemblyByPartialName,
            ]:
            self.assertRaises(TypeError, method, None)

        for method in [
            clr.AddReference,
            clr.AddReferenceToFile,
            clr.AddReferenceToFileAndPath,
            clr.AddReferenceByName,
            clr.AddReferenceByPartialName,
            ]:
            self.assertRaises(TypeError, method, None, None)

        import System
        self.assertRaises(ValueError, clr.LoadAssemblyFromFile, System.IO.Path.DirectorySeparatorChar)
        self.assertRaises(ValueError, clr.LoadAssemblyFromFile, '') 
Example #11
Source File: ipunittest.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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") 
Example #12
Source File: ipunittest.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #13
Source File: test_compiler.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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') 
Example #14
Source File: test_compiler.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #15
Source File: test_ipyc.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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')) 
Example #16
Source File: testdata.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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 os
        import sys
        clr.AddReferenceToFileAndPath(os.path.join(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,
        ) 
Example #17
Source File: test_clrload.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_addreferencetofileandpath_conflict(self):
        """verify AddReferenceToFileAndPath picks up the path specified, not some arbitrary assembly somewhere in your path already"""
        code1 = """
    using System;

    public class CollisionTest {
        public static string Result(){
            return "Test1";
        }
    }
    """

        code2 = """
    using System;

    public class CollisionTest {
        public static string Result(){
            return "Test2";
        }
    }
    """
        import clr
        tmp = self.temporary_dir

        test1_cs, test1_dll = os.path.join(tmp, 'test1.cs'), os.path.join(tmp, 'CollisionTest.dll')
        test2_cs, test2_dll = os.path.join(tmp, 'test2.cs'), os.path.join(sys.prefix, 'CollisionTest.dll')

        self.write_to_file(test1_cs, code1)
        self.write_to_file(test2_cs, code2)

        self.assertEqual(self.run_csc("/nologo /target:library /out:" + test2_dll + ' ' + test2_cs), 0)
        self.assertEqual(self.run_csc("/nologo /target:library /out:" + test1_dll + ' ' + test1_cs), 0)

        clr.AddReferenceToFileAndPath(test1_dll)
        import CollisionTest
        self.assertEqual(CollisionTest.Result(), "Test1")

    #TODO:@skip("multiple_execute") 
Example #18
Source File: test_clrload.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_negative_assembly_names(self):
        import clr
        self.assertRaises(IOError, clr.AddReferenceToFileAndPath, os.path.join(self.test_dir, 'this_file_does_not_exist.dll'))
        self.assertRaises(IOError, clr.AddReferenceToFileAndPath, os.path.join(self.test_dir, 'this_file_does_not_exist.dll'))
        self.assertRaises(IOError, clr.AddReferenceToFileAndPath, os.path.join(self.test_dir, 'this_file_does_not_exist.dll'))
        self.assertRaises(IOError, clr.AddReferenceByName, 'bad assembly name', 'WellFormed.But.Nonexistent, Version=9.9.9.9, Culture=neutral, PublicKeyToken=deadbeefdeadbeef, processorArchitecture=6502')
        self.assertRaises(IOError, clr.AddReference, 'this_assembly_does_not_exist_neither_by_file_name_nor_by_strong_name')

        self.assertRaises(TypeError, clr.AddReference, 35)

        for method in [
            clr.AddReference,
            clr.AddReferenceToFile,
            clr.AddReferenceToFileAndPath,
            clr.AddReferenceByName,
            clr.AddReferenceByPartialName,
            clr.LoadAssemblyFromFileWithPath,
            clr.LoadAssemblyFromFile,
            clr.LoadAssemblyByName,
            clr.LoadAssemblyByPartialName,
            ]:
            self.assertRaises(TypeError, method, None)

        for method in [
            clr.AddReference,
            clr.AddReferenceToFile,
            clr.AddReferenceToFileAndPath,
            clr.AddReferenceByName,
            clr.AddReferenceByPartialName,
            ]:
            self.assertRaises(TypeError, method, None, None)

        import System
        self.assertRaises(ValueError, clr.LoadAssemblyFromFile, System.IO.Path.DirectorySeparatorChar)
        self.assertRaises(ValueError, clr.LoadAssemblyFromFile, '') 
Example #19
Source File: ipunittest.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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") 
Example #20
Source File: test_ipyc.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
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) 
Example #21
Source File: test_ipyc.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
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, 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)