def _get_importer(path_name):
"""Python version of PyImport_GetImporter C API function"""
cache = sys.path_importer_cache
try:
importer = cache[path_name]
except KeyError:
# Not yet cached. Flag as using the
# standard machinery until we finish
# checking the hooks
cache[path_name] = None
for hook in sys.path_hooks:
try:
importer = hook(path_name)
break
except ImportError:
pass
else:
# The following check looks a bit odd. The trick is that
# NullImporter raises ImportError if the supplied path is a
# *valid* directory entry (and hence able to be handled
# by the standard import machinery)
try:
importer = imp.NullImporter(path_name)
except ImportError:
return None
cache[path_name] = importer
return importer
python类path_importer_cache()的实例源码
def get_importer(path_item):
"""Retrieve a PEP 302 importer for the given path item
The returned importer is cached in sys.path_importer_cache
if it was newly created by a path hook.
If there is no importer, a wrapper around the basic import
machinery is returned. This wrapper is never inserted into
the importer cache (None is inserted instead).
The cache (or part of it) can be cleared manually if a
rescan of sys.path_hooks is necessary.
"""
try:
importer = sys.path_importer_cache[path_item]
except KeyError:
for path_hook in sys.path_hooks:
try:
importer = path_hook(path_item)
break
except ImportError:
pass
else:
importer = None
sys.path_importer_cache.setdefault(path_item, importer)
if importer is None:
try:
importer = ImpImporter(path_item)
except ImportError:
importer = None
return importer
def unload(module):
for m in list(sys.modules.keys()):
if m == module or m.startswith(module+"."):
del sys.modules[m]
for p in list(sys.path_importer_cache.keys()):
if module in p:
del sys.path_importer_cache[p]
try:
del module
except:
pass
def uncache_zipdir(path):
"""Ensure that the importer caches dont have stale info for `path`"""
from zipimport import _zip_directory_cache as zdc
_uncache(path, zdc)
_uncache(path, sys.path_importer_cache)
def _get_importer(path_name):
"""Python version of PyImport_GetImporter C API function"""
cache = sys.path_importer_cache
try:
importer = cache[path_name]
except KeyError:
# Not yet cached. Flag as using the
# standard machinery until we finish
# checking the hooks
cache[path_name] = None
for hook in sys.path_hooks:
try:
importer = hook(path_name)
break
except ImportError:
pass
else:
# The following check looks a bit odd. The trick is that
# NullImporter raises ImportError if the supplied path is a
# *valid* directory entry (and hence able to be handled
# by the standard import machinery)
try:
importer = imp.NullImporter(path_name)
except ImportError:
return None
cache[path_name] = importer
return importer
def get_importer(path_item):
"""Retrieve a PEP 302 importer for the given path item
The returned importer is cached in sys.path_importer_cache
if it was newly created by a path hook.
If there is no importer, a wrapper around the basic import
machinery is returned. This wrapper is never inserted into
the importer cache (None is inserted instead).
The cache (or part of it) can be cleared manually if a
rescan of sys.path_hooks is necessary.
"""
try:
importer = sys.path_importer_cache[path_item]
except KeyError:
for path_hook in sys.path_hooks:
try:
importer = path_hook(path_item)
break
except ImportError:
pass
else:
importer = None
sys.path_importer_cache.setdefault(path_item, importer)
if importer is None:
try:
importer = ImpImporter(path_item)
except ImportError:
importer = None
return importer
def unload(module):
for m in list(sys.modules.keys()):
if m == module or m.startswith(module+"."):
del sys.modules[m]
for p in list(sys.path_importer_cache.keys()):
if module in p:
del sys.path_importer_cache[p]
try:
del module
except:
pass
def print_importers():
import sys
import pprint
print('PATH:'),
pprint.pprint(sys.path)
print()
print('IMPORTERS CACHE: {')
for name, cache_value in sys.path_importer_cache.items():
name = name.replace(sys.prefix, '...')
print('%s: %r' % (name, cache_value))
print('}')
def deactivate():
# CAREFUL : Even though we remove the path from sys.path,
# initialized finders will remain in sys.path_importer_cache
# removing metahook
sys.meta_path.pop(get_rospathfinder_index_in_meta_hooks())
# removing path_hook
sys.path_hooks.pop(get_rosdirectoryfinder_index_in_path_hooks())
filefinder2.deactivate()
# Resetting sys.path_importer_cache to get rid of previous importers
sys.path_importer_cache.clear()
def _get_importer(path_name):
"""Python version of PyImport_GetImporter C API function"""
cache = sys.path_importer_cache
try:
importer = cache[path_name]
except KeyError:
# Not yet cached. Flag as using the
# standard machinery until we finish
# checking the hooks
cache[path_name] = None
for hook in sys.path_hooks:
try:
importer = hook(path_name)
break
except ImportError:
pass
else:
# The following check looks a bit odd. The trick is that
# NullImporter throws ImportError if the supplied path is a
# *valid* directory entry (and hence able to be handled
# by the standard import machinery)
try:
importer = imp.NullImporter(path_name)
except ImportError:
return None
cache[path_name] = importer
return importer
def test_sys_path(self):
# Test that sys.path is used when 'path' is None.
# Implicitly tests that sys.path_importer_cache is used.
module = '<test module>'
path = '<test path>'
importer = util.mock_modules(module)
with util.import_state(path_importer_cache={path: importer},
path=[path]):
loader = machinery.PathFinder.find_module(module)
self.assertTrue(loader is importer)
def test_path(self):
# Test that 'path' is used when set.
# Implicitly tests that sys.path_importer_cache is used.
module = '<test module>'
path = '<test path>'
importer = util.mock_modules(module)
with util.import_state(path_importer_cache={path: importer}):
loader = machinery.PathFinder.find_module(module, [path])
self.assertTrue(loader is importer)
def test_path_hooks(self):
# Test that sys.path_hooks is used.
# Test that sys.path_importer_cache is set.
module = '<test module>'
path = '<test path>'
importer = util.mock_modules(module)
hook = import_util.mock_path_hook(path, importer=importer)
with util.import_state(path_hooks=[hook]):
loader = machinery.PathFinder.find_module(module, [path])
self.assertTrue(loader is importer)
self.assertTrue(path in sys.path_importer_cache)
self.assertTrue(sys.path_importer_cache[path] is importer)
def test_path_importer_cache_has_None(self):
# Test that if sys.path_importer_cache has None that None is returned.
clear_cache = {path: None for path in sys.path}
with util.import_state(path_importer_cache=clear_cache):
for name in ('asynchat', 'sys', '<test module>'):
self.assertTrue(machinery.PathFinder.find_module(name) is None)
def get_importer(path_item):
"""Retrieve a PEP 302 importer for the given path item
The returned importer is cached in sys.path_importer_cache
if it was newly created by a path hook.
If there is no importer, a wrapper around the basic import
machinery is returned. This wrapper is never inserted into
the importer cache (None is inserted instead).
The cache (or part of it) can be cleared manually if a
rescan of sys.path_hooks is necessary.
"""
try:
importer = sys.path_importer_cache[path_item]
except KeyError:
for path_hook in sys.path_hooks:
try:
importer = path_hook(path_item)
break
except ImportError:
pass
else:
importer = None
sys.path_importer_cache.setdefault(path_item, importer)
if importer is None:
try:
importer = ImpImporter(path_item)
except ImportError:
importer = None
return importer
def find_module(self, name, path=None):
sys.path_importer_cache.clear()
def install(compiler, suffixes):
filefinder = [(f, i) for i, f in enumerate(sys.path_hooks)
if repr(f).find('.path_hook_for_FileFinder') != -1]
if filefinder:
filefinder, fpos = filefinder[0]
sys.path_hooks[fpos] = PolyFileFinder.path_hook(*(_suffixer(_get_supported_file_loaders())))
sys.path_importer_cache = {}
pkgutil.iter_importer_modules.register(PolyFileFinder, _poly_file_finder_modules)
PolyFileFinder._install(compiler, suffixes)
def __enter__(self):
# suppress writing of .pyc files:
self.prev_dont_write_bytecode = sys.dont_write_bytecode
sys.dont_write_bytecode = True
if self.cleanup_import_caches:
# remember which modules were already loaded before we run the import.
self._backup_dict(sys.modules, 'modules', run_with_empty = False)
self._backup_dict(sys.path_importer_cache, 'path_importer_cache', run_with_empty = True)
def __exit__(self, exc_type, exc_val, exc_tb):
if self.cleanup_import_caches:
# remove all modules which got added to sys.modules in this import, to
# ensure the next time we are here, they get reloaded.
self._restore_dict(sys.modules, 'modules')
self._restore_dict(sys.path_importer_cache, 'path_importer_cache')
sys.dont_write_bytecode = self.prev_dont_write_bytecode
def uncache_zipdir(path):
"""Ensure that the importer caches dont have stale info for `path`"""
from zipimport import _zip_directory_cache as zdc
_uncache(path, zdc)
_uncache(path, sys.path_importer_cache)