importer.pxi 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. import marshal
  2. import sys
  3. from _codecs import utf_8_decode, utf_8_encode
  4. from _frozen_importlib import _call_with_frames_removed, spec_from_loader, BuiltinImporter
  5. from _frozen_importlib_external import _os, _path_isfile, _path_isabs, path_sep, _path_join, _path_split
  6. from _io import FileIO
  7. import __res as __resource
  8. _b = lambda x: x if isinstance(x, bytes) else utf_8_encode(x)[0]
  9. _s = lambda x: x if isinstance(x, str) else utf_8_decode(x)[0]
  10. env_source_root = b'Y_PYTHON_SOURCE_ROOT'
  11. cfg_source_root = b'arcadia-source-root'
  12. env_extended_source_search = b'Y_PYTHON_EXTENDED_SOURCE_SEARCH'
  13. res_ya_ide_venv = b'YA_IDE_VENV'
  14. executable = sys.executable or 'Y_PYTHON'
  15. sys.modules['run_import_hook'] = __resource
  16. def _probe(environ_dict, key, default_value=None):
  17. """ Probe bytes and str variants for environ.
  18. This is because in python3:
  19. * _os (nt) on windows returns str,
  20. * _os (posix) on linux return bytes
  21. For more information check:
  22. * https://github.com/python/cpython/blob/main/Lib/importlib/_bootstrap_external.py#L34
  23. * YA-1700
  24. """
  25. keys = [_b(key), _s(key)]
  26. for key in keys:
  27. if key in environ_dict:
  28. return _b(environ_dict[key])
  29. return _b(default_value) if isinstance(default_value, str) else default_value
  30. # This is the prefix in contrib/tools/python3/Lib/ya.make.
  31. py_prefix = b'py/'
  32. py_prefix_len = len(py_prefix)
  33. YA_IDE_VENV = __resource.find(res_ya_ide_venv)
  34. Y_PYTHON_EXTENDED_SOURCE_SEARCH = _probe(_os.environ, env_extended_source_search) or YA_IDE_VENV
  35. def _init_venv():
  36. if not _path_isabs(executable):
  37. raise RuntimeError(f'path in sys.executable is not absolute: {executable}')
  38. # Creative copy-paste from site.py
  39. exe_dir, _ = _path_split(executable)
  40. site_prefix, _ = _path_split(exe_dir)
  41. libpath = _path_join(site_prefix, 'lib',
  42. 'python%d.%d' % sys.version_info[:2],
  43. 'site-packages')
  44. sys.path.insert(0, libpath)
  45. # emulate site.venv()
  46. sys.prefix = site_prefix
  47. sys.exec_prefix = site_prefix
  48. conf_basename = 'pyvenv.cfg'
  49. candidate_confs = [
  50. conffile for conffile in (
  51. _path_join(exe_dir, conf_basename),
  52. _path_join(site_prefix, conf_basename)
  53. )
  54. if _path_isfile(conffile)
  55. ]
  56. if not candidate_confs:
  57. raise RuntimeError(f'{conf_basename} not found')
  58. virtual_conf = candidate_confs[0]
  59. with FileIO(virtual_conf, 'r') as f:
  60. for line in f:
  61. if b'=' in line:
  62. key, _, value = line.partition(b'=')
  63. key = key.strip().lower()
  64. value = value.strip()
  65. if key == cfg_source_root:
  66. return value
  67. raise RuntimeError(f'{cfg_source_root} key not found in {virtual_conf}')
  68. def _get_source_root():
  69. env_value = _probe(_os.environ, env_source_root)
  70. if env_value or not YA_IDE_VENV:
  71. return env_value
  72. return _init_venv()
  73. Y_PYTHON_SOURCE_ROOT = _get_source_root()
  74. def _print(*xs):
  75. """
  76. This is helpful for debugging, since automatic bytes to str conversion is
  77. not available yet. It is also possible to debug with GDB by breaking on
  78. __Pyx_AddTraceback (with Python GDB pretty printers enabled).
  79. """
  80. parts = []
  81. for s in xs:
  82. if not isinstance(s, (bytes, str)):
  83. s = str(s)
  84. parts.append(_s(s))
  85. sys.stderr.write(' '.join(parts) + '\n')
  86. def file_bytes(path):
  87. # 'open' is not avaiable yet.
  88. with FileIO(path, 'r') as f:
  89. return f.read()
  90. def iter_keys(prefix):
  91. l = len(prefix)
  92. for idx in range(__resource.count()):
  93. key = __resource.key_by_index(idx)
  94. if key.startswith(prefix):
  95. yield key, key[l:]
  96. def iter_py_modules(with_keys=False):
  97. for key, path in iter_keys(b'resfs/file/' + py_prefix):
  98. if path.endswith(b'.py'): # It may also end with '.pyc'.
  99. mod = _s(path[:-3].replace(b'/', b'.'))
  100. if with_keys:
  101. yield key, mod
  102. else:
  103. yield mod
  104. def py_src_key(filename):
  105. return py_prefix + _b(filename)
  106. def iter_prefixes(s):
  107. i = s.find('.')
  108. while i >= 0:
  109. yield s[:i]
  110. i = s.find('.', i + 1)
  111. def resfs_resolve(path):
  112. """
  113. Return the absolute path of a root-relative path if it exists.
  114. """
  115. path = _b(path)
  116. if Y_PYTHON_SOURCE_ROOT:
  117. if not path.startswith(Y_PYTHON_SOURCE_ROOT):
  118. path = _b(path_sep).join((Y_PYTHON_SOURCE_ROOT, path))
  119. if _path_isfile(path):
  120. return path
  121. def resfs_src(key, resfs_file=False):
  122. """
  123. Return the root-relative file path of a resource key.
  124. """
  125. if resfs_file:
  126. key = b'resfs/file/' + _b(key)
  127. return __resource.find(b'resfs/src/' + _b(key))
  128. def resfs_read(path, builtin=None):
  129. """
  130. Return the bytes of the resource file at path, or None.
  131. If builtin is True, do not look for it on the filesystem.
  132. If builtin is False, do not look in the builtin resources.
  133. """
  134. if builtin is not True:
  135. arcpath = resfs_src(path, resfs_file=True)
  136. if arcpath:
  137. fspath = resfs_resolve(arcpath)
  138. if fspath:
  139. return file_bytes(fspath)
  140. if builtin is not False:
  141. return __resource.find(b'resfs/file/' + _b(path))
  142. def resfs_files(prefix=b''):
  143. """
  144. List builtin resource file paths.
  145. """
  146. return [key[11:] for key, _ in iter_keys(b'resfs/file/' + _b(prefix))]
  147. def mod_path(mod):
  148. """
  149. Return the resfs path to the source code of the module with the given name.
  150. """
  151. return py_prefix + _b(mod).replace(b'.', b'/') + b'.py'
  152. class ResourceImporter:
  153. """ A meta_path importer that loads code from built-in resources.
  154. """
  155. def __init__(self):
  156. self.memory = set(iter_py_modules()) # Set of importable module names.
  157. self.source_map = {} # Map from file names to module names.
  158. self._source_name = {} # Map from original to altered module names.
  159. self._package_prefix = ''
  160. self._before_import_callback = None
  161. self._after_import_callback = None
  162. if Y_PYTHON_SOURCE_ROOT and Y_PYTHON_EXTENDED_SOURCE_SEARCH:
  163. self.arcadia_source_finder = ArcadiaSourceFinder(_s(Y_PYTHON_SOURCE_ROOT))
  164. else:
  165. self.arcadia_source_finder = None
  166. for p in list(self.memory) + list(sys.builtin_module_names):
  167. for pp in iter_prefixes(p):
  168. k = pp + '.__init__'
  169. if k not in self.memory:
  170. self.memory.add(k)
  171. def set_callbacks(self, before_import=None, after_import=None):
  172. """Callable[[module], None]"""
  173. self._before_import_callback= before_import
  174. self._after_import_callback = after_import
  175. def for_package(self, name):
  176. import copy
  177. importer = copy.copy(self)
  178. importer._package_prefix = name + '.'
  179. return importer
  180. def _find_mod_path(self, fullname):
  181. """Find arcadia relative path by module name"""
  182. relpath = resfs_src(mod_path(fullname), resfs_file=True)
  183. if relpath or not self.arcadia_source_finder:
  184. return relpath
  185. return self.arcadia_source_finder.get_module_path(fullname)
  186. def find_spec(self, fullname, path=None, target=None):
  187. # Поддежка переопределения стандартного distutils из пакетом из setuptools
  188. if fullname.startswith("distutils."):
  189. setuptools_path = f"{path_sep}setuptools{path_sep}_distutils"
  190. if path and len(path) > 0 and setuptools_path in path[0]:
  191. import importlib
  192. import importlib.abc
  193. setuptools_name = "setuptools._distutils.{}".format(fullname.removeprefix("distutils."))
  194. is_package = self.is_package(setuptools_name)
  195. if is_package:
  196. source = self.get_source(f"{setuptools_name}.__init__")
  197. relpath = self._find_mod_path(f"{setuptools_name}.__init__")
  198. else:
  199. source = self.get_source(setuptools_name)
  200. relpath = self._find_mod_path(setuptools_name)
  201. class DistutilsLoader(importlib.abc.Loader):
  202. def exec_module(self, module):
  203. code = compile(source, _s(relpath), 'exec', dont_inherit=True)
  204. module.__file__ = code.co_filename
  205. if is_package:
  206. module.__path__= [executable + path_sep + setuptools_name.replace('.', path_sep)]
  207. _call_with_frames_removed(exec, code, module.__dict__)
  208. return spec_from_loader(fullname, DistutilsLoader(), is_package=is_package)
  209. try:
  210. is_package = self.is_package(fullname)
  211. except ImportError:
  212. return None
  213. return spec_from_loader(fullname, self, is_package=is_package)
  214. def find_module(self, fullname, path=None):
  215. """For backward compatibility."""
  216. spec = self.find_spec(fullname, path)
  217. return spec.loader if spec is not None else None
  218. def create_module(self, spec):
  219. """Use default semantics for module creation."""
  220. def exec_module(self, module):
  221. code = self.get_code(module.__name__)
  222. module.__file__ = code.co_filename
  223. if self.is_package(module.__name__):
  224. module.__path__= [executable + path_sep + module.__name__.replace('.', path_sep)]
  225. # exec(code, module.__dict__)
  226. # __name__ and __file__ could be overwritten after execution
  227. # So these two things are needed if wee want to be consistent at some point
  228. initial_modname = module.__name__
  229. initial_filename = module.__file__
  230. if self._before_import_callback:
  231. self._before_import_callback(initial_modname, initial_filename)
  232. # “Zero-cost” exceptions are implemented.
  233. # The cost of try statements is almost eliminated when no exception is raised
  234. try:
  235. _call_with_frames_removed(exec, code, module.__dict__)
  236. finally:
  237. if self._after_import_callback:
  238. self._after_import_callback(initial_modname, initial_filename)
  239. # PEP-302 extension 1 of 3: data loader.
  240. def get_data(self, path):
  241. path = _b(path)
  242. abspath = resfs_resolve(path)
  243. if abspath:
  244. return file_bytes(abspath)
  245. path = path.replace(_b('\\'), _b('/'))
  246. data = resfs_read(path, builtin=True)
  247. if data is None:
  248. raise OSError(path) # Y_PYTHON_ENTRY_POINT=:resource_files
  249. return data
  250. # PEP-302 extension 2 of 3: get __file__ without importing.
  251. def get_filename(self, fullname):
  252. modname = fullname
  253. if self.is_package(fullname):
  254. fullname += '.__init__'
  255. relpath = self._find_mod_path(fullname)
  256. if isinstance(relpath, bytes):
  257. relpath = _s(relpath)
  258. return relpath or modname
  259. # PEP-302 extension 3 of 3: packaging introspection.
  260. # Used by `linecache` (while printing tracebacks) unless module filename
  261. # exists on the filesystem.
  262. def get_source(self, fullname):
  263. fullname = self._source_name.get(fullname) or fullname
  264. if self.is_package(fullname):
  265. fullname += '.__init__'
  266. relpath = self.get_filename(fullname)
  267. if relpath:
  268. abspath = resfs_resolve(relpath)
  269. if abspath:
  270. return _s(file_bytes(abspath))
  271. data = resfs_read(mod_path(fullname))
  272. return _s(data) if data else ''
  273. def get_code(self, fullname):
  274. modname = fullname
  275. if self.is_package(fullname):
  276. fullname += '.__init__'
  277. path = mod_path(fullname)
  278. relpath = self._find_mod_path(fullname)
  279. if relpath:
  280. abspath = resfs_resolve(relpath)
  281. if abspath:
  282. data = file_bytes(abspath)
  283. return compile(data, _s(abspath), 'exec', dont_inherit=True)
  284. yapyc_path = path + b'.yapyc3'
  285. yapyc_data = resfs_read(yapyc_path, builtin=True)
  286. if yapyc_data:
  287. return marshal.loads(yapyc_data)
  288. else:
  289. py_data = resfs_read(path, builtin=True)
  290. if py_data:
  291. return compile(py_data, _s(relpath), 'exec', dont_inherit=True)
  292. else:
  293. # This covers packages with no __init__.py in resources.
  294. return compile('', modname, 'exec', dont_inherit=True)
  295. def is_package(self, fullname):
  296. if fullname in self.memory:
  297. return False
  298. if fullname + '.__init__' in self.memory:
  299. return True
  300. if self.arcadia_source_finder:
  301. return self.arcadia_source_finder.is_package(fullname)
  302. raise ImportError(fullname)
  303. # Extension for contrib/python/coverage.
  304. def file_source(self, filename):
  305. """
  306. Return the key of the module source by its resource path.
  307. """
  308. if not self.source_map:
  309. for key, mod in iter_py_modules(with_keys=True):
  310. path = self.get_filename(mod)
  311. self.source_map[path] = key
  312. if filename in self.source_map:
  313. return self.source_map[filename]
  314. if resfs_read(filename, builtin=True) is not None:
  315. return b'resfs/file/' + _b(filename)
  316. return b''
  317. # Extension for pkgutil.iter_modules.
  318. def iter_modules(self, prefix=''):
  319. import re
  320. rx = re.compile(re.escape(self._package_prefix) + r'([^.]+)(\.__init__)?$')
  321. for p in self.memory:
  322. m = rx.match(p)
  323. if m:
  324. yield prefix + m.group(1), m.group(2) is not None
  325. if self.arcadia_source_finder:
  326. for m in self.arcadia_source_finder.iter_modules(self._package_prefix, prefix):
  327. yield m
  328. def get_resource_reader(self, fullname):
  329. import os
  330. path = os.path.dirname(self.get_filename(fullname))
  331. return _ResfsResourceReader(self, path)
  332. class _ResfsResourceReader:
  333. def __init__(self, importer, path):
  334. self.importer = importer
  335. self.path = path
  336. def open_resource(self, resource):
  337. path = f'{self.path}/{resource}'
  338. from io import BytesIO
  339. try:
  340. return BytesIO(self.importer.get_data(path))
  341. except OSError:
  342. raise FileNotFoundError(path)
  343. def resource_path(self, resource):
  344. # All resources are in the binary file, so there is no path to the file.
  345. # Raising FileNotFoundError tells the higher level API to extract the
  346. # binary data and create a temporary file.
  347. raise FileNotFoundError
  348. def is_resource(self, name):
  349. path = f'{self.path}/{name}'
  350. try:
  351. self.importer.get_data(path)
  352. except OSError:
  353. return False
  354. return True
  355. def contents(self):
  356. subdirs_seen = set()
  357. len_path = len(self.path) + 1 # path + /
  358. for key in resfs_files(f"{self.path}/"):
  359. relative = key[len_path:]
  360. res_or_subdir, *other = relative.split(b'/')
  361. if not other:
  362. yield _s(res_or_subdir)
  363. elif res_or_subdir not in subdirs_seen:
  364. subdirs_seen.add(res_or_subdir)
  365. yield _s(res_or_subdir)
  366. def files(self):
  367. import sitecustomize
  368. return sitecustomize.ArcadiaResourceContainer(f"resfs/file/{self.path}/")
  369. class BuiltinSubmoduleImporter(BuiltinImporter):
  370. @classmethod
  371. def find_spec(cls, fullname, path=None, target=None):
  372. if path is not None:
  373. return super().find_spec(fullname, None, target)
  374. else:
  375. return None
  376. class ArcadiaSourceFinder:
  377. """
  378. Search modules and packages in arcadia source tree.
  379. See https://wiki.yandex-team.ru/devtools/extended-python-source-search/ for details
  380. """
  381. NAMESPACE_PREFIX = b'py/namespace/'
  382. PY_EXT = '.py'
  383. YA_MAKE = 'ya.make'
  384. S_IFDIR = 0o040000
  385. def __init__(self, source_root):
  386. self.source_root = source_root
  387. self.module_path_cache = {'': set()}
  388. for key, dirty_path in iter_keys(self.NAMESPACE_PREFIX):
  389. # dirty_path contains unique prefix to prevent repeatable keys in the resource storage
  390. path = dirty_path.split(b'/', 1)[1]
  391. namespaces = __resource.find(key).split(b':')
  392. for n in namespaces:
  393. package_name = _s(n.rstrip(b'.'))
  394. self.module_path_cache.setdefault(package_name, set()).add(_s(path))
  395. # Fill parents with default empty path set if parent doesn't exist in the cache yet
  396. while package_name:
  397. package_name = package_name.rpartition('.')[0]
  398. if package_name in self.module_path_cache:
  399. break
  400. self.module_path_cache.setdefault(package_name, set())
  401. for package_name in self.module_path_cache.keys():
  402. self._add_parent_dirs(package_name, visited=set())
  403. def get_module_path(self, fullname):
  404. """
  405. Find file path for module 'fullname'.
  406. For packages caller pass fullname as 'package.__init__'.
  407. Return None if nothing is found.
  408. """
  409. try:
  410. if not self.is_package(fullname):
  411. return _b(self._cache_module_path(fullname))
  412. except ImportError:
  413. pass
  414. def is_package(self, fullname):
  415. """Check if fullname is a package. Raise ImportError if fullname is not found"""
  416. path = self._cache_module_path(fullname)
  417. if isinstance(path, set):
  418. return True
  419. if isinstance(path, str):
  420. return False
  421. raise ImportError(fullname)
  422. def iter_modules(self, package_prefix, prefix):
  423. paths = self._cache_module_path(package_prefix.rstrip('.'))
  424. if paths is not None:
  425. # Note: it's ok to yield duplicates because pkgutil discards them
  426. # Yield from cache
  427. import re
  428. rx = re.compile(re.escape(package_prefix) + r'([^.]+)$')
  429. # Save result to temporary list to prevent 'RuntimeError: dictionary changed size during iteration'
  430. found = []
  431. for mod, path in self.module_path_cache.items():
  432. if path is not None:
  433. m = rx.match(mod)
  434. if m:
  435. found.append((prefix + m.group(1), self.is_package(mod)))
  436. yield from found
  437. # Yield from file system
  438. for path in paths:
  439. abs_path = _path_join(self.source_root, path)
  440. for dir_item in _os.listdir(abs_path):
  441. if self._path_is_simple_dir(_path_join(abs_path, dir_item)):
  442. yield prefix + dir_item, True
  443. elif dir_item.endswith(self.PY_EXT) and _path_isfile(_path_join(abs_path, dir_item)):
  444. yield prefix + dir_item[:-len(self.PY_EXT)], False
  445. def _isdir(self, path):
  446. """ Unlike _path_isdir() this function don't follow symlink """
  447. try:
  448. stat_info = _os.lstat(path)
  449. except OSError:
  450. return False
  451. return (stat_info.st_mode & 0o170000) == self.S_IFDIR
  452. def _path_is_simple_dir(self, abs_path):
  453. """
  454. Check if path is a directory but doesn't contain ya.make file.
  455. We don't want to steal directory from nested project and treat it as a package
  456. """
  457. return self._isdir(abs_path) and not _path_isfile(_path_join(abs_path, self.YA_MAKE))
  458. def _find_module_in_paths(self, find_package_only, paths, module):
  459. """Auxiliary method. See _cache_module_path() for details"""
  460. if paths:
  461. package_paths = set()
  462. for path in paths:
  463. rel_path = _path_join(path, module)
  464. if not find_package_only:
  465. # Check if file_path is a module
  466. module_path = rel_path + self.PY_EXT
  467. if _path_isfile(_path_join(self.source_root, module_path)):
  468. return module_path
  469. # Check if file_path is a package
  470. if self._path_is_simple_dir(_path_join(self.source_root, rel_path)):
  471. package_paths.add(rel_path)
  472. if package_paths:
  473. return package_paths
  474. def _cache_module_path(self, fullname, find_package_only=False):
  475. """
  476. Find module path or package directory paths and save result in the cache
  477. find_package_only=True - don't try to find module
  478. Returns:
  479. List of relative package paths - for a package
  480. Relative module path - for a module
  481. None - module or package is not found
  482. """
  483. if fullname not in self.module_path_cache:
  484. parent, _, tail = fullname.rpartition('.')
  485. parent_paths = self._cache_module_path(parent, find_package_only=True)
  486. self.module_path_cache[fullname] = self._find_module_in_paths(find_package_only, parent_paths, tail)
  487. return self.module_path_cache[fullname]
  488. def _add_parent_dirs(self, package_name, visited):
  489. if not package_name or package_name in visited:
  490. return
  491. visited.add(package_name)
  492. parent, _, tail = package_name.rpartition('.')
  493. self._add_parent_dirs(parent, visited)
  494. paths = self.module_path_cache[package_name]
  495. for parent_path in self.module_path_cache[parent]:
  496. rel_path = _path_join(parent_path, tail)
  497. if self._path_is_simple_dir(_path_join(self.source_root, rel_path)):
  498. paths.add(rel_path)
  499. def excepthook(*args, **kws):
  500. # traceback module cannot be imported at module level, because interpreter
  501. # is not fully initialized yet
  502. import traceback
  503. return traceback.print_exception(*args, **kws)
  504. importer = ResourceImporter()
  505. def executable_path_hook(path):
  506. if path == executable:
  507. return importer
  508. if path.startswith(executable + path_sep):
  509. return importer.for_package(path[len(executable + path_sep):].replace(path_sep, '.'))
  510. raise ImportError(path)
  511. def get_path0():
  512. """
  513. An incomplete and simplified version of _PyPathConfig_ComputeSysPath0.
  514. We need this to somewhat properly emulate the behaviour of a normal python interpreter
  515. when using ya ide venv.
  516. """
  517. if not sys.argv:
  518. return
  519. argv0 = sys.argv[0]
  520. have_module_arg = argv0 == '-m'
  521. if have_module_arg:
  522. return _os.getcwd()
  523. if YA_IDE_VENV:
  524. sys.meta_path.append(importer)
  525. sys.meta_path.append(BuiltinSubmoduleImporter)
  526. if executable not in sys.path:
  527. sys.path.append(executable)
  528. path0 = get_path0()
  529. if path0 is not None:
  530. sys.path.insert(0, path0)
  531. sys.path_hooks.append(executable_path_hook)
  532. else:
  533. sys.meta_path.insert(0, BuiltinSubmoduleImporter)
  534. sys.meta_path.insert(0, importer)
  535. if executable not in sys.path:
  536. sys.path.insert(0, executable)
  537. sys.path_hooks.insert(0, executable_path_hook)
  538. sys.path_importer_cache[executable] = importer
  539. # Indicator that modules and resources are built-in rather than on the file system.
  540. sys.is_standalone_binary = True
  541. sys.frozen = True
  542. # Set of names of importable modules.
  543. sys.extra_modules = importer.memory
  544. # Use custom implementation of traceback printer.
  545. # Built-in printer (PyTraceBack_Print) does not support custom module loaders
  546. sys.excepthook = excepthook