def pyimport(self, modname=None, ensuresyspath=True): |
""" return path as an imported python module. |
if modname is None, look for the containing package |
and construct an according module name. |
The module will be put/looked up in sys.modules. |
""" |
if not self.check(): |
raise py.error.ENOENT(self) |
|
pkgpath = None |
if modname is None: |
|
|
|
|
pkgpath = self.pypkgpath() |
if pkgpath is not None: |
if ensuresyspath: |
self._prependsyspath(pkgpath.dirpath()) |
pkg = __import__(pkgpath.basename, None, None, []) |
|
if hasattr(pkg, '__pkg__'): |
modname = pkg.__pkg__.getimportname(self) |
assert modname is not None, "package %s doesn't know %s" % ( |
pkg.__name__, self) |
|
else: |
names = self.new(ext='').relto(pkgpath.dirpath()) |
names = names.split(self.sep) |
modname = ".".join(names) |
else: |
|
if ensuresyspath: |
self._prependsyspath(self.dirpath()) |
modname = self.purebasename |
-> mod = __import__(modname, None, None, ['__doc__']) |
|
return mod |
else: |
try: |
return sys.modules[modname] |
except KeyError: |
|
mod = py.std.new.module(modname) |
mod.__file__ = str(self) |
sys.modules[modname] = mod |
try: |
execfile(str(self), mod.__dict__) |
except: |
del sys.modules[modname] |
raise |
return mod |