def import_module(name):
name = os.path.realpath(name)
thepath = os.path.dirname(name)
name = os.path.basename(name)
if name.endswith(".py"):
name = name[:-3]
f,path,desc = imp.find_module(name,[thepath])
try:
return imp.load_module(name, f, path, desc)
finally:
if f:
f.close()
#### INTERNAL/EXTERNAL FILE EMBEDDING ####
python类load_module()的实例源码
def import_module(name):
name = os.path.realpath(name)
thepath = os.path.dirname(name)
name = os.path.basename(name)
if name.endswith(".py"):
name = name[:-3]
f,path,desc = imp.find_module(name,[thepath])
try:
return imp.load_module(name, f, path, desc)
finally:
if f:
f.close()
#### INTERNAL/EXTERNAL FILE EMBEDDING ####
def runfile(fullpath):
"""
Import a Python module from a path.
"""
# Change the working directory to the directory of the example, so
# it can get at its data files, if any.
pwd = os.getcwd()
path, fname = os.path.split(fullpath)
sys.path.insert(0, os.path.abspath(path))
stdout = sys.stdout
sys.stdout = cStringIO.StringIO()
os.chdir(path)
try:
fd = open(fname)
module = imp.load_module("__main__", fd, fname, ('py', 'r', imp.PY_SOURCE))
finally:
del sys.path[0]
os.chdir(pwd)
sys.stdout = stdout
return module
def _imported_module(self):
"""Load the module this adapter points at."""
pyname = os.path.splitext(os.path.basename(self.module_abs_path()))[0]
pydir = os.path.dirname(self.module_abs_path())
(file_obj, pathname, description) = imp.find_module(pyname, [pydir])
with file_obj:
# this will reload the module if it has already been loaded.
mod = imp.load_module(
"opentimelineio.adapters.{}".format(self.name),
file_obj,
pathname,
description
)
return mod
def load_module(self, fullname, path=None):
imp_lock()
try:
# PEP302 If there is an existing module object named 'fullname'
# in sys.modules, the loader must use that existing module.
module = sys.modules.get(fullname)
if module is None:
module = imp.init_builtin(fullname)
except Exception:
# Remove 'fullname' from sys.modules if it was appended there.
if fullname in sys.modules:
sys.modules.pop(fullname)
raise # Raise the same exception again.
finally:
# Release the interpreter's import lock.
imp_unlock()
return module
### Optional Extensions to the PEP-302 Importer Protocol
def get_plugins(plugintype, module = None):
""" Discover the plugin classes contained in Python files.
Return a list of plugin classes.
"""
dir = os.path.join(os.getcwd(), "plugins", plugintype.id)
loaded = 0
plugins = []
for filename in os.listdir(dir):
modname, ext = os.path.splitext(filename)
if ext == '.py':
file, path, descr = imp.find_module(modname, [dir])
if file:
if module == modname:
# Loading the module registers the plugin in
# the corresponding base classes
mod = imp.load_module(modname, file, path, descr)
loaded += 1
elif not module:
plugins.append(modname)
loaded += 1
if plugins:
return plugins
else:
return plugintype.registry
def import_it(self, partname, fqname, parent, force_load=0):
if not partname:
# completely empty module name should only happen in
# 'from . import' or __import__("")
return parent
if not force_load:
try:
return self.modules[fqname]
except KeyError:
pass
try:
path = parent and parent.__path__
except AttributeError:
return None
partname = str(partname)
stuff = self.loader.find_module(partname, path)
if not stuff:
return None
fqname = str(fqname)
m = self.loader.load_module(fqname, stuff)
if parent:
setattr(parent, partname, m)
return m
def test_imp_module(self):
# Verify that the imp module can correctly load and find .py files
# XXX (ncoghlan): It would be nice to use test_support.CleanImport
# here, but that breaks because the os module registers some
# handlers in copy_reg on import. Since CleanImport doesn't
# revert that registration, the module is left in a broken
# state after reversion. Reinitialising the module contents
# and just reverting os.environ to its previous state is an OK
# workaround
orig_path = os.path
orig_getenv = os.getenv
with EnvironmentVarGuard():
x = imp.find_module("os")
new_os = imp.load_module("os", *x)
self.assertIs(os, new_os)
self.assertIs(orig_path, new_os.path)
self.assertIsNot(orig_getenv, new_os.getenv)
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
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
def get_module_constant(module, symbol, default=-1, paths=None):
"""Find 'module' by searching 'paths', and extract 'symbol'
Return 'None' if 'module' does not exist on 'paths', or it does not define
'symbol'. If the module defines 'symbol' as a constant, return the
constant. Otherwise, return 'default'."""
try:
f, path, (suffix, mode, kind) = find_module(module, paths)
except ImportError:
# Module doesn't exist
return None
try:
if kind == PY_COMPILED:
f.read(8) # skip magic & date
code = marshal.load(f)
elif kind == PY_FROZEN:
code = imp.get_frozen_object(module)
elif kind == PY_SOURCE:
code = compile(f.read(), path, 'exec')
else:
# Not something we can parse; we'll have to import it. :(
if module not in sys.modules:
imp.load_module(module, f, path, (suffix, mode, kind))
return getattr(sys.modules[module], symbol, None)
finally:
if f:
f.close()
return extract_constant(code, symbol, default)
def load_plugins(plugin_dir='./plugins/'):
for plugin_file in [fn for fn in glob.glob(plugin_dir + '*.py') if not os.path.basename(fn).startswith("__init__")]:
modname = os.path.basename(plugin_file.rsplit('.', 1)[0])
if globals().get(modname, None) is None:
try:
(mod_fh, mod_path, mod_desc) = imp.find_module(modname, [plugin_dir])
imp.load_module(modname, mod_fh, mod_path, mod_desc)
except:
raise PluginImportError(traceback.format_exc())
finally:
if mod_fh:
mod_fh.close()
# main class for new plugins to inherit from
def get_module_constant(module, symbol, default=-1, paths=None):
"""Find 'module' by searching 'paths', and extract 'symbol'
Return 'None' if 'module' does not exist on 'paths', or it does not define
'symbol'. If the module defines 'symbol' as a constant, return the
constant. Otherwise, return 'default'."""
try:
f, path, (suffix, mode, kind) = find_module(module, paths)
except ImportError:
# Module doesn't exist
return None
try:
if kind == PY_COMPILED:
f.read(8) # skip magic & date
code = marshal.load(f)
elif kind == PY_FROZEN:
code = imp.get_frozen_object(module)
elif kind == PY_SOURCE:
code = compile(f.read(), path, 'exec')
else:
# Not something we can parse; we'll have to import it. :(
if module not in sys.modules:
imp.load_module(module, f, path, (suffix, mode, kind))
return getattr(sys.modules[module], symbol, None)
finally:
if f:
f.close()
return extract_constant(code, symbol, default)
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_gnm', [dirname(__file__)])
except ImportError:
import _gnm
return _gnm
if fp is not None:
try:
_mod = imp.load_module('_gnm', fp, pathname, description)
finally:
fp.close()
return _mod
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_gdal', [dirname(__file__)])
except ImportError:
import _gdal
return _gdal
if fp is not None:
try:
_mod = imp.load_module('_gdal', fp, pathname, description)
finally:
fp.close()
return _mod
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_gdal_array', [dirname(__file__)])
except ImportError:
import _gdal_array
return _gdal_array
if fp is not None:
try:
_mod = imp.load_module('_gdal_array', fp, pathname, description)
finally:
fp.close()
return _mod
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_osr', [dirname(__file__)])
except ImportError:
import _osr
return _osr
if fp is not None:
try:
_mod = imp.load_module('_osr', fp, pathname, description)
finally:
fp.close()
return _mod
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_ogr', [dirname(__file__)])
except ImportError:
import _ogr
return _ogr
if fp is not None:
try:
_mod = imp.load_module('_ogr', fp, pathname, description)
finally:
fp.close()
return _mod
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_gdalconst', [dirname(__file__)])
except ImportError:
import _gdalconst
return _gdalconst
if fp is not None:
try:
_mod = imp.load_module('_gdalconst', fp, pathname, description)
finally:
fp.close()
return _mod
def load_module(self, fullname):
self._reopen()
try:
mod = imp.load_module(fullname, self.file, self.filename, self.etc)
finally:
if self.file:
self.file.close()
# Note: we don't set __loader__ because we want the module to look
# normal; i.e. this is just a wrapper for standard import machinery
return mod