importer.pxi 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. @staticmethod
  333. def find_distributions(*args, **kwargs):
  334. """
  335. Find distributions.
  336. Return an iterable of all Distribution instances capable of
  337. loading the metadata for packages matching ``context.name``
  338. (or all names if ``None`` indicated) along the paths in the list
  339. of directories ``context.path``.
  340. """
  341. from sitecustomize import MetadataArcadiaFinder
  342. return MetadataArcadiaFinder.find_distributions(*args, **kwargs)
  343. class _ResfsResourceReader:
  344. def __init__(self, importer, path):
  345. self.importer = importer
  346. self.path = path
  347. def open_resource(self, resource):
  348. path = f'{self.path}/{resource}'
  349. from io import BytesIO
  350. try:
  351. return BytesIO(self.importer.get_data(path))
  352. except OSError:
  353. raise FileNotFoundError(path)
  354. def resource_path(self, resource):
  355. # All resources are in the binary file, so there is no path to the file.
  356. # Raising FileNotFoundError tells the higher level API to extract the
  357. # binary data and create a temporary file.
  358. raise FileNotFoundError
  359. def is_resource(self, name):
  360. path = f'{self.path}/{name}'
  361. try:
  362. self.importer.get_data(path)
  363. except OSError:
  364. return False
  365. return True
  366. def contents(self):
  367. subdirs_seen = set()
  368. len_path = len(self.path) + 1 # path + /
  369. for key in resfs_files(f"{self.path}/"):
  370. relative = key[len_path:]
  371. res_or_subdir, *other = relative.split(b'/')
  372. if not other:
  373. yield _s(res_or_subdir)
  374. elif res_or_subdir not in subdirs_seen:
  375. subdirs_seen.add(res_or_subdir)
  376. yield _s(res_or_subdir)
  377. def files(self):
  378. import sitecustomize
  379. return sitecustomize.ArcadiaResourceContainer(f"resfs/file/{self.path}/")
  380. class BuiltinSubmoduleImporter(BuiltinImporter):
  381. @classmethod
  382. def find_spec(cls, fullname, path=None, target=None):
  383. if path is not None:
  384. return super().find_spec(fullname, None, target)
  385. else:
  386. return None
  387. class ArcadiaSourceFinder:
  388. """
  389. Search modules and packages in arcadia source tree.
  390. See https://wiki.yandex-team.ru/devtools/extended-python-source-search/ for details
  391. """
  392. NAMESPACE_PREFIX = b'py/namespace/'
  393. PY_EXT = '.py'
  394. YA_MAKE = 'ya.make'
  395. S_IFDIR = 0o040000
  396. def __init__(self, source_root):
  397. self.source_root = source_root
  398. self.module_path_cache = {'': set()}
  399. for key, dirty_path in iter_keys(self.NAMESPACE_PREFIX):
  400. # dirty_path contains unique prefix to prevent repeatable keys in the resource storage
  401. path = dirty_path.split(b'/', 1)[1]
  402. namespaces = __resource.find(key).split(b':')
  403. for n in namespaces:
  404. package_name = _s(n.rstrip(b'.'))
  405. self.module_path_cache.setdefault(package_name, set()).add(_s(path))
  406. # Fill parents with default empty path set if parent doesn't exist in the cache yet
  407. while package_name:
  408. package_name = package_name.rpartition('.')[0]
  409. if package_name in self.module_path_cache:
  410. break
  411. self.module_path_cache.setdefault(package_name, set())
  412. for package_name in self.module_path_cache.keys():
  413. self._add_parent_dirs(package_name, visited=set())
  414. def get_module_path(self, fullname):
  415. """
  416. Find file path for module 'fullname'.
  417. For packages caller pass fullname as 'package.__init__'.
  418. Return None if nothing is found.
  419. """
  420. try:
  421. if not self.is_package(fullname):
  422. return _b(self._cache_module_path(fullname))
  423. except ImportError:
  424. pass
  425. def is_package(self, fullname):
  426. """Check if fullname is a package. Raise ImportError if fullname is not found"""
  427. path = self._cache_module_path(fullname)
  428. if isinstance(path, set):
  429. return True
  430. if isinstance(path, str):
  431. return False
  432. raise ImportError(fullname)
  433. def iter_modules(self, package_prefix, prefix):
  434. paths = self._cache_module_path(package_prefix.rstrip('.'))
  435. if paths is not None:
  436. # Note: it's ok to yield duplicates because pkgutil discards them
  437. # Yield from cache
  438. import re
  439. rx = re.compile(re.escape(package_prefix) + r'([^.]+)$')
  440. # Save result to temporary list to prevent 'RuntimeError: dictionary changed size during iteration'
  441. found = []
  442. for mod, path in self.module_path_cache.items():
  443. if path is not None:
  444. m = rx.match(mod)
  445. if m:
  446. found.append((prefix + m.group(1), self.is_package(mod)))
  447. yield from found
  448. # Yield from file system
  449. for path in paths:
  450. abs_path = _path_join(self.source_root, path)
  451. for dir_item in _os.listdir(abs_path):
  452. if self._path_is_simple_dir(_path_join(abs_path, dir_item)):
  453. yield prefix + dir_item, True
  454. elif dir_item.endswith(self.PY_EXT) and _path_isfile(_path_join(abs_path, dir_item)):
  455. yield prefix + dir_item[:-len(self.PY_EXT)], False
  456. def _isdir(self, path):
  457. """ Unlike _path_isdir() this function don't follow symlink """
  458. try:
  459. stat_info = _os.lstat(path)
  460. except OSError:
  461. return False
  462. return (stat_info.st_mode & 0o170000) == self.S_IFDIR
  463. def _path_is_simple_dir(self, abs_path):
  464. """
  465. Check if path is a directory but doesn't contain ya.make file.
  466. We don't want to steal directory from nested project and treat it as a package
  467. """
  468. return self._isdir(abs_path) and not _path_isfile(_path_join(abs_path, self.YA_MAKE))
  469. def _find_module_in_paths(self, find_package_only, paths, module):
  470. """Auxiliary method. See _cache_module_path() for details"""
  471. if paths:
  472. package_paths = set()
  473. for path in paths:
  474. rel_path = _path_join(path, module)
  475. if not find_package_only:
  476. # Check if file_path is a module
  477. module_path = rel_path + self.PY_EXT
  478. if _path_isfile(_path_join(self.source_root, module_path)):
  479. return module_path
  480. # Check if file_path is a package
  481. if self._path_is_simple_dir(_path_join(self.source_root, rel_path)):
  482. package_paths.add(rel_path)
  483. if package_paths:
  484. return package_paths
  485. def _cache_module_path(self, fullname, find_package_only=False):
  486. """
  487. Find module path or package directory paths and save result in the cache
  488. find_package_only=True - don't try to find module
  489. Returns:
  490. List of relative package paths - for a package
  491. Relative module path - for a module
  492. None - module or package is not found
  493. """
  494. if fullname not in self.module_path_cache:
  495. parent, _, tail = fullname.rpartition('.')
  496. parent_paths = self._cache_module_path(parent, find_package_only=True)
  497. self.module_path_cache[fullname] = self._find_module_in_paths(find_package_only, parent_paths, tail)
  498. return self.module_path_cache[fullname]
  499. def _add_parent_dirs(self, package_name, visited):
  500. if not package_name or package_name in visited:
  501. return
  502. visited.add(package_name)
  503. parent, _, tail = package_name.rpartition('.')
  504. self._add_parent_dirs(parent, visited)
  505. paths = self.module_path_cache[package_name]
  506. for parent_path in self.module_path_cache[parent]:
  507. rel_path = _path_join(parent_path, tail)
  508. if self._path_is_simple_dir(_path_join(self.source_root, rel_path)):
  509. paths.add(rel_path)
  510. def excepthook(*args, **kws):
  511. # traceback module cannot be imported at module level, because interpreter
  512. # is not fully initialized yet
  513. import traceback
  514. return traceback.print_exception(*args, **kws)
  515. importer = ResourceImporter()
  516. def executable_path_hook(path):
  517. if path == executable:
  518. return importer
  519. if path.startswith(executable + path_sep):
  520. return importer.for_package(path[len(executable + path_sep):].replace(path_sep, '.'))
  521. raise ImportError(path)
  522. def get_path0():
  523. """
  524. An incomplete and simplified version of _PyPathConfig_ComputeSysPath0.
  525. We need this to somewhat properly emulate the behaviour of a normal python interpreter
  526. when using ya ide venv.
  527. """
  528. if not sys.argv:
  529. return
  530. argv0 = sys.argv[0]
  531. have_module_arg = argv0 == '-m'
  532. if have_module_arg:
  533. return _os.getcwd()
  534. if YA_IDE_VENV:
  535. sys.meta_path.append(importer)
  536. sys.meta_path.append(BuiltinSubmoduleImporter)
  537. if executable not in sys.path:
  538. sys.path.append(executable)
  539. path0 = get_path0()
  540. if path0 is not None:
  541. sys.path.insert(0, path0)
  542. sys.path_hooks.append(executable_path_hook)
  543. else:
  544. sys.meta_path.insert(0, BuiltinSubmoduleImporter)
  545. sys.meta_path.insert(0, importer)
  546. if executable not in sys.path:
  547. sys.path.insert(0, executable)
  548. sys.path_hooks.insert(0, executable_path_hook)
  549. sys.path_importer_cache[executable] = importer
  550. # Indicator that modules and resources are built-in rather than on the file system.
  551. sys.is_standalone_binary = True
  552. sys.frozen = True
  553. # Set of names of importable modules.
  554. sys.extra_modules = importer.memory
  555. # Use custom implementation of traceback printer.
  556. # Built-in printer (PyTraceBack_Print) does not support custom module loaders
  557. sys.excepthook = excepthook