本文整理匯總了Python中imp.find_module方法的典型用法代碼示例。如果您正苦於以下問題:Python imp.find_module方法的具體用法?Python imp.find_module怎麽用?Python imp.find_module使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類imp
的用法示例。
在下文中一共展示了imp.find_module方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: import_helper
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_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
示例2: _is_relative_import
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_module [as 別名]
def _is_relative_import(module_name, path):
"""Checks if import is relative. Returns True if relative, False if
absolute, and None if import could not be found."""
try:
# Check within the restricted path of a (sub-)package
imp.find_module(module_name, [path])
except ImportError:
pass
else:
return True
try:
# Check across all of sys.path
imp.find_module(module_name)
except ImportError:
pass
else:
return False
# Module could not be found on system due to:
# 1. Import that doesn't exist. "Bad import".
# 2. Since we're only scanning the AST, there's a good chance the
# import's inclusion is conditional, and would never be triggered.
# For example, an import specific to an OS.
return None
示例3: _load_package_tests
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_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()
示例4: _find_and_load_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_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 find_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: find_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_module [as 別名]
def find_module(self, modname, module_parts, processed, submodule_path):
"""Find the given module
Each finder is responsible for each protocol of finding, as long as
they all return a ModuleSpec.
:param str modname: The module which needs to be searched.
:param list module_parts: It should be a list of strings,
where each part contributes to the module's
namespace.
:param list processed: What parts from the module parts were processed
so far.
:param list submodule_path: A list of paths where the module
can be looked into.
:returns: A ModuleSpec, describing how and where the module was found,
None, otherwise.
"""
示例7: check_mysqldb_modules
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_module [as 別名]
def check_mysqldb_modules():
# 檢查MySQLdb模塊是否存在
# check MySQLdb module exists
try:
imp.find_module('MySQLdb')
found = 1
except ImportError:
found = 0
if found == 0:
os.system('yum install -y MySQL-python')
# 如果MySQLdb不存在,則使用yum安裝MySQL-python
# If MySQLdb doesn`t exist, then use Yum to install MySQL-python
else:
pass
# 如果MySLQdb存在,則什麽都不用做
# If MySLQdb exists, there's nothing to do
示例8: find_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_module [as 別名]
def find_module(self, fullname, path=None):
if fullname in _WHITE_LIST_C_MODULES:
return None
if any(regex.match(fullname) for regex in self._enabled_regexes):
return None
_, _, submodule_name = fullname.rpartition('.')
try:
result = imp.find_module(submodule_name, path)
except ImportError:
return None
f, _, description = result
_, _, file_type = description
if isinstance(f, file):
f.close()
if file_type == imp.C_EXTENSION:
return self
return None
示例9: test_load_with_path_hook
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_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__)
示例10: test_load_with_path_hook_cant_find
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_module [as 別名]
def test_load_with_path_hook_cant_find(self):
class DummyPathHook(object):
def __init__(self, path):
if path != 'dummy/path':
raise ImportError
def find_module(self, unused_fullname):
return None
def load_module(self, fullname):
raise ImportError
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('distutils.util', util.__name__)
示例11: SetAllowedModule
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_module [as 別名]
def SetAllowedModule(name):
"""Allow the use of a module based on where it is located.
Meant to be used by use_library() so that it has a link back into the
trusted part of the interpreter.
Args:
name: Name of the module to allow.
"""
stream, pathname, description = imp.find_module(name)
pathname = os.path.normcase(os.path.abspath(pathname))
if stream:
stream.close()
FakeFile.ALLOWED_FILES.add(pathname)
FakeFile.ALLOWED_FILES.add(os.path.realpath(pathname))
else:
assert description[2] == imp.PKG_DIRECTORY
if pathname.startswith(SITE_PACKAGES):
FakeFile.ALLOWED_SITE_PACKAGE_DIRS.add(pathname)
FakeFile.ALLOWED_SITE_PACKAGE_DIRS.add(os.path.realpath(pathname))
else:
FakeFile.ALLOWED_DIRS.add(pathname)
FakeFile.ALLOWED_DIRS.add(os.path.realpath(pathname))
示例12: find_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_module [as 別名]
def find_module(module, paths=None):
"""Just like 'imp.find_module()', but with package support"""
parts = module.split('.')
while parts:
part = parts.pop(0)
f, path, (suffix,mode,kind) = info = imp.find_module(part, paths)
if kind==PKG_DIRECTORY:
parts = parts or ['__init__']
paths = [path]
elif parts:
raise ImportError("Can't find %r in %s" % (parts,module))
return info
示例13: _check_if_pyc
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_module [as 別名]
def _check_if_pyc(fname):
"""Return True if the extension is .pyc, False if .py
and None if otherwise"""
from imp import find_module
from os.path import realpath, dirname, basename, splitext
# Normalize the file-path for the find_module()
filepath = realpath(fname)
dirpath = dirname(filepath)
module_name = splitext(basename(filepath))[0]
# Validate and fetch
try:
fileobj, fullpath, (_, _, pytype) = find_module(module_name, [dirpath])
except ImportError:
raise IOError("Cannot find config file. "
"Path maybe incorrect! : {0}".format(filepath))
return pytype, fileobj, fullpath
示例14: init_plugins
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_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
示例15: swig_import_helper
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import find_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