Return a module spec based on a file location. To indicate that the module is a package, set submodule_search_locations to a list of directory paths. An empty list is sufficient, though its not otherwise useful to the import system. The loader must take a spec as its only __in
(name, location=None, *, loader=None,
submodule_search_locations=_POPULATE)
| 558 | |
| 559 | |
| 560 | def spec_from_file_location(name, location=None, *, loader=None, |
| 561 | submodule_search_locations=_POPULATE): |
| 562 | """Return a module spec based on a file location. |
| 563 | |
| 564 | To indicate that the module is a package, set |
| 565 | submodule_search_locations to a list of directory paths. An |
| 566 | empty list is sufficient, though its not otherwise useful to the |
| 567 | import system. |
| 568 | |
| 569 | The loader must take a spec as its only __init__() arg. |
| 570 | |
| 571 | """ |
| 572 | if location is None: |
| 573 | # The caller may simply want a partially populated location- |
| 574 | # oriented spec. So we set the location to a bogus value and |
| 575 | # fill in as much as we can. |
| 576 | location = '<unknown>' |
| 577 | if hasattr(loader, 'get_filename'): |
| 578 | # ExecutionLoader |
| 579 | try: |
| 580 | location = loader.get_filename(name) |
| 581 | except ImportError: |
| 582 | pass |
| 583 | else: |
| 584 | location = _os.fspath(location) |
| 585 | try: |
| 586 | location = _path_abspath(location) |
| 587 | except OSError: |
| 588 | pass |
| 589 | |
| 590 | # If the location is on the filesystem, but doesn't actually exist, |
| 591 | # we could return None here, indicating that the location is not |
| 592 | # valid. However, we don't have a good way of testing since an |
| 593 | # indirect location (e.g. a zip file or URL) will look like a |
| 594 | # non-existent file relative to the filesystem. |
| 595 | |
| 596 | spec = _bootstrap.ModuleSpec(name, loader, origin=location) |
| 597 | spec._set_fileattr = True |
| 598 | |
| 599 | # Pick a loader if one wasn't provided. |
| 600 | if loader is None: |
| 601 | for loader_class, suffixes in _get_supported_file_loaders(): |
| 602 | if location.endswith(tuple(suffixes)): |
| 603 | loader = loader_class(name, location) |
| 604 | spec.loader = loader |
| 605 | break |
| 606 | else: |
| 607 | return None |
| 608 | |
| 609 | # Set submodule_search_paths appropriately. |
| 610 | if submodule_search_locations is _POPULATE: |
| 611 | # Check the loader. |
| 612 | if hasattr(loader, 'is_package'): |
| 613 | try: |
| 614 | is_package = loader.is_package(name) |
| 615 | except ImportError: |
| 616 | pass |
| 617 | else: |