imp
imp是实现import机制的库
imp.get_magic()
返回字节码文件(pyc)的magic num,用于标识python版本的
imp.get_suffixes()
返回的是(suffix, mode, type)形式的关于module的信息,不同平台的可被包含的种类可能不同
# Mac
[('.so', 'rb', 3), ('module.so', 'rb', 3), ('.py', 'U', 1), ('.pyc', 'rb', 2)]
imp.find_module(name[, path])
找到name对应的模块,如果没有给出path则在sys.path中找,给出时path需要为路径名的列表,如果格式不正确的静默跳过。
找到了,返回的格式为(file, pathname, description),file是file对象,pathname是路径名称,description为(suffix, mode, type)。
找不到返回的是None,同时抛出ImportError
imp.load_module(name, file, pathname, description)
如果该模块已经被import了,则相当于reload。
name是完整的模块名称,包含package。
file则是打开的文件,pathname是文件路径,都可以不填
引入成功则返回module对象,否则抛出ImportError,调用者负责关闭文件
imp.new_module(name)
Return a new empty module object called name. This object is not inserted in sys.modules
imp.
lock_held
()
Return True
if the import lock is currently held, else False
. On platforms without threads, always return False
.
On platforms with threads, a thread executing an import holds an internal lock until the import is complete. This lock blocks other threads from doing an import until the original import completes, which in turn prevents other threads from seeing incomplete module objects constructed by the original thread while in the process of completing its import (and the imports, if any, triggered by that).
imp.
acquire_lock
()
Acquire the interpreter’s import lock for the current thread. This lock should be used by import hooks to ensure thread-safety when importing modules.
Once a thread has acquired the import lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it.
On platforms without threads, this function does nothing.
New in version 2.3.
imp.
release_lock
()
Release the interpreter’s import lock. On platforms without threads, this function does nothing.
New in version 2.3.
例子
import imp
import sys
def __import__(name, globals=None, locals=None, fromlist=None):
try:
return sys.modules[name]
except KeyError:
pass
fp, pathname, description = imp.find_module(name)
try:
return imp.load_module(name, fp, pathname, description)
finally:
if fp:
fp.close()
importlib
coding: utf8
import sys
def _resolve_name(name, package, level):
"""返回该模块的绝对名称"""
if not hasattr(package, 'rindex'): # 这是为了什么?判断package是否为str么?
raise ValueError("'package' not set to a string")
dot = len(package) # 几层
# 找到该层 舍去之后的东西
for x in xrange(level, 1, -1):
try:
dot = package.rindex('.', 0, dot)
except ValueError:
raise ValueError("attempted relative import beyond top-level "
"package")
return "%s.%s" % (package[:dot], name)
def import_module(name, package=None):
"""
引入模块 如果是相对引入,需要设置package
"""
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
level = 0
for character in name:
if character != '.':
break
level += 1
# 这个可以数出来名称开头有几个点 即需要上溯几层
# 然后解析的时候不带点 直接传名称进去
name = _resolve_name(name[level:], package, level)
__import__(name) # 直接引入
return sys.modules[name] # 看系统被引入模块中是否包含了