site.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. """Append module search paths for third-party packages to sys.path.
  2. ****************************************************************
  3. * This module is automatically imported during initialization. *
  4. ****************************************************************
  5. This will append site-specific paths to the module search path. On
  6. Unix (including Mac OSX), it starts with sys.prefix and
  7. sys.exec_prefix (if different) and appends
  8. lib/python<version>/site-packages.
  9. On other platforms (such as Windows), it tries each of the
  10. prefixes directly, as well as with lib/site-packages appended. The
  11. resulting directories, if they exist, are appended to sys.path, and
  12. also inspected for path configuration files.
  13. If a file named "pyvenv.cfg" exists one directory above sys.executable,
  14. sys.prefix and sys.exec_prefix are set to that directory and
  15. it is also checked for site-packages (sys.base_prefix and
  16. sys.base_exec_prefix will always be the "real" prefixes of the Python
  17. installation). If "pyvenv.cfg" (a bootstrap configuration file) contains
  18. the key "include-system-site-packages" set to anything other than "false"
  19. (case-insensitive), the system-level prefixes will still also be
  20. searched for site-packages; otherwise they won't.
  21. All of the resulting site-specific directories, if they exist, are
  22. appended to sys.path, and also inspected for path configuration
  23. files.
  24. A path configuration file is a file whose name has the form
  25. <package>.pth; its contents are additional directories (one per line)
  26. to be added to sys.path. Non-existing directories (or
  27. non-directories) are never added to sys.path; no directory is added to
  28. sys.path more than once. Blank lines and lines beginning with
  29. '#' are skipped. Lines starting with 'import' are executed.
  30. For example, suppose sys.prefix and sys.exec_prefix are set to
  31. /usr/local and there is a directory /usr/local/lib/python2.5/site-packages
  32. with three subdirectories, foo, bar and spam, and two path
  33. configuration files, foo.pth and bar.pth. Assume foo.pth contains the
  34. following:
  35. # foo package configuration
  36. foo
  37. bar
  38. bletch
  39. and bar.pth contains:
  40. # bar package configuration
  41. bar
  42. Then the following directories are added to sys.path, in this order:
  43. /usr/local/lib/python2.5/site-packages/bar
  44. /usr/local/lib/python2.5/site-packages/foo
  45. Note that bletch is omitted because it doesn't exist; bar precedes foo
  46. because bar.pth comes alphabetically before foo.pth; and spam is
  47. omitted because it is not mentioned in either path configuration file.
  48. The readline module is also automatically configured to enable
  49. completion for systems that support it. This can be overridden in
  50. sitecustomize, usercustomize or PYTHONSTARTUP. Starting Python in
  51. isolated mode (-I) disables automatic readline configuration.
  52. After these operations, an attempt is made to import a module
  53. named sitecustomize, which can perform arbitrary additional
  54. site-specific customizations. If this import fails with an
  55. ImportError exception, it is silently ignored.
  56. """
  57. import sys
  58. import os
  59. import builtins
  60. import _sitebuiltins
  61. import io
  62. import stat
  63. # Prefixes for site-packages; add additional prefixes like /usr/local here
  64. PREFIXES = [sys.prefix, sys.exec_prefix]
  65. # Enable per user site-packages directory
  66. # set it to False to disable the feature or True to force the feature
  67. ENABLE_USER_SITE = None
  68. # for distutils.commands.install
  69. # These values are initialized by the getuserbase() and getusersitepackages()
  70. # functions, through the main() function when Python starts.
  71. USER_SITE = None
  72. USER_BASE = None
  73. def _trace(message):
  74. if sys.flags.verbose:
  75. print(message, file=sys.stderr)
  76. def makepath(*paths):
  77. dir = os.path.join(*paths)
  78. try:
  79. dir = os.path.abspath(dir)
  80. except OSError:
  81. pass
  82. return dir, os.path.normcase(dir)
  83. def abs_paths():
  84. """Set all module __file__ and __cached__ attributes to an absolute path"""
  85. for m in set(sys.modules.values()):
  86. loader_module = None
  87. try:
  88. loader_module = m.__loader__.__module__
  89. except AttributeError:
  90. try:
  91. loader_module = m.__spec__.loader.__module__
  92. except AttributeError:
  93. pass
  94. if loader_module not in {'_frozen_importlib', '_frozen_importlib_external'}:
  95. continue # don't mess with a PEP 302-supplied __file__
  96. try:
  97. m.__file__ = os.path.abspath(m.__file__)
  98. except (AttributeError, OSError, TypeError):
  99. pass
  100. try:
  101. m.__cached__ = os.path.abspath(m.__cached__)
  102. except (AttributeError, OSError, TypeError):
  103. pass
  104. def removeduppaths():
  105. """ Remove duplicate entries from sys.path along with making them
  106. absolute"""
  107. # This ensures that the initial path provided by the interpreter contains
  108. # only absolute pathnames, even if we're running from the build directory.
  109. L = []
  110. known_paths = set()
  111. for dir in sys.path:
  112. # Filter out duplicate paths (on case-insensitive file systems also
  113. # if they only differ in case); turn relative paths into absolute
  114. # paths.
  115. dir, dircase = makepath(dir)
  116. if dircase not in known_paths:
  117. L.append(dir)
  118. known_paths.add(dircase)
  119. sys.path[:] = L
  120. return known_paths
  121. def _init_pathinfo():
  122. """Return a set containing all existing file system items from sys.path."""
  123. d = set()
  124. for item in sys.path:
  125. try:
  126. if os.path.exists(item):
  127. _, itemcase = makepath(item)
  128. d.add(itemcase)
  129. except TypeError:
  130. continue
  131. return d
  132. def addpackage(sitedir, name, known_paths):
  133. """Process a .pth file within the site-packages directory:
  134. For each line in the file, either combine it with sitedir to a path
  135. and add that to known_paths, or execute it if it starts with 'import '.
  136. """
  137. if known_paths is None:
  138. known_paths = _init_pathinfo()
  139. reset = True
  140. else:
  141. reset = False
  142. fullname = os.path.join(sitedir, name)
  143. try:
  144. st = os.lstat(fullname)
  145. except OSError:
  146. return
  147. if ((getattr(st, 'st_flags', 0) & stat.UF_HIDDEN) or
  148. (getattr(st, 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_HIDDEN)):
  149. _trace(f"Skipping hidden .pth file: {fullname!r}")
  150. return
  151. _trace(f"Processing .pth file: {fullname!r}")
  152. try:
  153. with io.open_code(fullname) as f:
  154. pth_content = f.read()
  155. except OSError:
  156. return
  157. try:
  158. # Accept BOM markers in .pth files as we do in source files
  159. # (Windows PowerShell 5.1 makes it hard to emit UTF-8 files without a BOM)
  160. pth_content = pth_content.decode("utf-8-sig")
  161. except UnicodeDecodeError:
  162. # Fallback to locale encoding for backward compatibility.
  163. # We will deprecate this fallback in the future.
  164. import locale
  165. pth_content = pth_content.decode(locale.getencoding())
  166. _trace(f"Cannot read {fullname!r} as UTF-8. "
  167. f"Using fallback encoding {locale.getencoding()!r}")
  168. for n, line in enumerate(pth_content.splitlines(), 1):
  169. if line.startswith("#"):
  170. continue
  171. if line.strip() == "":
  172. continue
  173. try:
  174. if line.startswith(("import ", "import\t")):
  175. exec(line)
  176. continue
  177. line = line.rstrip()
  178. dir, dircase = makepath(sitedir, line)
  179. if dircase not in known_paths and os.path.exists(dir):
  180. sys.path.append(dir)
  181. known_paths.add(dircase)
  182. except Exception as exc:
  183. print(f"Error processing line {n:d} of {fullname}:\n",
  184. file=sys.stderr)
  185. import traceback
  186. for record in traceback.format_exception(exc):
  187. for line in record.splitlines():
  188. print(' '+line, file=sys.stderr)
  189. print("\nRemainder of file ignored", file=sys.stderr)
  190. break
  191. if reset:
  192. known_paths = None
  193. return known_paths
  194. def addsitedir(sitedir, known_paths=None):
  195. """Add 'sitedir' argument to sys.path if missing and handle .pth files in
  196. 'sitedir'"""
  197. _trace(f"Adding directory: {sitedir!r}")
  198. if known_paths is None:
  199. known_paths = _init_pathinfo()
  200. reset = True
  201. else:
  202. reset = False
  203. sitedir, sitedircase = makepath(sitedir)
  204. if not sitedircase in known_paths:
  205. sys.path.append(sitedir) # Add path component
  206. known_paths.add(sitedircase)
  207. try:
  208. names = os.listdir(sitedir)
  209. except OSError:
  210. return
  211. names = [name for name in names
  212. if name.endswith(".pth") and not name.startswith(".")]
  213. for name in sorted(names):
  214. addpackage(sitedir, name, known_paths)
  215. if reset:
  216. known_paths = None
  217. return known_paths
  218. def check_enableusersite():
  219. """Check if user site directory is safe for inclusion
  220. The function tests for the command line flag (including environment var),
  221. process uid/gid equal to effective uid/gid.
  222. None: Disabled for security reasons
  223. False: Disabled by user (command line option)
  224. True: Safe and enabled
  225. """
  226. if sys.flags.no_user_site:
  227. return False
  228. if hasattr(os, "getuid") and hasattr(os, "geteuid"):
  229. # check process uid == effective uid
  230. if os.geteuid() != os.getuid():
  231. return None
  232. if hasattr(os, "getgid") and hasattr(os, "getegid"):
  233. # check process gid == effective gid
  234. if os.getegid() != os.getgid():
  235. return None
  236. return True
  237. # NOTE: sysconfig and it's dependencies are relatively large but site module
  238. # needs very limited part of them.
  239. # To speedup startup time, we have copy of them.
  240. #
  241. # See https://bugs.python.org/issue29585
  242. # Copy of sysconfig._getuserbase()
  243. def _getuserbase():
  244. env_base = os.environ.get("PYTHONUSERBASE", None)
  245. if env_base:
  246. return env_base
  247. # Emscripten, VxWorks, and WASI have no home directories
  248. if sys.platform in {"emscripten", "vxworks", "wasi"}:
  249. return None
  250. def joinuser(*args):
  251. return os.path.expanduser(os.path.join(*args))
  252. if os.name == "nt":
  253. base = os.environ.get("APPDATA") or "~"
  254. return joinuser(base, "Python")
  255. if sys.platform == "darwin" and sys._framework:
  256. return joinuser("~", "Library", sys._framework,
  257. "%d.%d" % sys.version_info[:2])
  258. return joinuser("~", ".local")
  259. # Same to sysconfig.get_path('purelib', os.name+'_user')
  260. def _get_path(userbase):
  261. version = sys.version_info
  262. if os.name == 'nt':
  263. ver_nodot = sys.winver.replace('.', '')
  264. return f'{userbase}\\Python{ver_nodot}\\site-packages'
  265. if sys.platform == 'darwin' and sys._framework:
  266. return f'{userbase}/lib/python/site-packages'
  267. return f'{userbase}/lib/python{version[0]}.{version[1]}/site-packages'
  268. def getuserbase():
  269. """Returns the `user base` directory path.
  270. The `user base` directory can be used to store data. If the global
  271. variable ``USER_BASE`` is not initialized yet, this function will also set
  272. it.
  273. """
  274. global USER_BASE
  275. if USER_BASE is None:
  276. USER_BASE = _getuserbase()
  277. return USER_BASE
  278. def getusersitepackages():
  279. """Returns the user-specific site-packages directory path.
  280. If the global variable ``USER_SITE`` is not initialized yet, this
  281. function will also set it.
  282. """
  283. global USER_SITE, ENABLE_USER_SITE
  284. userbase = getuserbase() # this will also set USER_BASE
  285. if USER_SITE is None:
  286. if userbase is None:
  287. ENABLE_USER_SITE = False # disable user site and return None
  288. else:
  289. USER_SITE = _get_path(userbase)
  290. return USER_SITE
  291. def addusersitepackages(known_paths):
  292. """Add a per user site-package to sys.path
  293. Each user has its own python directory with site-packages in the
  294. home directory.
  295. """
  296. # get the per user site-package path
  297. # this call will also make sure USER_BASE and USER_SITE are set
  298. _trace("Processing user site-packages")
  299. user_site = getusersitepackages()
  300. if ENABLE_USER_SITE and os.path.isdir(user_site):
  301. addsitedir(user_site, known_paths)
  302. return known_paths
  303. def getsitepackages(prefixes=None):
  304. """Returns a list containing all global site-packages directories.
  305. For each directory present in ``prefixes`` (or the global ``PREFIXES``),
  306. this function will find its `site-packages` subdirectory depending on the
  307. system environment, and will return a list of full paths.
  308. """
  309. sitepackages = []
  310. seen = set()
  311. if prefixes is None:
  312. prefixes = PREFIXES
  313. for prefix in prefixes:
  314. if not prefix or prefix in seen:
  315. continue
  316. seen.add(prefix)
  317. if os.sep == '/':
  318. libdirs = [sys.platlibdir]
  319. if sys.platlibdir != "lib":
  320. libdirs.append("lib")
  321. for libdir in libdirs:
  322. path = os.path.join(prefix, libdir,
  323. "python%d.%d" % sys.version_info[:2],
  324. "site-packages")
  325. sitepackages.append(path)
  326. else:
  327. sitepackages.append(prefix)
  328. sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
  329. return sitepackages
  330. def addsitepackages(known_paths, prefixes=None):
  331. """Add site-packages to sys.path"""
  332. _trace("Processing global site-packages")
  333. for sitedir in getsitepackages(prefixes):
  334. if os.path.isdir(sitedir):
  335. addsitedir(sitedir, known_paths)
  336. return known_paths
  337. def setquit():
  338. """Define new builtins 'quit' and 'exit'.
  339. These are objects which make the interpreter exit when called.
  340. The repr of each object contains a hint at how it works.
  341. """
  342. if os.sep == '\\':
  343. eof = 'Ctrl-Z plus Return'
  344. else:
  345. eof = 'Ctrl-D (i.e. EOF)'
  346. builtins.quit = _sitebuiltins.Quitter('quit', eof)
  347. builtins.exit = _sitebuiltins.Quitter('exit', eof)
  348. def setcopyright():
  349. """Set 'copyright' and 'credits' in builtins"""
  350. builtins.copyright = _sitebuiltins._Printer("copyright", sys.copyright)
  351. builtins.credits = _sitebuiltins._Printer("credits", """\
  352. Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  353. for supporting Python development. See www.python.org for more information.""")
  354. files, dirs = [], []
  355. # Not all modules are required to have a __file__ attribute. See
  356. # PEP 420 for more details.
  357. here = getattr(sys, '_stdlib_dir', None)
  358. if not here and hasattr(os, '__file__'):
  359. here = os.path.dirname(os.__file__)
  360. if here:
  361. files.extend(["LICENSE.txt", "LICENSE"])
  362. dirs.extend([os.path.join(here, os.pardir), here, os.curdir])
  363. builtins.license = _sitebuiltins._Printer(
  364. "license",
  365. "See https://www.python.org/psf/license/",
  366. files, dirs)
  367. def sethelper():
  368. builtins.help = _sitebuiltins._Helper()
  369. def enablerlcompleter():
  370. """Enable default readline configuration on interactive prompts, by
  371. registering a sys.__interactivehook__.
  372. If the readline module can be imported, the hook will set the Tab key
  373. as completion key and register ~/.python_history as history file.
  374. This can be overridden in the sitecustomize or usercustomize module,
  375. or in a PYTHONSTARTUP file.
  376. """
  377. def register_readline():
  378. import atexit
  379. try:
  380. import readline
  381. import rlcompleter
  382. except ImportError:
  383. return
  384. # Reading the initialization (config) file may not be enough to set a
  385. # completion key, so we set one first and then read the file.
  386. readline_doc = getattr(readline, '__doc__', '')
  387. if readline_doc is not None and 'libedit' in readline_doc:
  388. readline.parse_and_bind('bind ^I rl_complete')
  389. else:
  390. readline.parse_and_bind('tab: complete')
  391. try:
  392. readline.read_init_file()
  393. except OSError:
  394. # An OSError here could have many causes, but the most likely one
  395. # is that there's no .inputrc file (or .editrc file in the case of
  396. # Mac OS X + libedit) in the expected location. In that case, we
  397. # want to ignore the exception.
  398. pass
  399. if readline.get_current_history_length() == 0:
  400. # If no history was loaded, default to .python_history.
  401. # The guard is necessary to avoid doubling history size at
  402. # each interpreter exit when readline was already configured
  403. # through a PYTHONSTARTUP hook, see:
  404. # http://bugs.python.org/issue5845#msg198636
  405. history = os.path.join(os.path.expanduser('~'),
  406. '.python_history')
  407. try:
  408. readline.read_history_file(history)
  409. except OSError:
  410. pass
  411. def write_history():
  412. try:
  413. readline.write_history_file(history)
  414. except OSError:
  415. # bpo-19891, bpo-41193: Home directory does not exist
  416. # or is not writable, or the filesystem is read-only.
  417. pass
  418. atexit.register(write_history)
  419. sys.__interactivehook__ = register_readline
  420. def venv(known_paths):
  421. global PREFIXES, ENABLE_USER_SITE
  422. env = os.environ
  423. if sys.platform == 'darwin' and '__PYVENV_LAUNCHER__' in env:
  424. executable = sys._base_executable = os.environ['__PYVENV_LAUNCHER__']
  425. else:
  426. executable = sys.executable
  427. exe_dir = os.path.dirname(os.path.abspath(executable))
  428. site_prefix = os.path.dirname(exe_dir)
  429. sys._home = None
  430. conf_basename = 'pyvenv.cfg'
  431. candidate_conf = next(
  432. (
  433. conffile for conffile in (
  434. os.path.join(exe_dir, conf_basename),
  435. os.path.join(site_prefix, conf_basename)
  436. )
  437. if os.path.isfile(conffile)
  438. ),
  439. None
  440. )
  441. if candidate_conf:
  442. virtual_conf = candidate_conf
  443. system_site = "true"
  444. # Issue 25185: Use UTF-8, as that's what the venv module uses when
  445. # writing the file.
  446. with open(virtual_conf, encoding='utf-8') as f:
  447. for line in f:
  448. if '=' in line:
  449. key, _, value = line.partition('=')
  450. key = key.strip().lower()
  451. value = value.strip()
  452. if key == 'include-system-site-packages':
  453. system_site = value.lower()
  454. elif key == 'home':
  455. sys._home = value
  456. sys.prefix = sys.exec_prefix = site_prefix
  457. # Doing this here ensures venv takes precedence over user-site
  458. addsitepackages(known_paths, [sys.prefix])
  459. # addsitepackages will process site_prefix again if its in PREFIXES,
  460. # but that's ok; known_paths will prevent anything being added twice
  461. if system_site == "true":
  462. PREFIXES.insert(0, sys.prefix)
  463. else:
  464. PREFIXES = [sys.prefix]
  465. ENABLE_USER_SITE = False
  466. return known_paths
  467. def execsitecustomize():
  468. """Run custom site specific code, if available."""
  469. try:
  470. try:
  471. import sitecustomize
  472. except ImportError as exc:
  473. if exc.name == 'sitecustomize':
  474. pass
  475. else:
  476. raise
  477. except Exception as err:
  478. if sys.flags.verbose:
  479. sys.excepthook(*sys.exc_info())
  480. else:
  481. sys.stderr.write(
  482. "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
  483. "%s: %s\n" %
  484. (err.__class__.__name__, err))
  485. def execusercustomize():
  486. """Run custom user specific code, if available."""
  487. try:
  488. try:
  489. import usercustomize
  490. except ImportError as exc:
  491. if exc.name == 'usercustomize':
  492. pass
  493. else:
  494. raise
  495. except Exception as err:
  496. if sys.flags.verbose:
  497. sys.excepthook(*sys.exc_info())
  498. else:
  499. sys.stderr.write(
  500. "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
  501. "%s: %s\n" %
  502. (err.__class__.__name__, err))
  503. def main():
  504. """Add standard site-specific directories to the module search path.
  505. This function is called automatically when this module is imported,
  506. unless the python interpreter was started with the -S flag.
  507. """
  508. global ENABLE_USER_SITE
  509. orig_path = sys.path[:]
  510. #known_paths = removeduppaths()
  511. if orig_path != sys.path:
  512. # removeduppaths() might make sys.path absolute.
  513. # fix __file__ and __cached__ of already imported modules too.
  514. abs_paths()
  515. #known_paths = venv(known_paths)
  516. if ENABLE_USER_SITE is None:
  517. ENABLE_USER_SITE = check_enableusersite()
  518. #known_paths = addusersitepackages(known_paths)
  519. #known_paths = addsitepackages(known_paths)
  520. setquit()
  521. setcopyright()
  522. sethelper()
  523. if not sys.flags.isolated:
  524. enablerlcompleter()
  525. execsitecustomize()
  526. if ENABLE_USER_SITE:
  527. execusercustomize()
  528. # Prevent extending of sys.path when python was started with -S and
  529. # site is imported later.
  530. if not sys.flags.no_site:
  531. main()
  532. def _script():
  533. help = """\
  534. %s [--user-base] [--user-site]
  535. Without arguments print some useful information
  536. With arguments print the value of USER_BASE and/or USER_SITE separated
  537. by '%s'.
  538. Exit codes with --user-base or --user-site:
  539. 0 - user site directory is enabled
  540. 1 - user site directory is disabled by user
  541. 2 - user site directory is disabled by super user
  542. or for security reasons
  543. >2 - unknown error
  544. """
  545. args = sys.argv[1:]
  546. if not args:
  547. user_base = getuserbase()
  548. user_site = getusersitepackages()
  549. print("sys.path = [")
  550. for dir in sys.path:
  551. print(" %r," % (dir,))
  552. print("]")
  553. def exists(path):
  554. if path is not None and os.path.isdir(path):
  555. return "exists"
  556. else:
  557. return "doesn't exist"
  558. print(f"USER_BASE: {user_base!r} ({exists(user_base)})")
  559. print(f"USER_SITE: {user_site!r} ({exists(user_site)})")
  560. print(f"ENABLE_USER_SITE: {ENABLE_USER_SITE!r}")
  561. sys.exit(0)
  562. buffer = []
  563. if '--user-base' in args:
  564. buffer.append(USER_BASE)
  565. if '--user-site' in args:
  566. buffer.append(USER_SITE)
  567. if buffer:
  568. print(os.pathsep.join(buffer))
  569. if ENABLE_USER_SITE:
  570. sys.exit(0)
  571. elif ENABLE_USER_SITE is False:
  572. sys.exit(1)
  573. elif ENABLE_USER_SITE is None:
  574. sys.exit(2)
  575. else:
  576. sys.exit(3)
  577. else:
  578. import textwrap
  579. print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
  580. sys.exit(10)
  581. if __name__ == '__main__':
  582. _script()