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