def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, "IDEA.so") del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def load_library(self, data, fullname, dlopen=True, initfuncname=None): fd = -1 closefd = True result = False if self.memfd: fd = self.memfd() if fd != -1: name = '/proc/self/fd/{}'.format(fd) closefd = False if fd == -1: fd, name = mkstemp(dir=self.dir) try: write(fd, data) if dlopen: result = ctypes.CDLL(fullname) else: if initfuncname: result = imp.load_dynamic(initfuncname[4:], name) else: result = imp.load_dynamic(fullname, name) except Exception as e: self.dir = None raise e finally: if closefd: close(fd) unlink(name) return result
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, '_simplex.cp35-win32.pyd') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def Dtool_PreloadDLL(module): if module in sys.modules: return # First find it as a .pyd module on the Python path. if Dtool_FindModule(module): # OK, we should have no problem importing it as is. return # Nope, we'll need to search for a dynamic lib and preload it. # Search for the appropriate directory. target = None filename = module.replace('.', os.path.sep) + dll_suffix + dll_ext for dir in sys.path + [sys.prefix]: lib = os.path.join(dir, filename) if (os.path.exists(lib)): target = dir break if target is None: message = "DLL loader cannot find %s." % (module) raise ImportError(message) # Now import the file explicitly. pathname = os.path.join(target, filename) imp.load_dynamic(module, pathname)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, 'readline.so') __loader__ = None del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, "greenlet.so") __loader__ = None del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, "struct_ufunc_test.so") __loader__ = None del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, "etree.cpython-35m-darwin.so") __loader__ = None del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, '_texcaller.so') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, "vonmises_cython.pyd") __loader__ = None del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, "_correlate.so") __loader__ = None del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, "_backend_gdk.pyd") __loader__ = None del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, "monitoredqueue.pyd") __loader__ = None del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def find_psutil_build(buildDir): for item in os.listdir(buildDir): try: build = os.path.join(buildDir, item) binary = os.path.join(build, "_psutil_linux.so") imp.load_dynamic("_psutil_linux", binary) return build except Exception, e: pass
def test_imp_load_dynamic(self): #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=17459 self.assertEqual(imp.load_dynamic("", ""), None) try: _x_mod = os.path.join(self.test_dir, "x.py") self.write_to_file(_x_mod, "") with open(_x_mod, "r") as f: self.assertEqual(imp.load_dynamic("", "", f), None) finally: os.unlink(_x_mod)
def find_psutil_build(buildDir): for item in os.listdir(buildDir): try: build = os.path.join(buildDir, item) binary = os.path.join(build, '_psutil_linux.so') imp.load_dynamic('_psutil_linux', binary) return build except Exception: pass raise Exception("Available build of psutil not found.")
def test_load_dynamic_ImportError_path(self): # Issue #1559549 added `name` and `path` attributes to ImportError # in order to provide better detail. Issue #10854 implemented those # attributes on import failures of extensions on Windows. path = 'bogus file path' name = 'extension' with self.assertRaises(ImportError) as err: imp.load_dynamic(name, path) self.assertIn(path, err.exception.path) self.assertEqual(name, err.exception.name)
def load_module(self, fullname): f = fullname.replace('.', '_') mod = sys.modules.get(f) if mod is None: print 'LOAD DYNAMIC', f try: mod = imp.load_dynamic(f, f) except ImportError, e: print 'LOAD DYNAMIC FALLBACK', fullname, e mod = imp.load_dynamic(fullname, fullname) return mod
def test_imp_load_dynamic(): #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=17459 if not is_cpython: AreEqual(imp.load_dynamic("", ""), None) try: _x_mod = path_combine(testpath.public_testdir, "x.py") write_to_file(_x_mod, "") with open(_x_mod, "r") as f: AreEqual(imp.load_dynamic("", "", f), None) finally: nt.unlink(_x_mod)
def __bootstrap__(): global __file__ global __bootstrap__ global __loader__ import sys import pkg_resources import imp __file__ = pkg_resources.resource_filename(__name__, 'fragmentation_cy.so') __loader__ = None del __bootstrap__ del __loader__ imp.load_dynamic(__name__, __file__)
def test_issue16421_multiple_modules_in_one_dll(self): # Issue 16421: loading several modules from the same compiled file fails m = '_testimportmultiple' fileobj, pathname, description = imp.find_module(m) fileobj.close() mod0 = imp.load_dynamic(m, pathname) mod1 = imp.load_dynamic('_testimportmultiple_foo', pathname) mod2 = imp.load_dynamic('_testimportmultiple_bar', pathname) self.assertEqual(mod0.__name__, m) self.assertEqual(mod1.__name__, '_testimportmultiple_foo') self.assertEqual(mod2.__name__, '_testimportmultiple_bar') with self.assertRaises(ImportError): imp.load_dynamic('nonexistent', pathname)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__,'_speedups.so') del __bootstrap__ # Somehow __loader__ is undefined when butler builds the documentation # So do not delete it in that case try: del __loader__ except: pass imp.load_dynamic(__name__,__file__)
def __load(): import imp, os, sys, struct if hasattr(sys, "gettotalrefcount"): suffix = "-pydebug" pyd = "_d.pyd" else: suffix = "" pyd = ".pyd" if struct.calcsize("P") == 8: dirname = "build\\lib.win-amd64-%d.%d%s" % (sys.version_info[0], sys.version_info[1], suffix) else: dirname = "build\\lib.win32-%d.%d%s" % (sys.version_info[0], sys.version_info[1], suffix) path = os.path.abspath(os.path.join(dirname, __name__ + pyd)) imp.load_dynamic(__name__, path)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, os, pkg_resources, imp, platform if os.name == 'nt': __file__ = '_libevent.pyd' else: if 'arm' in platform.machine(): machine = 'pi' elif 'x86_64' in platform.machine(): machine = 'x86_64' else: machine = 'i386' __file__ = pkg_resources.resource_filename(__name__,'libevent-py%s-%s-%s.so' % (sys.version[:3],sys.platform,machine)) __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__)
def load_module( name, pyxfilename, pyxbuild_dir=None, is_package=False, build_inplace=False, language_level=None, so_path=None ): try: if so_path is None: if is_package: module_name = name + ".__init__" else: module_name = name so_path = build_module( module_name, pyxfilename, pyxbuild_dir, inplace=build_inplace, language_level=language_level ) mod = imp.load_dynamic(name, so_path) if is_package and not hasattr(mod, "__path__"): mod.__path__ = [os.path.dirname(so_path)] assert mod.__file__ == so_path, (mod.__file__, so_path) except Exception: if pyxargs.load_py_module_on_import_failure and pyxfilename.endswith(".py"): # try to fall back to normal import mod = imp.load_source(name, pyxfilename) assert mod.__file__ in (pyxfilename, pyxfilename + "c", pyxfilename + "o"), (mod.__file__, pyxfilename) else: import traceback raise ImportError( "Building module %s failed: %s" % (name, traceback.format_exception_only(*sys.exc_info()[:2])) ), None, sys.exc_info()[2] return mod
def pythran(self, line, cell): """ Compile and import everything from a Pythran code cell. %%pythran #pythran export foo(int) def foo(x): return x + x """ args = magic_arguments.parse_argstring(self.pythran, line) kwargs = {} if args.D: kwargs['define_macros'] = args.D if args.O: kwargs.setdefault('extra_compile_args', []).extend( '-O' + str(x) for x in args.O) if args.march: kwargs.setdefault('extra_compile_args', []).extend( '-march=' + str(x) for x in args.march) if args.fopenmp: kwargs.setdefault('extra_compile_args', []).append( '-fopenmp') m = hashlib.md5() m.update(cell) module_name = "pythranized_" + m.hexdigest() module_path = pythran.compile_pythrancode(module_name, cell, **kwargs) module = imp.load_dynamic(module_name, module_path) self._import_all(module)
def run_pythran(self, modname, module_path, runas, prelude=None, check_exception=False): """ Run Pythran code and clean Pythran dynamic library. runas may be a string to run or a tuple : (function name, list of parameters). """ # Caller may requires some cleaning prelude and prelude() pymod = load_dynamic(modname, module_path) err_msg = "Excepected exception but none raise." try: if isinstance(runas, tuple): ret_val = getattr(pymod, runas[0])(*runas[1]) else: # Produce the pythran result, exec in the loaded module ctx exec runas in pymod.__dict__ ret_val = getattr(pymod, self.TEST_RETURNVAL) if check_exception: raise AssertionError(err_msg) return ret_val except BaseException as e: if not check_exception or e.args[0] == err_msg: raise return type(e) finally: # Clean temporary DLL #FIXME: We can't remove this file while it is used in an import # through the exec statement (Windows constraints...) if sys.platform != "win32": os.remove(module_path) pass
def load_pybindings(name, path): """ Merges python bindings from shared library 'name' into module 'name'. Use when you have a directory structure:: lib/ foo.so foo/ __init__.py something.py Here, inside ``foo/__init__.py`` call ``load_pybindings(__name__, __path__)`` this assumes that the first entry in list ``__path__`` is where you want the wrapped classes to merge to. """ import imp, sys m = imp.load_dynamic(name, path[0] + ".so") thismod = sys.modules[name] for (k,v) in m.__dict__.items(): if not k.startswith("_"): thismod.__dict__[k] = v
def load_module(name, pyxfilename, pyxbuild_dir=None, is_package=False, build_inplace=False, language_level=None, so_path=None): try: if so_path is None: if is_package: module_name = name + '.__init__' else: module_name = name so_path = build_module(module_name, pyxfilename, pyxbuild_dir, inplace=build_inplace, language_level=language_level) mod = imp.load_dynamic(name, so_path) if is_package and not hasattr(mod, '__path__'): mod.__path__ = [os.path.dirname(so_path)] assert mod.__file__ == so_path, (mod.__file__, so_path) except Exception: if pyxargs.load_py_module_on_import_failure and pyxfilename.endswith('.py'): # try to fall back to normal import mod = imp.load_source(name, pyxfilename) assert mod.__file__ in (pyxfilename, pyxfilename+'c', pyxfilename+'o'), (mod.__file__, pyxfilename) else: tb = sys.exc_info()[2] import traceback exc = ImportError("Building module %s failed: %s" % ( name, traceback.format_exception_only(*sys.exc_info()[:2]))) if sys.version_info[0] >= 3: raise exc.with_traceback(tb) else: exec("raise exc, None, tb", {'exc': exc, 'tb': tb}) return mod
def __call__(self, *args, **kwds): #print self.compile_state if self.compile_state=='not_compiled': self.compile() assert self.compile_state=='compiled' if self.compile_state!='loaded': path=set() for jitted_func in self.walked_jitted_funcs: #print jitted_func.func_name path.add(jitted_func.module_dir) sys.path.extend(path) for jitted_func in self.walked_jitted_funcs: compiled_module=imp.load_dynamic(jitted_func.module_name, jitted_func.so_file) if jitted_func.load_names: func_init=getattr(compiled_module, "%s_init"%jitted_func.func_name) func_init(jitted_func.func_globals) #print 'load',jitted_func.module_name c_func=getattr(compiled_module, "%s__p"%jitted_func.func_name) jitted_func.c_func=c_func jitted_func.compile_state='loaded' assert self.compile_state=='loaded' return self.c_func(*args, **kwds)
def cython(self, line, cell): """Compile and import everything from a Cython code cell. The contents of the cell are written to a `.pyx` file in the directory `IPYTHONDIR/cython` using a filename with the hash of the code. This file is then cythonized and compiled. The resulting module is imported and all of its symbols are injected into the user's namespace. The usage is similar to that of `%%cython_pyximport` but you don't have to pass a module name:: %%cython def f(x): return 2.0*x To compile OpenMP codes, pass the required `--compile-args` and `--link-args`. For example with gcc:: %%cython --compile-args=-fopenmp --link-args=-fopenmp ... To enable profile guided optimisation, pass the ``--pgo`` option. Note that the cell itself needs to take care of establishing a suitable profile when executed. This can be done by implementing the functions to optimise, and then calling them directly in the same cell on some realistic training data like this:: %%cython --pgo def critical_function(data): for item in data: ... # execute function several times to build profile from somewhere import some_typical_data for _ in range(100): critical_function(some_typical_data) In Python 3.5 and later, you can distinguish between the profile and non-profile runs as follows:: if "_pgo_" in __name__: ... # execute critical code here """ args = magic_arguments.parse_argstring(self.cython, line) code = cell if cell.endswith('\n') else cell + '\n' lib_dir = os.path.join(get_ipython_cache_dir(), 'cython') quiet = True key = (code, line, sys.version_info, sys.executable, cython_version) if not os.path.exists(lib_dir): os.makedirs(lib_dir) if args.pgo: key += ('pgo', ) if args.force: # Force a new module name by adding the current time to the # key which is hashed to determine the module name. key += (time.time(), ) if args.name: module_name = py3compat.unicode_to_str(args.name) else: module_name = "_cython_magic_" + hashlib.md5( str(key).encode('utf-8')).hexdigest() html_file = os.path.join(lib_dir, module_name + '.html') module_path = os.path.join(lib_dir, module_name + self.so_ext) have_module = os.path.isfile(module_path) need_cythonize = args.pgo or not have_module if args.annotate: if not os.path.isfile(html_file): need_cythonize = True extension = None if need_cythonize: extensions = self._cythonize(module_name, code, lib_dir, args, quiet=quiet) assert len(extensions) == 1 extension = extensions[0] self._code_cache[key] = module_name if args.pgo: self._profile_pgo_wrapper(extension, lib_dir) self._build_extension(extension, lib_dir, pgo_step_name='use' if args.pgo else None) module = imp.load_dynamic(module_name, module_path) self._import_all(module) if args.annotate: try: with io.open(html_file, encoding='utf-8') as f: annotated_html = f.read() except IOError as e: # File could not be opened. Most likely the user has a version # of Cython before 0.15.1 (when `cythonize` learned the # `force` keyword argument) and has already compiled this # exact source without annotation. print( 'Cython completed successfully but the annotated ' 'source could not be read.', file=sys.stderr) print(e, file=sys.stderr) else: return display.HTML(self.clean_annotated_html(annotated_html))
# for the build directory, load from the file import imp, platform if platform.system() == 'Windows': cv2File = 'cv2.pyd' cv2Path = '../../../../OpenCV-build/lib/Release/' + cv2File else: cv2File = 'cv2.so' cv2Path = '../../../../OpenCV-build/lib/' + cv2File cv2Path = os.path.abspath(os.path.join(scriptPath, cv2Path)) # in the build directory, this path should exist, but in the installed extension # it should be in the python path, so only use the short file name if not os.path.isfile(cv2Path): print 'Full path not found: ', cv2Path cv2Path = cv2File print 'Loading cv2 from ', cv2Path cv2 = imp.load_dynamic('cv2', cv2File) # CameraCalibration class CameraCalibration(ScriptedLoadableModule): def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) self.parent.title = "CameraCalibration" # TODO make this more human readable by adding spaces self.parent.categories = ["Camera"] self.parent.dependencies = [] self.parent.contributors = ["Adam Rankin (Robarts Research Institute)"] self.parent.helpText = """Perform camera calibration against an external tracker.""" self.parent.helpText += self.getDefaultModuleDocumentationLink() self.parent.acknowledgementText = """ This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc. and Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.
def import_from_dll(dll_path=SHARED_CV2_DLL_PATH): return load_dynamic("cv2", dll_path)
Example DaVinci Resolve script: Draw folder and project tree from project manager window. import DaVinciResolveScript as dvr_script resolve = dvr_script.scriptapp("Resolve") fusion = resolve.Fusion() projectManager = resolve.GetProjectManager() projectManager.CreateProject("Hello World") from python_get_resolve import GetResolve """ import imp smodule = imp.load_dynamic( 'fusionscript', 'C:\\Program Files\\Blackmagic Design\\DaVinci Resolve\\fusionscript.dll') resolve = smodule.scriptapp('Resolve') def DisplayProjectsWithinFolder(projectManager, folderString="- ", projectString=" "): folderString = " " + folderString projectString = " " + projectString projects = sorted(projectManager.GetProjectsInCurrentFolder().values()) for projectName in projects: print(projectString + projectName) folders = sorted(projectManager.GetFoldersInCurrentFolder().values())
def load_dynamic(self, name, filename, file=None): return imp.load_dynamic(name, filename, file)
# -- coding: utf-8 -- import sys if sys.version_info.major == 3: import imp # import importlib as imp else: import imp from hypertable.thrift_client import * from hypertable.thrift_client.hyperthrift.gen.ttypes import * # import libHyperPython as ht_serialize if sys.argv[1] == 'python': ht_serialize = imp.load_dynamic('libHyperPython', sys.argv[2]) elif sys.argv[1] == 'python3': ht_serialize = imp.load_dynamic('libHyperPython', sys.argv[2]) elif sys.argv[1] == 'pypy': ht_serialize = imp.load_dynamic('libHyperPyPy', sys.argv[2]) print("SerializedCellsReader Test") num_cells = 100 value_multi = 200 test_input = [] output_test = [] client = ThriftClient("localhost", 15867) try: client.create_namespace("test") except:
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, 'test_rational.cpython-35m-arm-linux-gnueabihf.so') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__)
def __bootstrap(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__,'lib_csm_launch_py.py') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, 'sigtools.cpython-35m-x86_64-linux-gnu.so') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, 'fftpack_lite.so') del __bootstrap__, __loader__ imp.load_dynamic(__name__, __file__)
def load_module(name, pyxfilename): so_path = build_module(name, pyxfilename) mod = imp.load_dynamic(name, so_path) assert mod.__file__ == so_path, (mod.__file__, so_path) return mod
def __bootstrap__(): global __bootstrap__, __file__ import sys, imp __file__ = '_etree.pyd' del __bootstrap__ imp.load_dynamic(__name__, __file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, 'streams.so') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__)
#========================================================================== # VERSION #========================================================================== PM_API_VERSION = 0x0121 # v1.33 PM_REQ_SW_VERSION = 0x0121 # v1.33 import os import sys try: import promira as api except ImportError, ex1: import imp, platform ext = platform.system() in ('Windows', 'Microsoft') and '.dll' or '.so' try: api = imp.load_dynamic('promira', 'promira' + ext) except ImportError, ex2: import_err_msg = 'Error importing promira%s\n' % ext import_err_msg += ' Architecture of promira%s may be wrong\n' % ext import_err_msg += '%s\n%s' % (ex1, ex2) raise ImportError(import_err_msg) PM_SW_VERSION = api.py_version() & 0xffff PM_REQ_API_VERSION = (api.py_version() >> 16) & 0xffff PM_LIBRARY_LOADED = \ ((PM_SW_VERSION >= PM_REQ_SW_VERSION) and \ (PM_API_VERSION >= PM_REQ_API_VERSION)) from array import array, ArrayType import struct
def run_test(self, code, *params, **interface): """Test if a function call return value is unchanged when executed using python eval or compiled with pythran. Args: code (str): python (pythran valid) module to test. params (tuple): arguments to pass to the function to test. prelude (fct): function to call between 'code' and the c++ generated code interface (dict): pythran interface for the module to test. Each key is the name of a function to call, the value is a list of the arguments' type. Special keys are 'module_name', 'prelude', 'runas' and 'check_output'. Returns: nothing. Raises: AssertionError by 'unittest' if return value differ. SyntaxError if code is not python valid. pythran.CompileError if generated code can't be compiled. ...possibly others... """ # Extract special keys from interface. module_name = interface.pop('module_name', None) prelude = interface.pop('prelude', None) check_output = interface.pop('check_output', True) runas = interface.pop('runas', None) for name in sorted(interface.keys()): if runas: # runas is a python code string to run the test. By convention # the last statement of the sequence is the value to test. # We insert ourselves a variable to capture this value: # "a=1; b=2; myfun(a+b,a-b)" => "a=1; b=2; RES=myfun(a+b,a-b)" runas_commands = runas.split(";") begin = ";".join(runas_commands[:-1] + ['']) exec code + "\n" + begin in { } # this just tests the syntax of runas last = self.TEST_RETURNVAL + '=' + runas_commands[-1] runas = begin + "\n" + last else: # No runas provided, derive one from interface and params attributes = [] for p in params: if isinstance(p, str): attributes.append("'{0}'".format(p)) elif isinstance(p, ndarray): attributes.append("numpy.{0}".format( repr(p).replace("\n", ""))) else: # repr preserve the "L" suffix for long attributes.append(repr(p)) arglist = ",".join(attributes) function_call = "{0}({1})".format(name, arglist) runas = self.TEST_RETURNVAL + '=' + function_call # Caller may requires some cleaning prelude and prelude() # Produce the reference, python-way, run in an separated 'env' env = {'__builtin__': __import__('__builtin__')} refcode = code + "\n" + runas # Compare if exception raised in python and in pythran are the same python_exception_type = None pythran_exception_type = None try: if check_output: exec refcode in env python_ref = env[self.TEST_RETURNVAL] except BaseException as e: python_exception_type = type(e) # If no module name was provided, create one modname = module_name or ("test_" + name) # Compile the code using pythran cxx_compiled = compile_pythrancode(modname, code, interface, cxxflags=self.PYTHRAN_CXX_FLAGS) try: if not check_output: return # Caller may requires some cleaning prelude and prelude() pymod = load_dynamic(modname, cxx_compiled) try: # Produce the pythran result, exec in the loaded module ctx exec runas in pymod.__dict__ except BaseException as e: pythran_exception_type = type(e) else: pythran_res = getattr(pymod, self.TEST_RETURNVAL) # Test Results, assert if mismatch if python_exception_type: raise AssertionError( "expected exception was %s, but nothing happend!" % python_exception_type) self.compare_pythonpythran_results(python_ref, pythran_res) finally: # Clean temporary DLL os.remove(cxx_compiled) # Only compare the type of exceptions raised if pythran_exception_type != python_exception_type: if python_exception_type is None: raise e else: raise AssertionError( "expected exception was %s, but received %s" % (python_exception_type, pythran_exception_type))
from twisted.web import server from twisted.internet import reactor from txjsonrpc.web.jsonrpc import Proxy import xml.dom.minidom import xmlrpclib, pickle from SimpleXMLRPCServer import SimpleXMLRPCServer from core.returnvalue import * from core.bmparser import CompositionParser import os import random import commands from composition import CompositionManager from core.bmlogging import setup_logging import imp blockmon = imp.load_dynamic('blockmon', '../libblockmonlib.so') class BMProcessManager: """\brief Controls a running blockmon process. Note that this class/file can be used directly as an executable (the method used by the blockmon daemon to spawn blockmon processes) or by creating an instance of the class (the method used for the blockmon CLI). For the former, the manager runs an XML-RPC server which the blockmon daemon uses to communicate with it. Further note that all xml-rpc operations return a pickled ReturnValue object. """ bm_running = False def __init__(self, comp=None, bm_logger=None,
def load_dynamic(name, module_path): return imp.load_dynamic(name, module_path)
import imp import time #hahaha sys.path.append( "C:\\Program Files (x86)\\Viavi\\Xgig Maestro\\SDK\\LoadTester\\lib") import LoadTesterAPI_dll from LoadTesterAPI_dll import * sys.path.append( "C:\\Program Files (x86)\\Viavi\\Xgig Maestro\\SDK\\Jammer\\bin") from jammerapi_python import * if sys.version_info < (2, 7): # import _api_tracecontrol_python26 as _api_tracecontrol_python _api_tracecontrol_python = imp.load_dynamic( "_api_tracecontrol_python", "C:\Program Files (x86)\Viavi\Xgig Analyzer\SDK\TCAPI\Lib\_api_tracecontrol_python26.pyd" ) else: # import _api_tracecontrol_python27 as _api_tracecontrol_python _api_tracecontrol_python = imp.load_dynamic( "_api_tracecontrol_python", "C:\Program Files (x86)\Viavi\Xgig Analyzer\SDK\TCAPI\Lib\_api_tracecontrol_python27.pyd" ) ###################################################################################################################################################################### #######import my telnet.py file ,you need to put it into same folder ,if not you need to write the path #######This file is filed to update lidense to chassis ############ file, path, desc = imp.find_module('telnet') print file, path, desc Telnet_update_license_py = imp.load_module("telnet", file, path, desc)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, '_dumper.cp35-win32.pyd') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__)
""" SandboxBridge allows for registering Qt window types with Sandbox from Python. Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. """ import os import sys import imp from PySide2 import QtWidgets bridge_path = os.path.join(os.path.dirname(sys.executable), "EditorPlugins", "SandboxPythonBridge.dll") bridge_plugin = imp.load_dynamic("SandboxPythonBridge", bridge_path) def register_window(window_type, name, category="", needs_menu_item=True, menu_path="", unique=True): """ Register a new window type with the Sandbox. This should only be called once per window type, when your python plugin is initialized. :param class window_type: The class of your window. This must be a subclass of QWidget. :param str name: The name of your window. :param str category: The category of your window. :param bool needs_menu_item: If true, the window will be displayed in the "tools" submenu of the sandbox filemenu. :param str menu_path: The path (within the tools menu) to display your tool's menu item. Nested menus can be decalred with forward slahes. :param bool unique: If true, only one instance of your menu can be displayed at a time. Otherwise, multiple may be opened simultaneously.
def cython(self, line, cell): """Compile and import everything from a Cython code cell. The contents of the cell are written to a `.pyx` file in the directory `IPYTHONDIR/cython` using a filename with the hash of the code. This file is then cythonized and compiled. The resulting module is imported and all of its symbols are injected into the user's namespace. The usage is similar to that of `%%cython_pyximport` but you don't have to pass a module name:: %%cython def f(x): return 2.0*x To compile OpenMP codes, pass the required `--compile-args` and `--link-args`. For example with gcc:: %%cython --compile-args=-fopenmp --link-args=-fopenmp ... """ args = magic_arguments.parse_argstring(self.cython, line) code = cell if cell.endswith('\n') else cell+'\n' lib_dir = os.path.join(get_ipython_cache_dir(), 'cython') quiet = True key = code, sys.version_info, sys.executable, Cython.__version__ if not os.path.exists(lib_dir): os.makedirs(lib_dir) if args.force: # Force a new module name by adding the current time to the # key which is hashed to determine the module name. key += time.time(), if args.name: module_name = py3compat.unicode_to_str(args.name) else: module_name = "_cython_magic_" + hashlib.md5(str(key).encode('utf-8')).hexdigest() module_path = os.path.join(lib_dir, module_name + self.so_ext) have_module = os.path.isfile(module_path) need_cythonize = not have_module if args.annotate: html_file = os.path.join(lib_dir, module_name + '.html') if not os.path.isfile(html_file): need_cythonize = True if need_cythonize: c_include_dirs = args.include if 'numpy' in code: import numpy c_include_dirs.append(numpy.get_include()) pyx_file = os.path.join(lib_dir, module_name + '.pyx') pyx_file = py3compat.cast_bytes_py2(pyx_file, encoding=sys.getfilesystemencoding()) with io.open(pyx_file, 'w', encoding='utf-8') as f: f.write(code) extension = Extension( name = module_name, sources = [pyx_file], include_dirs = c_include_dirs, library_dirs = args.library_dirs, extra_compile_args = args.compile_args, extra_link_args = args.link_args, libraries = args.lib, language = 'c++' if args.cplus else 'c', ) build_extension = self._get_build_extension() try: opts = dict( quiet=quiet, annotate = args.annotate, force = True, ) build_extension.extensions = cythonize([extension], **opts) except CompileError: return if not have_module: build_extension.build_temp = os.path.dirname(pyx_file) build_extension.build_lib = lib_dir build_extension.run() self._code_cache[key] = module_name module = imp.load_dynamic(module_name, module_path) self._import_all(module) if args.annotate: try: with io.open(html_file, encoding='utf-8') as f: annotated_html = f.read() except IOError as e: # File could not be opened. Most likely the user has a version # of Cython before 0.15.1 (when `cythonize` learned the # `force` keyword argument) and has already compiled this # exact source without annotation. print('Cython completed successfully but the annotated ' 'source could not be read.', file=sys.stderr) print(e, file=sys.stderr) else: return display.HTML(self.clean_annotated_html(annotated_html))
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, '_flinalg.cpython-36m-aarch64-linux-gnu.so') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__)
import os import re import BigWorld import ResMgr from gui.shared.utils.HangarSpace import g_hangarSpace from xfw import * from xvm_main.python.logger import * import xvm_main.python.config as config from xvm_main.python.xvm import l10n #Native module import imp XVMNativePing = imp.load_dynamic( 'XVMNativePing', './res_mods/mods/packages/xvm_ping/native/XVMNativePing.pyd') ############################# """ NOTE: ICMP requires root privileges. Don't use it. """ class _Ping(object): def __init__(self): self.lock = threading.RLock() self.thread = None self.resp = None self.done_config = False self.loginSection = ResMgr.openSection('scripts_config.xml')['login']
import imp vdtnpfun = imp.load_dynamic('vdtnpfun', 'vdtnpfun_directory/vdtnpfun.so') import vdtnpfun print dir(vdtnpfun) from vdt_ctypes import * import numpy as np import timeit #print vdt_arch() #print vdt_expf([1,2,3,4]) loadit('vdt_expf') N = 2001 xx = np.linspace(-np.pi, np.pi, N) xf = np.linspace(-np.pi, np.pi, N) x = np.linspace(-np.pi, np.pi, N) def nsc(): global xx s = np.sin(xx) c = np.cos(xx) return (s, c) def nscf(): global xf
def _instantiate(net_id, import_id=-1): """ After every is compiled, actually create the Cython objects and bind them to the Python ones.""" if import_id < 0: import_id = net_id if Global.config['verbose']: Global._print('Building network ...') # Import the Cython library try: cython_module = imp.load_dynamic( 'ANNarchyCore' + str(import_id), 'annarchy/ANNarchyCore' + str(import_id) + '.so') except Exception as e: Global._print(e) Global._error( 'Something went wrong when importing the network. Force recompilation with --clean.' ) exit(0) Global._network[net_id]['instance'] = cython_module # Bind the py extensions to the corresponding python objects for pop in Global._network[net_id]['populations']: if Global.config['verbose']: Global._print('Creating population', pop.name) if Global.config['show_time']: t0 = time.time() # Instantiate the population pop._instantiate(cython_module) if Global.config['show_time']: Global._print('Creating', pop.name, 'took', (time.time() - t0) * 1000, 'milliseconds') # Instantiate projections for proj in Global._network[net_id]['projections']: if Global.config['verbose']: Global._print('Creating projection from', proj.pre.name, 'to', proj.post.name, 'with target="', proj.target, '"') if Global.config['show_time']: t0 = time.time() # Create the projection proj._instantiate(cython_module) if Global.config['show_time']: Global._print('Creating the projection took', (time.time() - t0) * 1000, 'milliseconds') # Finish to initialize the network, especially the rng # Must be called after the pops and projs are created! cython_module.pyx_create(Global.config['dt'], Global.config['seed']) # Transfer initial values for pop in Global._network[net_id]['populations']: if Global.config['verbose']: Global._print('Initializing population', pop.name) pop._init_attributes() for proj in Global._network[net_id]['projections']: if Global.config['verbose']: Global._print('Initializing projection from', proj.pre.name, 'to', proj.post.name, 'with target="', proj.target, '"') proj._init_attributes() # Sets the desired number of threads if Global.config['num_threads'] > 1: cython_module.set_number_threads(Global.config['num_threads']) # Start the monitors for monitor in Global._network[net_id]['monitors']: monitor._init_monitoring()
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, '_min_spanning_tree.pyd') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, 'tslib.cpython-37m-darwin.so') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__)
def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, 'refnanny.cpython-34m.so') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__)
def __load(): import imp, os, sys dirname = sys.prefix path = os.path.join(dirname, 'rwobject.pyd') #print "py2exe extension module", __name__, "->", path mod = imp.load_dynamic(__name__, path)
# \file _CADI.py # \brief High level Python interface to CADI models. # \date Copyright 2013 ARM Limited. All rights reserved. import platform import imp import os variety = '%(system)s-%(bits)s' % { 'system': platform.system(), 'bits': platform.architecture()[0] } module_name = { 'Linux-64bit': '_CADI_64.so', 'Linux-32bit': '_CADI_32.so', 'Windows-64bit': '_CADI_64.pyd', 'Windows-32bit': '_CADI_32.pyd', }[variety] _CADI = imp.load_dynamic('_CADI', os.path.join(os.path.dirname(__file__), module_name)) globals().update(_CADI.__dict__) del platform, imp, os, module_name, _CADI