本文整理匯總了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))
示例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
示例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
示例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__)
示例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()
示例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__)
示例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
示例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'>")
示例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')
示例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
示例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
示例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
示例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()
示例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
示例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