当前位置: 首页>>代码示例>>Python>>正文


Python imp.new_module方法代码示例

本文整理汇总了Python中imp.new_module方法的典型用法代码示例。如果您正苦于以下问题:Python imp.new_module方法的具体用法?Python imp.new_module怎么用?Python imp.new_module使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在imp的用法示例。


在下文中一共展示了imp.new_module方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: import_object_from_string_code

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def import_object_from_string_code(code, object):
    """Used to import an object from arbitrary passed code.

    Passed in code is treated as a module and is imported and added
    to `sys.modules` with its SHA256 hash as key.

    Args:
        code (string): Python code to import as module

        object (string): Name of object to extract from imported module
    """
    sha256 = hashlib.sha256(code.encode('UTF-8')).hexdigest()
    module = imp.new_module(sha256)
    try:
        exec_(code, module.__dict__)
    except Exception as e:
        raise exceptions.UserError('User code exception', exception_message=str(e))
    sys.modules[sha256] = module
    try:
        return getattr(module, object)
    except AttributeError:
        raise exceptions.UserError("{} not found in code".format(object)) 
开发者ID:reiinakano,项目名称:xcessiv,代码行数:24,代码来源:functions.py

示例2: import_string_code_as_module

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def import_string_code_as_module(code):
    """Used to run arbitrary passed code as a module

    Args:
        code (string): Python code to import as module

    Returns:
        module: Python module
    """
    sha256 = hashlib.sha256(code.encode('UTF-8')).hexdigest()
    module = imp.new_module(sha256)
    try:
        exec_(code, module.__dict__)
    except Exception as e:
        raise exceptions.UserError('User code exception', exception_message=str(e))
    sys.modules[sha256] = module
    return module 
开发者ID:reiinakano,项目名称:xcessiv,代码行数:19,代码来源:functions.py

示例3: import_stub_module

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def import_stub_module(self, name):
    """Import the stub module replacement for the specified module."""
    # Do the equivalent of
    # ``from google.appengine.dist import <name>``.
    providing_dist = dist
    # When using the Py27 runtime, modules in dist27 have priority.
    # (They have already been vetted.)
    if name in dist27.__all__:
      providing_dist = dist27
    fullname = '%s.%s' % (providing_dist.__name__, name)
    __import__(fullname, {}, {})
    module = imp.new_module(fullname)
    module.__dict__.update(sys.modules[fullname].__dict__)
    module.__loader__ = self
    module.__name__ = name
    module.__package__ = None
    module.__name__ = name
    sys.modules[name] = module
    return module 
开发者ID:elsigh,项目名称:browserscope,代码行数:21,代码来源:sandbox.py

示例4: test_load_with_path_hook

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def test_load_with_path_hook(self):

    class DummyPathHook(object):

      def __init__(self, path):
        if path != 'dummy/path':
          raise ImportError

      def find_module(self, unused_fullname):
        return self

      def load_module(self, fullname):
        return imp.new_module('fake name: %s' % fullname)

    self.test_policies['distutils.util'] = sandbox.ModuleOverridePolicy(
        None, [], {}, default_pass_through=True)
    sys.path_hooks = [DummyPathHook]
    util = self.hook.load_module('distutils.util')
    self.assertEqual('fake name: distutils.util', util.__name__) 
开发者ID:elsigh,项目名称:browserscope,代码行数:21,代码来源:sandbox_test.py

示例5: load_from_string

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def load_from_string(self, settings_string='', module_name='customsettings'):
        '''
        Loads settings from a settings_string. Expects an escaped string like
        the following:
            "NAME=\'stuff\'\nTYPE=[\'item\']\n"

        @param settings_string: The string with your settings
        @return: A dict of loaded settings
        '''
        try:
            mod = imp.new_module(module_name)
            exec(settings_string, mod.__dict__)
        except TypeError:
            log.warning("Could not import settings")
        self.my_settings = {}
        try:
            self.my_settings = self._convert_to_dict(mod)
        except ImportError:
            log.warning("Settings unable to be loaded")

        return self.settings() 
开发者ID:istresearch,项目名称:scrapy-cluster,代码行数:23,代码来源:settings_wrapper.py

