本文整理匯總了Python中imp.load_module方法的典型用法代碼示例。如果您正苦於以下問題:Python imp.load_module方法的具體用法?Python imp.load_module怎麽用?Python imp.load_module使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類imp
的用法示例。
在下文中一共展示了imp.load_module方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _load_package_tests
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def _load_package_tests(name):
"""
Load the test classes from another modularcrypto package
:param name:
A unicode string of the other package name
:return:
A list of unittest.TestCase classes of the tests for the package
"""
package_dir = os.path.join('..', name)
if not os.path.exists(package_dir):
return []
tests_module_info = imp.find_module('tests', [package_dir])
tests_module = imp.load_module('%s.tests' % name, *tests_module_info)
return tests_module.test_classes()
示例2: import_helper
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def import_helper():
from os.path import dirname
import imp
possible_libs = ["_alf_grammar.win32",
"_alf_grammar.ntoarm",
"_alf_grammar.ntox86",
"_alf_grammar.linux"]
found_lib = False
for i in possible_libs:
fp = None
try:
fp, pathname, description = imp.find_module(i, [dirname(__file__)])
_mod = imp.load_module("_alf_grammar", fp, pathname, description)
found_lib = True
break
except ImportError:
pass
finally:
if fp:
fp.close()
if not found_lib:
raise ImportError("Failed to load _alf_grammar module")
return _mod
示例3: importfile
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def importfile(path):
"""Import a Python source file or compiled file given its path."""
magic = imp.get_magic()
with open(path, 'rb') as file:
if file.read(len(magic)) == magic:
kind = imp.PY_COMPILED
else:
kind = imp.PY_SOURCE
file.seek(0)
filename = os.path.basename(path)
name, ext = os.path.splitext(filename)
try:
module = imp.load_module(name, file, path, (ext, 'r', kind))
except:
raise ErrorDuringImport(path, sys.exc_info())
return module
示例4: _find_and_load_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def _find_and_load_module(self, name, path=None):
"""
Finds and loads it. But if there's a . in the name, handles it
properly.
"""
bits = name.split('.')
while len(bits) > 1:
# Treat the first bit as a package
packagename = bits.pop(0)
package = self._find_and_load_module(packagename, path)
try:
path = package.__path__
except AttributeError:
# This could be e.g. moves.
flog.debug('Package {0} has no __path__.'.format(package))
if name in sys.modules:
return sys.modules[name]
flog.debug('What to do here?')
name = bits[0]
module_info = imp.find_module(name, path)
return imp.load_module(name, *module_info)
示例5: find_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def find_module(self, fullname, path=None):
logger.debug('Running find_module: {0}...'.format(fullname))
if '.' in fullname:
parent, child = fullname.rsplit('.', 1)
if path is None:
loader = self.find_module(parent, path)
mod = loader.load_module(parent)
path = mod.__path__
fullname = child
# Perhaps we should try using the new importlib functionality in Python
# 3.3: something like this?
# thing = importlib.machinery.PathFinder.find_module(fullname, path)
try:
self.found = imp.find_module(fullname, path)
except Exception as e:
logger.debug('Py2Fixer could not find {0}')
logger.debug('Exception was: {0})'.format(fullname, e))
return None
self.kind = self.found[-1][-1]
if self.kind == imp.PKG_DIRECTORY:
self.pathname = os.path.join(self.found[1], '__init__.py')
elif self.kind == imp.PY_SOURCE:
self.pathname = self.found[1]
return self
示例6: npy_load_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def npy_load_module(name, fn, info=None):
"""
Load a module.
.. versionadded:: 1.11.2
Parameters
----------
name : str
Full module name.
fn : str
Path to module file.
info : tuple, optional
Only here for backward compatibility with Python 2.*.
Returns
-------
mod : module
"""
import importlib.machinery
return importlib.machinery.SourceFileLoader(name, fn).load_module()
示例7: _find_and_load_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def _find_and_load_module(self, submodule_name, fullname, path):
"""Finds and loads a module, using a provided search path.
Args:
submodule_name: The name of the submodule within its parent package.
fullname: The full name of the module to load.
path: A list containing the paths to search for the module.
Returns:
The requested module.
Raises:
ImportError: The module could not be imported.
"""
source_file, path_name, description, loader = self._find_module_or_loader(
submodule_name, fullname, path)
if loader:
return loader.load_module(fullname)
try:
return imp.load_module(fullname, source_file, path_name, description)
finally:
if source_file:
source_file.close()
示例8: __init__
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def __init__(self, name, loadfile):
"""
Load a single plugin
:param name: module name
:param loadfile: the main .py file
:raises Exception: Typically ImportError or OSError
"""
self.name = name # Display name.
self.folder = name # basename of plugin folder. None for internal plugins.
self.module = None # None for disabled plugins.
if loadfile:
sys.stdout.write(('loading plugin %s from "%s"\n' % (name.replace('.', '_'), loadfile)).encode('utf-8'))
with open(loadfile, 'rb') as plugfile:
module = imp.load_module('plugin_%s' % name.encode('ascii', 'replace').replace('.', '_'), plugfile, loadfile.encode(sys.getfilesystemencoding()),
('.py', 'r', imp.PY_SOURCE))
if module.plugin_start.func_code.co_argcount == 0:
newname = module.plugin_start()
else:
newname = module.plugin_start(os.path.dirname(loadfile))
self.name = newname and unicode(newname) or name
self.module = module
else:
sys.stdout.write('plugin %s disabled\n' % name)
示例9: make_py
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def make_py(parser, environ, filename):
module = load_module(environ, filename)
if not module:
return None
if hasattr(module, 'application') and module.application:
return getattr(module.application, 'wsgi_application', module.application)
base_name = module.__name__.split('.')[-1]
if hasattr(module, base_name):
obj = getattr(module, base_name)
if hasattr(obj, 'wsgi_application'):
return obj.wsgi_application
else:
# @@: Old behavior; should probably be deprecated eventually:
return getattr(module, base_name)()
environ['wsgi.errors'].write(
"Cound not find application or %s in %s\n"
% (base_name, module))
return None
示例10: init_plugins
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def init_plugins():
p_files = glob.glob(CTCore.plugins_folder + "*.py")
for p in p_files:
p_full = os.path.join(os.path.dirname(os.path.realpath(__file__)),p)
(path, name) = os.path.split(p_full)
(name, ext) = os.path.splitext(name)
(p_file, filename, data) = imp.find_module(name, [path])
mod = imp.load_module(name, p_file, filename, data)
for name, value in inspect.getmembers(mod):
if inspect.isclass(value):
if issubclass(value, ConsolePlugin) and value is not ConsolePlugin:
p_num = len(CTCore.plugins)
CTCore.plugins.append(namedtuple('Plugin', ['id', 'name','module', 'description']))
CTCore.plugins[p_num].id = p_num
CTCore.plugins[p_num].name = name
CTCore.plugins[p_num].module = value
CTCore.plugins[p_num].description = value.description
示例11: synopsis
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def synopsis(filename, cache={}):
"""Get the one-line summary out of a module file."""
mtime = os.stat(filename).st_mtime
lastupdate, result = cache.get(filename, (0, None))
if lastupdate < mtime:
info = inspect.getmoduleinfo(filename)
try:
file = open(filename)
except IOError:
# module can't be opened, so skip it
return None
if info and 'b' in info[2]: # binary modules have to be imported
try: module = imp.load_module('__temp__', file, filename, info[1:])
except: return None
result = (module.__doc__ or '').splitlines()[0]
del sys.modules['__temp__']
else: # text modules can be directly examined
result = source_synopsis(file)
file.close()
cache[filename] = (mtime, result)
return result
示例12: importfile
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def importfile(path):
"""Import a Python source file or compiled file given its path."""
magic = imp.get_magic()
file = open(path, 'r')
if file.read(len(magic)) == magic:
kind = imp.PY_COMPILED
else:
kind = imp.PY_SOURCE
file.close()
filename = os.path.basename(path)
name, ext = os.path.splitext(filename)
file = open(path, 'r')
try:
module = imp.load_module(name, file, path, (ext, 'r', kind))
except:
raise ErrorDuringImport(path, sys.exc_info())
file.close()
return module
示例13: load_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def load_module(self, name, stuff):
file, filename, info = stuff
(suff, mode, type) = info
try:
if type == BUILTIN_MODULE:
return self.hooks.init_builtin(name)
if type == FROZEN_MODULE:
return self.hooks.init_frozen(name)
if type == C_EXTENSION:
m = self.hooks.load_dynamic(name, filename, file)
elif type == PY_SOURCE:
m = self.hooks.load_source(name, filename, file)
elif type == PY_COMPILED:
m = self.hooks.load_compiled(name, filename, file)
elif type == PKG_DIRECTORY:
m = self.hooks.load_package(name, filename, file)
else:
raise ImportError, "Unrecognized module type (%r) for %s" % \
(type, name)
finally:
if file: file.close()
m.__file__ = filename
return m
示例14: synopsis
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def synopsis(filename, cache={}):
"""Get the one-line summary out of a module file."""
mtime = os.stat(filename).st_mtime
lastupdate, result = cache.get(filename, (None, None))
if lastupdate is None or lastupdate < mtime:
info = inspect.getmoduleinfo(filename)
try:
file = open(filename)
except IOError:
# module can't be opened, so skip it
return None
if info and 'b' in info[2]: # binary modules have to be imported
try: module = imp.load_module('__temp__', file, filename, info[1:])
except: return None
result = module.__doc__.splitlines()[0] if module.__doc__ else None
del sys.modules['__temp__']
else: # text modules can be directly examined
result = source_synopsis(file)
file.close()
cache[filename] = (mtime, result)
return result
示例15: swig_import_helper
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_module [as 別名]
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_snowboydetect', [dirname(__file__)])
except ImportError:
import _snowboydetect
return _snowboydetect
if fp is not None:
try:
_mod = imp.load_module('_snowboydetect', fp, pathname, description)
finally:
fp.close()
return _mod