PEP 302 Finder that wraps Python's "classic" import algorithm ImpImporter(dirname) produces a PEP 302 finder that searches that directory. ImpImporter(None) produces a PEP 302 finder that searches the current sys.path, plus any modules that are frozen or built-in. Note that
| 192 | imp = importlib.import_module('imp') |
| 193 | |
| 194 | class ImpImporter: |
| 195 | """PEP 302 Finder that wraps Python's "classic" import algorithm |
| 196 | |
| 197 | ImpImporter(dirname) produces a PEP 302 finder that searches that |
| 198 | directory. ImpImporter(None) produces a PEP 302 finder that searches |
| 199 | the current sys.path, plus any modules that are frozen or built-in. |
| 200 | |
| 201 | Note that ImpImporter does not currently support being used by placement |
| 202 | on sys.meta_path. |
| 203 | """ |
| 204 | |
| 205 | def __init__(self, path=None): |
| 206 | global imp |
| 207 | warnings.warn("This emulation is deprecated and slated for removal " |
| 208 | "in Python 3.12; use 'importlib' instead", |
| 209 | DeprecationWarning) |
| 210 | _import_imp() |
| 211 | self.path = path |
| 212 | |
| 213 | def find_module(self, fullname, path=None): |
| 214 | # Note: we ignore 'path' argument since it is only used via meta_path |
| 215 | subname = fullname.split(".")[-1] |
| 216 | if subname != fullname and self.path is None: |
| 217 | return None |
| 218 | if self.path is None: |
| 219 | path = None |
| 220 | else: |
| 221 | path = [os.path.realpath(self.path)] |
| 222 | try: |
| 223 | file, filename, etc = imp.find_module(subname, path) |
| 224 | except ImportError: |
| 225 | return None |
| 226 | return ImpLoader(fullname, file, filename, etc) |
| 227 | |
| 228 | def iter_modules(self, prefix=''): |
| 229 | if self.path is None or not os.path.isdir(self.path): |
| 230 | return |
| 231 | |
| 232 | yielded = {} |
| 233 | import inspect |
| 234 | try: |
| 235 | filenames = os.listdir(self.path) |
| 236 | except OSError: |
| 237 | # ignore unreadable directories like import does |
| 238 | filenames = [] |
| 239 | filenames.sort() # handle packages before same-named modules |
| 240 | |
| 241 | for fn in filenames: |
| 242 | modname = inspect.getmodulename(fn) |
| 243 | if modname=='__init__' or modname in yielded: |
| 244 | continue |
| 245 | |
| 246 | path = os.path.join(self.path, fn) |
| 247 | ispkg = False |
| 248 | |
| 249 | if not modname and os.path.isdir(path) and '.' not in fn: |
| 250 | modname = fn |
| 251 | try: |