示例6: __init__

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def __init__(self, fileName):
        scriptEnv = Python.CreateRuntime()
        self.fileName = fileName
        self.engine = scriptEnv.GetEngine("python")        
        self.context = HostingHelpers.GetLanguageContext(self.engine) 
        scriptEnv.LoadAssembly(Type.GetType("System.String").Assembly) #mscorlib.dll
        scriptEnv.LoadAssembly(UriBuilder().GetType().Assembly)  #System.dll
                
        self.InitializePath()
        
        executable = Assembly.GetEntryAssembly().Location
        prefix = Path.GetDirectoryName(executable)
        
        self.context.SystemState.executable = executable
        self.context.SystemState.exec_prefix = self.context.SystemState.prefix = prefix
        
        import imp
        mod = imp.new_module('__main__')
        mod.__file__ = fileName
        mod.__builtins__ = sys.modules['__builtin__']
        self.context.SystemState.modules['__main__'] = mod
        self.mainScope = scriptEnv.CreateScope(mod.__dict__) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:24,代码来源:run_interactive.py

示例7: __init__

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def __init__(self, *names):
        self.modules = {}
        for name in names:
            if not name.endswith('.__init__'):
                import_name = name
            else:
                import_name = name[:-len('.__init__')]
            if '.' not in name:
                package = None
            elif import_name == name:
                package = name.rsplit('.', 1)[0]
            else:
                package = import_name
            module = imp.new_module(import_name)
            module.__loader__ = self
            module.__file__ = '<mock __file__>'
            module.__package__ = package
            module.attr = name
            if import_name != name:
                module.__path__ = ['<mock __path__>']
            self.modules[import_name] = module 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:23,代码来源:test_importlib.py

示例8: test_module_name

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def test_module_name(self):
        import imp
        m = imp.new_module('foo')
        self.assertEqual(m.__str__(), "<module 'foo' (built-in)>")
        m.__name__ = 'bar'
        self.assertEqual(m.__str__(), "<module 'bar' (built-in)>")
        m.__name__ = None
        self.assertEqual(m.__str__(), "<module '?' (built-in)>")
        m.__name__ = []
        self.assertEqual(m.__str__(), "<module '?' (built-in)>")
        m.__file__ = None
        self.assertEqual(m.__str__(), "<module '?' (built-in)>")
        m.__file__ = []
        self.assertEqual(m.__str__(), "<module '?' (built-in)>")
        m.__file__ = 'foo.py'
        self.assertEqual(m.__str__(), "<module '?' from 'foo.py'>") 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:18,代码来源:test_imp.py

示例9: main

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def main():
    host_config = parse_argv()

    namespace = probe_host(host_config)
    host_config.namespace = namespace

    live_test_mod = imp.new_module('livetests')
    sys.modules['livetests'] = live_test_mod

    def add_test_class(klass, name=None):
        if name is None:
            name = klass.__name__
        else:
            if not PY3:
                name = name.encode('ascii')
            klass.__name__ = name
        setattr(live_test_mod, name, klass)

    TestGeneral.conf = host_config
    add_test_class(TestGeneral)
    add_test_class(createUidTestClass(host_config, use_uid=True), 'TestWithUIDs')
    add_test_class(createUidTestClass(host_config, use_uid=False), 'TestWithoutUIDs')

    unittest.main(module='livetests') 
开发者ID:Schibum,项目名称:sndlatr,代码行数:26,代码来源:livetest.py

示例10: save_main_module

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def save_main_module(file, module_name):
    # patch provided by: Scott Schlesier - when script is run, it does not
    # use globals from pydevd:
    # This will prevent the pydevd script from contaminating the namespace for the script to be debugged
    # pretend pydevd is not the main module, and
    # convince the file to be debugged that it was loaded as main
    sys.modules[module_name] = sys.modules['__main__']
    sys.modules[module_name].__name__ = module_name

    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=DeprecationWarning)
        warnings.simplefilter("ignore", category=PendingDeprecationWarning)
        from imp import new_module

    m = new_module('__main__')
    sys.modules['__main__'] = m
    if hasattr(sys.modules[module_name], '__loader__'):
        m.__loader__ = getattr(sys.modules[module_name], '__loader__')
    m.__file__ = file

    return m 
开发者ID:fabioz,项目名称:PyDev.Debugger,代码行数:23,代码来源:pydevd_utils.py

