1 | n/a | """Utilities to support packages.""" |
---|
2 | n/a | |
---|
3 | n/a | from collections import namedtuple |
---|
4 | n/a | from functools import singledispatch as simplegeneric |
---|
5 | n/a | import importlib |
---|
6 | n/a | import importlib.util |
---|
7 | n/a | import importlib.machinery |
---|
8 | n/a | import os |
---|
9 | n/a | import os.path |
---|
10 | n/a | import sys |
---|
11 | n/a | from types import ModuleType |
---|
12 | n/a | import warnings |
---|
13 | n/a | |
---|
14 | n/a | __all__ = [ |
---|
15 | n/a | 'get_importer', 'iter_importers', 'get_loader', 'find_loader', |
---|
16 | n/a | 'walk_packages', 'iter_modules', 'get_data', |
---|
17 | n/a | 'ImpImporter', 'ImpLoader', 'read_code', 'extend_path', |
---|
18 | n/a | 'ModuleInfo', |
---|
19 | n/a | ] |
---|
20 | n/a | |
---|
21 | n/a | |
---|
22 | n/a | ModuleInfo = namedtuple('ModuleInfo', 'module_finder name ispkg') |
---|
23 | n/a | ModuleInfo.__doc__ = 'A namedtuple with minimal info about a module.' |
---|
24 | n/a | |
---|
25 | n/a | |
---|
26 | n/a | def _get_spec(finder, name): |
---|
27 | n/a | """Return the finder-specific module spec.""" |
---|
28 | n/a | # Works with legacy finders. |
---|
29 | n/a | try: |
---|
30 | n/a | find_spec = finder.find_spec |
---|
31 | n/a | except AttributeError: |
---|
32 | n/a | loader = finder.find_module(name) |
---|
33 | n/a | if loader is None: |
---|
34 | n/a | return None |
---|
35 | n/a | return importlib.util.spec_from_loader(name, loader) |
---|
36 | n/a | else: |
---|
37 | n/a | return find_spec(name) |
---|
38 | n/a | |
---|
39 | n/a | |
---|
40 | n/a | def read_code(stream): |
---|
41 | n/a | # This helper is needed in order for the PEP 302 emulation to |
---|
42 | n/a | # correctly handle compiled files |
---|
43 | n/a | import marshal |
---|
44 | n/a | |
---|
45 | n/a | magic = stream.read(4) |
---|
46 | n/a | if magic != importlib.util.MAGIC_NUMBER: |
---|
47 | n/a | return None |
---|
48 | n/a | |
---|
49 | n/a | stream.read(8) # Skip timestamp and size |
---|
50 | n/a | return marshal.load(stream) |
---|
51 | n/a | |
---|
52 | n/a | |
---|
53 | n/a | def walk_packages(path=None, prefix='', onerror=None): |
---|
54 | n/a | """Yields ModuleInfo for all modules recursively |
---|
55 | n/a | on path, or, if path is None, all accessible modules. |
---|
56 | n/a | |
---|
57 | n/a | 'path' should be either None or a list of paths to look for |
---|
58 | n/a | modules in. |
---|
59 | n/a | |
---|
60 | n/a | 'prefix' is a string to output on the front of every module name |
---|
61 | n/a | on output. |
---|
62 | n/a | |
---|
63 | n/a | Note that this function must import all *packages* (NOT all |
---|
64 | n/a | modules!) on the given path, in order to access the __path__ |
---|
65 | n/a | attribute to find submodules. |
---|
66 | n/a | |
---|
67 | n/a | 'onerror' is a function which gets called with one argument (the |
---|
68 | n/a | name of the package which was being imported) if any exception |
---|
69 | n/a | occurs while trying to import a package. If no onerror function is |
---|
70 | n/a | supplied, ImportErrors are caught and ignored, while all other |
---|
71 | n/a | exceptions are propagated, terminating the search. |
---|
72 | n/a | |
---|
73 | n/a | Examples: |
---|
74 | n/a | |
---|
75 | n/a | # list all modules python can access |
---|
76 | n/a | walk_packages() |
---|
77 | n/a | |
---|
78 | n/a | # list all submodules of ctypes |
---|
79 | n/a | walk_packages(ctypes.__path__, ctypes.__name__+'.') |
---|
80 | n/a | """ |
---|
81 | n/a | |
---|
82 | n/a | def seen(p, m={}): |
---|
83 | n/a | if p in m: |
---|
84 | n/a | return True |
---|
85 | n/a | m[p] = True |
---|
86 | n/a | |
---|
87 | n/a | for info in iter_modules(path, prefix): |
---|
88 | n/a | yield info |
---|
89 | n/a | |
---|
90 | n/a | if info.ispkg: |
---|
91 | n/a | try: |
---|
92 | n/a | __import__(info.name) |
---|
93 | n/a | except ImportError: |
---|
94 | n/a | if onerror is not None: |
---|
95 | n/a | onerror(info.name) |
---|
96 | n/a | except Exception: |
---|
97 | n/a | if onerror is not None: |
---|
98 | n/a | onerror(info.name) |
---|
99 | n/a | else: |
---|
100 | n/a | raise |
---|
101 | n/a | else: |
---|
102 | n/a | path = getattr(sys.modules[info.name], '__path__', None) or [] |
---|
103 | n/a | |
---|
104 | n/a | # don't traverse path items we've seen before |
---|
105 | n/a | path = [p for p in path if not seen(p)] |
---|
106 | n/a | |
---|
107 | n/a | yield from walk_packages(path, info.name+'.', onerror) |
---|
108 | n/a | |
---|
109 | n/a | |
---|
110 | n/a | def iter_modules(path=None, prefix=''): |
---|
111 | n/a | """Yields ModuleInfo for all submodules on path, |
---|
112 | n/a | or, if path is None, all top-level modules on sys.path. |
---|
113 | n/a | |
---|
114 | n/a | 'path' should be either None or a list of paths to look for |
---|
115 | n/a | modules in. |
---|
116 | n/a | |
---|
117 | n/a | 'prefix' is a string to output on the front of every module name |
---|
118 | n/a | on output. |
---|
119 | n/a | """ |
---|
120 | n/a | if path is None: |
---|
121 | n/a | importers = iter_importers() |
---|
122 | n/a | else: |
---|
123 | n/a | importers = map(get_importer, path) |
---|
124 | n/a | |
---|
125 | n/a | yielded = {} |
---|
126 | n/a | for i in importers: |
---|
127 | n/a | for name, ispkg in iter_importer_modules(i, prefix): |
---|
128 | n/a | if name not in yielded: |
---|
129 | n/a | yielded[name] = 1 |
---|
130 | n/a | yield ModuleInfo(i, name, ispkg) |
---|
131 | n/a | |
---|
132 | n/a | |
---|
133 | n/a | @simplegeneric |
---|
134 | n/a | def iter_importer_modules(importer, prefix=''): |
---|
135 | n/a | if not hasattr(importer, 'iter_modules'): |
---|
136 | n/a | return [] |
---|
137 | n/a | return importer.iter_modules(prefix) |
---|
138 | n/a | |
---|
139 | n/a | |
---|
140 | n/a | # Implement a file walker for the normal importlib path hook |
---|
141 | n/a | def _iter_file_finder_modules(importer, prefix=''): |
---|
142 | n/a | if importer.path is None or not os.path.isdir(importer.path): |
---|
143 | n/a | return |
---|
144 | n/a | |
---|
145 | n/a | yielded = {} |
---|
146 | n/a | import inspect |
---|
147 | n/a | try: |
---|
148 | n/a | filenames = os.listdir(importer.path) |
---|
149 | n/a | except OSError: |
---|
150 | n/a | # ignore unreadable directories like import does |
---|
151 | n/a | filenames = [] |
---|
152 | n/a | filenames.sort() # handle packages before same-named modules |
---|
153 | n/a | |
---|
154 | n/a | for fn in filenames: |
---|
155 | n/a | modname = inspect.getmodulename(fn) |
---|
156 | n/a | if modname=='__init__' or modname in yielded: |
---|
157 | n/a | continue |
---|
158 | n/a | |
---|
159 | n/a | path = os.path.join(importer.path, fn) |
---|
160 | n/a | ispkg = False |
---|
161 | n/a | |
---|
162 | n/a | if not modname and os.path.isdir(path) and '.' not in fn: |
---|
163 | n/a | modname = fn |
---|
164 | n/a | try: |
---|
165 | n/a | dircontents = os.listdir(path) |
---|
166 | n/a | except OSError: |
---|
167 | n/a | # ignore unreadable directories like import does |
---|
168 | n/a | dircontents = [] |
---|
169 | n/a | for fn in dircontents: |
---|
170 | n/a | subname = inspect.getmodulename(fn) |
---|
171 | n/a | if subname=='__init__': |
---|
172 | n/a | ispkg = True |
---|
173 | n/a | break |
---|
174 | n/a | else: |
---|
175 | n/a | continue # not a package |
---|
176 | n/a | |
---|
177 | n/a | if modname and '.' not in modname: |
---|
178 | n/a | yielded[modname] = 1 |
---|
179 | n/a | yield prefix + modname, ispkg |
---|
180 | n/a | |
---|
181 | n/a | iter_importer_modules.register( |
---|
182 | n/a | importlib.machinery.FileFinder, _iter_file_finder_modules) |
---|
183 | n/a | |
---|
184 | n/a | |
---|
185 | n/a | def _import_imp(): |
---|
186 | n/a | global imp |
---|
187 | n/a | with warnings.catch_warnings(): |
---|
188 | n/a | warnings.simplefilter('ignore', DeprecationWarning) |
---|
189 | n/a | imp = importlib.import_module('imp') |
---|
190 | n/a | |
---|
191 | n/a | class ImpImporter: |
---|
192 | n/a | """PEP 302 Finder that wraps Python's "classic" import algorithm |
---|
193 | n/a | |
---|
194 | n/a | ImpImporter(dirname) produces a PEP 302 finder that searches that |
---|
195 | n/a | directory. ImpImporter(None) produces a PEP 302 finder that searches |
---|
196 | n/a | the current sys.path, plus any modules that are frozen or built-in. |
---|
197 | n/a | |
---|
198 | n/a | Note that ImpImporter does not currently support being used by placement |
---|
199 | n/a | on sys.meta_path. |
---|
200 | n/a | """ |
---|
201 | n/a | |
---|
202 | n/a | def __init__(self, path=None): |
---|
203 | n/a | global imp |
---|
204 | n/a | warnings.warn("This emulation is deprecated, use 'importlib' instead", |
---|
205 | n/a | DeprecationWarning) |
---|
206 | n/a | _import_imp() |
---|
207 | n/a | self.path = path |
---|
208 | n/a | |
---|
209 | n/a | def find_module(self, fullname, path=None): |
---|
210 | n/a | # Note: we ignore 'path' argument since it is only used via meta_path |
---|
211 | n/a | subname = fullname.split(".")[-1] |
---|
212 | n/a | if subname != fullname and self.path is None: |
---|
213 | n/a | return None |
---|
214 | n/a | if self.path is None: |
---|
215 | n/a | path = None |
---|
216 | n/a | else: |
---|
217 | n/a | path = [os.path.realpath(self.path)] |
---|
218 | n/a | try: |
---|
219 | n/a | file, filename, etc = imp.find_module(subname, path) |
---|
220 | n/a | except ImportError: |
---|
221 | n/a | return None |
---|
222 | n/a | return ImpLoader(fullname, file, filename, etc) |
---|
223 | n/a | |
---|
224 | n/a | def iter_modules(self, prefix=''): |
---|
225 | n/a | if self.path is None or not os.path.isdir(self.path): |
---|
226 | n/a | return |
---|
227 | n/a | |
---|
228 | n/a | yielded = {} |
---|
229 | n/a | import inspect |
---|
230 | n/a | try: |
---|
231 | n/a | filenames = os.listdir(self.path) |
---|
232 | n/a | except OSError: |
---|
233 | n/a | # ignore unreadable directories like import does |
---|
234 | n/a | filenames = [] |
---|
235 | n/a | filenames.sort() # handle packages before same-named modules |
---|
236 | n/a | |
---|
237 | n/a | for fn in filenames: |
---|
238 | n/a | modname = inspect.getmodulename(fn) |
---|
239 | n/a | if modname=='__init__' or modname in yielded: |
---|
240 | n/a | continue |
---|
241 | n/a | |
---|
242 | n/a | path = os.path.join(self.path, fn) |
---|
243 | n/a | ispkg = False |
---|
244 | n/a | |
---|
245 | n/a | if not modname and os.path.isdir(path) and '.' not in fn: |
---|
246 | n/a | modname = fn |
---|
247 | n/a | try: |
---|
248 | n/a | dircontents = os.listdir(path) |
---|
249 | n/a | except OSError: |
---|
250 | n/a | # ignore unreadable directories like import does |
---|
251 | n/a | dircontents = [] |
---|
252 | n/a | for fn in dircontents: |
---|
253 | n/a | subname = inspect.getmodulename(fn) |
---|
254 | n/a | if subname=='__init__': |
---|
255 | n/a | ispkg = True |
---|
256 | n/a | break |
---|
257 | n/a | else: |
---|
258 | n/a | continue # not a package |
---|
259 | n/a | |
---|
260 | n/a | if modname and '.' not in modname: |
---|
261 | n/a | yielded[modname] = 1 |
---|
262 | n/a | yield prefix + modname, ispkg |
---|
263 | n/a | |
---|
264 | n/a | |
---|
265 | n/a | class ImpLoader: |
---|
266 | n/a | """PEP 302 Loader that wraps Python's "classic" import algorithm |
---|
267 | n/a | """ |
---|
268 | n/a | code = source = None |
---|
269 | n/a | |
---|
270 | n/a | def __init__(self, fullname, file, filename, etc): |
---|
271 | n/a | warnings.warn("This emulation is deprecated, use 'importlib' instead", |
---|
272 | n/a | DeprecationWarning) |
---|
273 | n/a | _import_imp() |
---|
274 | n/a | self.file = file |
---|
275 | n/a | self.filename = filename |
---|
276 | n/a | self.fullname = fullname |
---|
277 | n/a | self.etc = etc |
---|
278 | n/a | |
---|
279 | n/a | def load_module(self, fullname): |
---|
280 | n/a | self._reopen() |
---|
281 | n/a | try: |
---|
282 | n/a | mod = imp.load_module(fullname, self.file, self.filename, self.etc) |
---|
283 | n/a | finally: |
---|
284 | n/a | if self.file: |
---|
285 | n/a | self.file.close() |
---|
286 | n/a | # Note: we don't set __loader__ because we want the module to look |
---|
287 | n/a | # normal; i.e. this is just a wrapper for standard import machinery |
---|
288 | n/a | return mod |
---|
289 | n/a | |
---|
290 | n/a | def get_data(self, pathname): |
---|
291 | n/a | with open(pathname, "rb") as file: |
---|
292 | n/a | return file.read() |
---|
293 | n/a | |
---|
294 | n/a | def _reopen(self): |
---|
295 | n/a | if self.file and self.file.closed: |
---|
296 | n/a | mod_type = self.etc[2] |
---|
297 | n/a | if mod_type==imp.PY_SOURCE: |
---|
298 | n/a | self.file = open(self.filename, 'r') |
---|
299 | n/a | elif mod_type in (imp.PY_COMPILED, imp.C_EXTENSION): |
---|
300 | n/a | self.file = open(self.filename, 'rb') |
---|
301 | n/a | |
---|
302 | n/a | def _fix_name(self, fullname): |
---|
303 | n/a | if fullname is None: |
---|
304 | n/a | fullname = self.fullname |
---|
305 | n/a | elif fullname != self.fullname: |
---|
306 | n/a | raise ImportError("Loader for module %s cannot handle " |
---|
307 | n/a | "module %s" % (self.fullname, fullname)) |
---|
308 | n/a | return fullname |
---|
309 | n/a | |
---|
310 | n/a | def is_package(self, fullname): |
---|
311 | n/a | fullname = self._fix_name(fullname) |
---|
312 | n/a | return self.etc[2]==imp.PKG_DIRECTORY |
---|
313 | n/a | |
---|
314 | n/a | def get_code(self, fullname=None): |
---|
315 | n/a | fullname = self._fix_name(fullname) |
---|
316 | n/a | if self.code is None: |
---|
317 | n/a | mod_type = self.etc[2] |
---|
318 | n/a | if mod_type==imp.PY_SOURCE: |
---|
319 | n/a | source = self.get_source(fullname) |
---|
320 | n/a | self.code = compile(source, self.filename, 'exec') |
---|
321 | n/a | elif mod_type==imp.PY_COMPILED: |
---|
322 | n/a | self._reopen() |
---|
323 | n/a | try: |
---|
324 | n/a | self.code = read_code(self.file) |
---|
325 | n/a | finally: |
---|
326 | n/a | self.file.close() |
---|
327 | n/a | elif mod_type==imp.PKG_DIRECTORY: |
---|
328 | n/a | self.code = self._get_delegate().get_code() |
---|
329 | n/a | return self.code |
---|
330 | n/a | |
---|
331 | n/a | def get_source(self, fullname=None): |
---|
332 | n/a | fullname = self._fix_name(fullname) |
---|
333 | n/a | if self.source is None: |
---|
334 | n/a | mod_type = self.etc[2] |
---|
335 | n/a | if mod_type==imp.PY_SOURCE: |
---|
336 | n/a | self._reopen() |
---|
337 | n/a | try: |
---|
338 | n/a | self.source = self.file.read() |
---|
339 | n/a | finally: |
---|
340 | n/a | self.file.close() |
---|
341 | n/a | elif mod_type==imp.PY_COMPILED: |
---|
342 | n/a | if os.path.exists(self.filename[:-1]): |
---|
343 | n/a | with open(self.filename[:-1], 'r') as f: |
---|
344 | n/a | self.source = f.read() |
---|
345 | n/a | elif mod_type==imp.PKG_DIRECTORY: |
---|
346 | n/a | self.source = self._get_delegate().get_source() |
---|
347 | n/a | return self.source |
---|
348 | n/a | |
---|
349 | n/a | def _get_delegate(self): |
---|
350 | n/a | finder = ImpImporter(self.filename) |
---|
351 | n/a | spec = _get_spec(finder, '__init__') |
---|
352 | n/a | return spec.loader |
---|
353 | n/a | |
---|
354 | n/a | def get_filename(self, fullname=None): |
---|
355 | n/a | fullname = self._fix_name(fullname) |
---|
356 | n/a | mod_type = self.etc[2] |
---|
357 | n/a | if mod_type==imp.PKG_DIRECTORY: |
---|
358 | n/a | return self._get_delegate().get_filename() |
---|
359 | n/a | elif mod_type in (imp.PY_SOURCE, imp.PY_COMPILED, imp.C_EXTENSION): |
---|
360 | n/a | return self.filename |
---|
361 | n/a | return None |
---|
362 | n/a | |
---|
363 | n/a | |
---|
364 | n/a | try: |
---|
365 | n/a | import zipimport |
---|
366 | n/a | from zipimport import zipimporter |
---|
367 | n/a | |
---|
368 | n/a | def iter_zipimport_modules(importer, prefix=''): |
---|
369 | n/a | dirlist = sorted(zipimport._zip_directory_cache[importer.archive]) |
---|
370 | n/a | _prefix = importer.prefix |
---|
371 | n/a | plen = len(_prefix) |
---|
372 | n/a | yielded = {} |
---|
373 | n/a | import inspect |
---|
374 | n/a | for fn in dirlist: |
---|
375 | n/a | if not fn.startswith(_prefix): |
---|
376 | n/a | continue |
---|
377 | n/a | |
---|
378 | n/a | fn = fn[plen:].split(os.sep) |
---|
379 | n/a | |
---|
380 | n/a | if len(fn)==2 and fn[1].startswith('__init__.py'): |
---|
381 | n/a | if fn[0] not in yielded: |
---|
382 | n/a | yielded[fn[0]] = 1 |
---|
383 | n/a | yield prefix + fn[0], True |
---|
384 | n/a | |
---|
385 | n/a | if len(fn)!=1: |
---|
386 | n/a | continue |
---|
387 | n/a | |
---|
388 | n/a | modname = inspect.getmodulename(fn[0]) |
---|
389 | n/a | if modname=='__init__': |
---|
390 | n/a | continue |
---|
391 | n/a | |
---|
392 | n/a | if modname and '.' not in modname and modname not in yielded: |
---|
393 | n/a | yielded[modname] = 1 |
---|
394 | n/a | yield prefix + modname, False |
---|
395 | n/a | |
---|
396 | n/a | iter_importer_modules.register(zipimporter, iter_zipimport_modules) |
---|
397 | n/a | |
---|
398 | n/a | except ImportError: |
---|
399 | n/a | pass |
---|
400 | n/a | |
---|
401 | n/a | |
---|
402 | n/a | def get_importer(path_item): |
---|
403 | n/a | """Retrieve a finder for the given path item |
---|
404 | n/a | |
---|
405 | n/a | The returned finder is cached in sys.path_importer_cache |
---|
406 | n/a | if it was newly created by a path hook. |
---|
407 | n/a | |
---|
408 | n/a | The cache (or part of it) can be cleared manually if a |
---|
409 | n/a | rescan of sys.path_hooks is necessary. |
---|
410 | n/a | """ |
---|
411 | n/a | try: |
---|
412 | n/a | importer = sys.path_importer_cache[path_item] |
---|
413 | n/a | except KeyError: |
---|
414 | n/a | for path_hook in sys.path_hooks: |
---|
415 | n/a | try: |
---|
416 | n/a | importer = path_hook(path_item) |
---|
417 | n/a | sys.path_importer_cache.setdefault(path_item, importer) |
---|
418 | n/a | break |
---|
419 | n/a | except ImportError: |
---|
420 | n/a | pass |
---|
421 | n/a | else: |
---|
422 | n/a | importer = None |
---|
423 | n/a | return importer |
---|
424 | n/a | |
---|
425 | n/a | |
---|
426 | n/a | def iter_importers(fullname=""): |
---|
427 | n/a | """Yield finders for the given module name |
---|
428 | n/a | |
---|
429 | n/a | If fullname contains a '.', the finders will be for the package |
---|
430 | n/a | containing fullname, otherwise they will be all registered top level |
---|
431 | n/a | finders (i.e. those on both sys.meta_path and sys.path_hooks). |
---|
432 | n/a | |
---|
433 | n/a | If the named module is in a package, that package is imported as a side |
---|
434 | n/a | effect of invoking this function. |
---|
435 | n/a | |
---|
436 | n/a | If no module name is specified, all top level finders are produced. |
---|
437 | n/a | """ |
---|
438 | n/a | if fullname.startswith('.'): |
---|
439 | n/a | msg = "Relative module name {!r} not supported".format(fullname) |
---|
440 | n/a | raise ImportError(msg) |
---|
441 | n/a | if '.' in fullname: |
---|
442 | n/a | # Get the containing package's __path__ |
---|
443 | n/a | pkg_name = fullname.rpartition(".")[0] |
---|
444 | n/a | pkg = importlib.import_module(pkg_name) |
---|
445 | n/a | path = getattr(pkg, '__path__', None) |
---|
446 | n/a | if path is None: |
---|
447 | n/a | return |
---|
448 | n/a | else: |
---|
449 | n/a | yield from sys.meta_path |
---|
450 | n/a | path = sys.path |
---|
451 | n/a | for item in path: |
---|
452 | n/a | yield get_importer(item) |
---|
453 | n/a | |
---|
454 | n/a | |
---|
455 | n/a | def get_loader(module_or_name): |
---|
456 | n/a | """Get a "loader" object for module_or_name |
---|
457 | n/a | |
---|
458 | n/a | Returns None if the module cannot be found or imported. |
---|
459 | n/a | If the named module is not already imported, its containing package |
---|
460 | n/a | (if any) is imported, in order to establish the package __path__. |
---|
461 | n/a | """ |
---|
462 | n/a | if module_or_name in sys.modules: |
---|
463 | n/a | module_or_name = sys.modules[module_or_name] |
---|
464 | n/a | if module_or_name is None: |
---|
465 | n/a | return None |
---|
466 | n/a | if isinstance(module_or_name, ModuleType): |
---|
467 | n/a | module = module_or_name |
---|
468 | n/a | loader = getattr(module, '__loader__', None) |
---|
469 | n/a | if loader is not None: |
---|
470 | n/a | return loader |
---|
471 | n/a | if getattr(module, '__spec__', None) is None: |
---|
472 | n/a | return None |
---|
473 | n/a | fullname = module.__name__ |
---|
474 | n/a | else: |
---|
475 | n/a | fullname = module_or_name |
---|
476 | n/a | return find_loader(fullname) |
---|
477 | n/a | |
---|
478 | n/a | |
---|
479 | n/a | def find_loader(fullname): |
---|
480 | n/a | """Find a "loader" object for fullname |
---|
481 | n/a | |
---|
482 | n/a | This is a backwards compatibility wrapper around |
---|
483 | n/a | importlib.util.find_spec that converts most failures to ImportError |
---|
484 | n/a | and only returns the loader rather than the full spec |
---|
485 | n/a | """ |
---|
486 | n/a | if fullname.startswith('.'): |
---|
487 | n/a | msg = "Relative module name {!r} not supported".format(fullname) |
---|
488 | n/a | raise ImportError(msg) |
---|
489 | n/a | try: |
---|
490 | n/a | spec = importlib.util.find_spec(fullname) |
---|
491 | n/a | except (ImportError, AttributeError, TypeError, ValueError) as ex: |
---|
492 | n/a | # This hack fixes an impedance mismatch between pkgutil and |
---|
493 | n/a | # importlib, where the latter raises other errors for cases where |
---|
494 | n/a | # pkgutil previously raised ImportError |
---|
495 | n/a | msg = "Error while finding loader for {!r} ({}: {})" |
---|
496 | n/a | raise ImportError(msg.format(fullname, type(ex), ex)) from ex |
---|
497 | n/a | return spec.loader if spec is not None else None |
---|
498 | n/a | |
---|
499 | n/a | |
---|
500 | n/a | def extend_path(path, name): |
---|
501 | n/a | """Extend a package's path. |
---|
502 | n/a | |
---|
503 | n/a | Intended use is to place the following code in a package's __init__.py: |
---|
504 | n/a | |
---|
505 | n/a | from pkgutil import extend_path |
---|
506 | n/a | __path__ = extend_path(__path__, __name__) |
---|
507 | n/a | |
---|
508 | n/a | This will add to the package's __path__ all subdirectories of |
---|
509 | n/a | directories on sys.path named after the package. This is useful |
---|
510 | n/a | if one wants to distribute different parts of a single logical |
---|
511 | n/a | package as multiple directories. |
---|
512 | n/a | |
---|
513 | n/a | It also looks for *.pkg files beginning where * matches the name |
---|
514 | n/a | argument. This feature is similar to *.pth files (see site.py), |
---|
515 | n/a | except that it doesn't special-case lines starting with 'import'. |
---|
516 | n/a | A *.pkg file is trusted at face value: apart from checking for |
---|
517 | n/a | duplicates, all entries found in a *.pkg file are added to the |
---|
518 | n/a | path, regardless of whether they are exist the filesystem. (This |
---|
519 | n/a | is a feature.) |
---|
520 | n/a | |
---|
521 | n/a | If the input path is not a list (as is the case for frozen |
---|
522 | n/a | packages) it is returned unchanged. The input path is not |
---|
523 | n/a | modified; an extended copy is returned. Items are only appended |
---|
524 | n/a | to the copy at the end. |
---|
525 | n/a | |
---|
526 | n/a | It is assumed that sys.path is a sequence. Items of sys.path that |
---|
527 | n/a | are not (unicode or 8-bit) strings referring to existing |
---|
528 | n/a | directories are ignored. Unicode items of sys.path that cause |
---|
529 | n/a | errors when used as filenames may cause this function to raise an |
---|
530 | n/a | exception (in line with os.path.isdir() behavior). |
---|
531 | n/a | """ |
---|
532 | n/a | |
---|
533 | n/a | if not isinstance(path, list): |
---|
534 | n/a | # This could happen e.g. when this is called from inside a |
---|
535 | n/a | # frozen package. Return the path unchanged in that case. |
---|
536 | n/a | return path |
---|
537 | n/a | |
---|
538 | n/a | sname_pkg = name + ".pkg" |
---|
539 | n/a | |
---|
540 | n/a | path = path[:] # Start with a copy of the existing path |
---|
541 | n/a | |
---|
542 | n/a | parent_package, _, final_name = name.rpartition('.') |
---|
543 | n/a | if parent_package: |
---|
544 | n/a | try: |
---|
545 | n/a | search_path = sys.modules[parent_package].__path__ |
---|
546 | n/a | except (KeyError, AttributeError): |
---|
547 | n/a | # We can't do anything: find_loader() returns None when |
---|
548 | n/a | # passed a dotted name. |
---|
549 | n/a | return path |
---|
550 | n/a | else: |
---|
551 | n/a | search_path = sys.path |
---|
552 | n/a | |
---|
553 | n/a | for dir in search_path: |
---|
554 | n/a | if not isinstance(dir, str): |
---|
555 | n/a | continue |
---|
556 | n/a | |
---|
557 | n/a | finder = get_importer(dir) |
---|
558 | n/a | if finder is not None: |
---|
559 | n/a | portions = [] |
---|
560 | n/a | if hasattr(finder, 'find_spec'): |
---|
561 | n/a | spec = finder.find_spec(final_name) |
---|
562 | n/a | if spec is not None: |
---|
563 | n/a | portions = spec.submodule_search_locations or [] |
---|
564 | n/a | # Is this finder PEP 420 compliant? |
---|
565 | n/a | elif hasattr(finder, 'find_loader'): |
---|
566 | n/a | _, portions = finder.find_loader(final_name) |
---|
567 | n/a | |
---|
568 | n/a | for portion in portions: |
---|
569 | n/a | # XXX This may still add duplicate entries to path on |
---|
570 | n/a | # case-insensitive filesystems |
---|
571 | n/a | if portion not in path: |
---|
572 | n/a | path.append(portion) |
---|
573 | n/a | |
---|
574 | n/a | # XXX Is this the right thing for subpackages like zope.app? |
---|
575 | n/a | # It looks for a file named "zope.app.pkg" |
---|
576 | n/a | pkgfile = os.path.join(dir, sname_pkg) |
---|
577 | n/a | if os.path.isfile(pkgfile): |
---|
578 | n/a | try: |
---|
579 | n/a | f = open(pkgfile) |
---|
580 | n/a | except OSError as msg: |
---|
581 | n/a | sys.stderr.write("Can't open %s: %s\n" % |
---|
582 | n/a | (pkgfile, msg)) |
---|
583 | n/a | else: |
---|
584 | n/a | with f: |
---|
585 | n/a | for line in f: |
---|
586 | n/a | line = line.rstrip('\n') |
---|
587 | n/a | if not line or line.startswith('#'): |
---|
588 | n/a | continue |
---|
589 | n/a | path.append(line) # Don't check for existence! |
---|
590 | n/a | |
---|
591 | n/a | return path |
---|
592 | n/a | |
---|
593 | n/a | |
---|
594 | n/a | def get_data(package, resource): |
---|
595 | n/a | """Get a resource from a package. |
---|
596 | n/a | |
---|
597 | n/a | This is a wrapper round the PEP 302 loader get_data API. The package |
---|
598 | n/a | argument should be the name of a package, in standard module format |
---|
599 | n/a | (foo.bar). The resource argument should be in the form of a relative |
---|
600 | n/a | filename, using '/' as the path separator. The parent directory name '..' |
---|
601 | n/a | is not allowed, and nor is a rooted name (starting with a '/'). |
---|
602 | n/a | |
---|
603 | n/a | The function returns a binary string, which is the contents of the |
---|
604 | n/a | specified resource. |
---|
605 | n/a | |
---|
606 | n/a | For packages located in the filesystem, which have already been imported, |
---|
607 | n/a | this is the rough equivalent of |
---|
608 | n/a | |
---|
609 | n/a | d = os.path.dirname(sys.modules[package].__file__) |
---|
610 | n/a | data = open(os.path.join(d, resource), 'rb').read() |
---|
611 | n/a | |
---|
612 | n/a | If the package cannot be located or loaded, or it uses a PEP 302 loader |
---|
613 | n/a | which does not support get_data(), then None is returned. |
---|
614 | n/a | """ |
---|
615 | n/a | |
---|
616 | n/a | spec = importlib.util.find_spec(package) |
---|
617 | n/a | if spec is None: |
---|
618 | n/a | return None |
---|
619 | n/a | loader = spec.loader |
---|
620 | n/a | if loader is None or not hasattr(loader, 'get_data'): |
---|
621 | n/a | return None |
---|
622 | n/a | # XXX needs test |
---|
623 | n/a | mod = (sys.modules.get(package) or |
---|
624 | n/a | importlib._bootstrap._load(spec)) |
---|
625 | n/a | if mod is None or not hasattr(mod, '__file__'): |
---|
626 | n/a | return None |
---|
627 | n/a | |
---|
628 | n/a | # Modify the resource name to be compatible with the loader.get_data |
---|
629 | n/a | # signature - an os.path format "filename" starting with the dirname of |
---|
630 | n/a | # the package's __file__ |
---|
631 | n/a | parts = resource.split('/') |
---|
632 | n/a | parts.insert(0, os.path.dirname(mod.__file__)) |
---|
633 | n/a | resource_name = os.path.join(*parts) |
---|
634 | n/a | return loader.get_data(resource_name) |
---|