Get a resource from a package. This is a wrapper round the PEP 302 loader get_data API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using '/' as the path separator
(package, resource)
| 598 | |
| 599 | |
| 600 | def get_data(package, resource): |
| 601 | """Get a resource from a package. |
| 602 | |
| 603 | This is a wrapper round the PEP 302 loader get_data API. The package |
| 604 | argument should be the name of a package, in standard module format |
| 605 | (foo.bar). The resource argument should be in the form of a relative |
| 606 | filename, using '/' as the path separator. The parent directory name '..' |
| 607 | is not allowed, and nor is a rooted name (starting with a '/'). |
| 608 | |
| 609 | The function returns a binary string, which is the contents of the |
| 610 | specified resource. |
| 611 | |
| 612 | For packages located in the filesystem, which have already been imported, |
| 613 | this is the rough equivalent of |
| 614 | |
| 615 | d = os.path.dirname(sys.modules[package].__file__) |
| 616 | data = open(os.path.join(d, resource), 'rb').read() |
| 617 | |
| 618 | If the package cannot be located or loaded, or it uses a PEP 302 loader |
| 619 | which does not support get_data(), then None is returned. |
| 620 | """ |
| 621 | |
| 622 | spec = importlib.util.find_spec(package) |
| 623 | if spec is None: |
| 624 | return None |
| 625 | loader = spec.loader |
| 626 | if loader is None or not hasattr(loader, 'get_data'): |
| 627 | return None |
| 628 | # XXX needs test |
| 629 | mod = (sys.modules.get(package) or |
| 630 | importlib._bootstrap._load(spec)) |
| 631 | if mod is None or not hasattr(mod, '__file__'): |
| 632 | return None |
| 633 | |
| 634 | # Modify the resource name to be compatible with the loader.get_data |
| 635 | # signature - an os.path format "filename" starting with the dirname of |
| 636 | # the package's __file__ |
| 637 | parts = resource.split('/') |
| 638 | parts.insert(0, os.path.dirname(mod.__file__)) |
| 639 | resource_name = os.path.join(*parts) |
| 640 | return loader.get_data(resource_name) |
| 641 | |
| 642 | |
| 643 | _NAME_PATTERN = None |