示例11: load_compiled

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def load_compiled(self, name, filename, code, ispackage = False):
		#if data[:4] != imp.get_magic():
		#	raise ImportError('Bad magic number in %s' % filename)
		# Ignore timestamp in data[4:8]
		#code = marshal.loads(data[8:])
		imp.acquire_lock() # Required in threaded applications

		try:
			mod = imp.new_module(name)
			sys.modules[name] = mod 	# To handle circular and submodule imports
										# it should come before exec.
			try:
				mod.__file__ = filename # Is not so important.
				# For package you have to set mod.__path__ here.
				# Here I handle simple cases only.
				if ispackage:
					mod.__path__ = [name.replace('.', '/')]
				exec(code in mod.__dict__)
			except:
				del sys.modules[name]
				raise
		finally:
			imp.release_lock()

		return mod 
开发者ID:turingsec,项目名称:marsnake,代码行数:27,代码来源:factory_module.py

示例12: load_module

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def load_module(path,encoding=None):
	try:
		return cache_modules[path]
	except KeyError:
		pass
	module=imp.new_module(WSCRIPT_FILE)
	try:
		code=Utils.readf(path,m='rU',encoding=encoding)
	except EnvironmentError:
		raise Errors.WafError('Could not read the file %r'%path)
	module_dir=os.path.dirname(path)
	sys.path.insert(0,module_dir)
	exec(compile(code,path,'exec'),module.__dict__)
	sys.path.remove(module_dir)
	cache_modules[path]=module
	return module 
开发者ID:MOSAIC-UA,项目名称:802.11ah-ns3,代码行数:18,代码来源:Context.py

示例13: compile_module

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def compile_module(self):
        """Builds a temporary module from the script file

        :raises exceptions.IOError: if the compilation of the script module failed
        """
        try:
            imp.acquire_lock()

            code = compile(self.script, '%s (%s)' % (self.filename, self._script_id), 'exec')
            # load module
            module_name = os.path.splitext(self.filename)[0] + str(self._script_id)
            tmp_module = imp.new_module(module_name)
            exec(code, tmp_module.__dict__)
            # return the module
            self.compiled_module = tmp_module
        except Exception as e:
            self.compiled_module = None
            raise
        finally:
            imp.release_lock() 
开发者ID:DLR-RM,项目名称:RAFCON,代码行数:22,代码来源:script.py

示例14: load_module

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def load_module(path,encoding=None):
	try:
		return cache_modules[path]
	except KeyError:
		pass
	module=imp.new_module(WSCRIPT_FILE)
	try:
		code=Utils.readf(path,m='rU',encoding=encoding)
	except EnvironmentError:
		raise Errors.WafError('Could not read the file %r'%path)
	module_dir=os.path.dirname(path)
	sys.path.insert(0,module_dir)
	try:exec(compile(code,path,'exec'),module.__dict__)
	finally:sys.path.remove(module_dir)
	cache_modules[path]=module
	return module 
开发者ID:KTH,项目名称:royal-chaos,代码行数:18,代码来源:Context.py

示例15: import_script

# 需要导入模块: import imp [as 别名]
# 或者: from imp import new_module [as 别名]
def import_script(self, script):
        """ Import script from the EXASolution database """
        z = self._z
        getattr(self._comm.req, 'import').script_name = script
        try:
            self._comm(z.MT_IMPORT, z.MT_IMPORT)
            if getattr(self._comm.rep, 'import').exception_message != '':
                message = getattr(self._comm.rep, 'import').exception_message
                raise RuntimeError(message)
            code = getattr(self._comm.rep, 'import').source_code
        except Exception as err:
            raise ImportError(u'importing script %s failed: %s' % (script, str(err)))
        print("IMPORT", self._comm.connection_id, repr(code), "cache", repr(self), repr(self.__modules))
        if self.__modules.has_key(code):            
            return self.__modules[code]
        obj = imp.new_module(script)
        obj.__file__ = '<%s>' % script
        obj.__dict__['exa'] = self
        self.__modules[code] = obj
        try: exec(compile(code, script, 'exec'),obj.__dict__)
        except Exception as err:
            raise ImportError(u'importing module %s failed: %s' % (script, str(err)))
        return obj 
开发者ID:exasol,项目名称:script-languages,代码行数:25,代码来源:common_client.py


注:本文中的imp.new_module方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。