site.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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. # Prefixes for site-packages; add additional prefixes like /usr/local here
  62. PREFIXES = [sys.prefix, sys.exec_prefix]
  63. # Enable per user site-packages directory
  64. # set it to False to disable the feature or True to force the feature
  65. ENABLE_USER_SITE = None
  66. # for distutils.commands.install
  67. # These values are initialized by the getuserbase() and getusersitepackages()
  68. # functions, through the main() function when Python starts.
  69. USER_SITE = None
  70. USER_BASE = None
  71. def makepath(*paths):
  72. dir = os.path.join(*paths)
  73. try:
  74. dir = os.path.abspath(dir)
  75. except OSError:
  76. pass
  77. return dir, os.path.normcase(dir)
  78. def abs_paths():
  79. """Set all module __file__ and __cached__ attributes to an absolute path"""
  80. for m in set(sys.modules.values()):
  81. if (getattr(getattr(m, '__loader__', None), '__module__', None) not in
  82. ('_frozen_importlib', '_frozen_importlib_external')):
  83. continue # don't mess with a PEP 302-supplied __file__
  84. try:
  85. m.__file__ = os.path.abspath(m.__file__)
  86. except (AttributeError, OSError, TypeError):
  87. pass
  88. try:
  89. m.__cached__ = os.path.abspath(m.__cached__)
  90. except (AttributeError, OSError, TypeError):
  91. pass
  92. def removeduppaths():
  93. """ Remove duplicate entries from sys.path along with making them
  94. absolute"""
  95. # This ensures that the initial path provided by the interpreter contains
  96. # only absolute pathnames, even if we're running from the build directory.
  97. L = []
  98. known_paths = set()
  99. for dir in sys.path:
  100. # Filter out duplicate paths (on case-insensitive file systems also
  101. # if they only differ in case); turn relative paths into absolute
  102. # paths.
  103. dir, dircase = makepath(dir)
  104. if dircase not in known_paths:
  105. L.append(dir)
  106. known_paths.add(dircase)
  107. sys.path[:] = L
  108. return known_paths
  109. def _init_pathinfo():
  110. """Return a set containing all existing file system items from sys.path."""
  111. d = set()
  112. for item in sys.path:
  113. try:
  114. if os.path.exists(item):
  115. _, itemcase = makepath(item)
  116. d.add(itemcase)
  117. except TypeError:
  118. continue
  119. return d
  120. def addpackage(sitedir, name, known_paths):
  121. """Process a .pth file within the site-packages directory:
  122. For each line in the file, either combine it with sitedir to a path
  123. and add that to known_paths, or execute it if it starts with 'import '.
  124. """
  125. if known_paths is None:
  126. known_paths = _init_pathinfo()
  127. reset = True
  128. else:
  129. reset = False
  130. fullname = os.path.join(sitedir, name)
  131. try:
  132. f = open(fullname, "r")
  133. except OSError:
  134. return
  135. with f:
  136. for n, line in enumerate(f):
  137. if line.startswith("#"):
  138. continue
  139. try:
  140. if line.startswith(("import ", "import\t")):
  141. exec(line)
  142. continue
  143. line = line.rstrip()
  144. dir, dircase = makepath(sitedir, line)
  145. if not dircase in known_paths and os.path.exists(dir):
  146. sys.path.append(dir)
  147. known_paths.add(dircase)
  148. except Exception:
  149. print("Error processing line {:d} of {}:\n".format(n+1, fullname),
  150. file=sys.stderr)
  151. import traceback
  152. for record in traceback.format_exception(*sys.exc_info()):
  153. for line in record.splitlines():
  154. print(' '+line, file=sys.stderr)
  155. print("\nRemainder of file ignored", file=sys.stderr)
  156. break
  157. if reset:
  158. known_paths = None
  159. return known_paths
  160. def addsitedir(sitedir, known_paths=None):
  161. """Add 'sitedir' argument to sys.path if missing and handle .pth files in
  162. 'sitedir'"""
  163. if known_paths is None:
  164. known_paths = _init_pathinfo()
  165. reset = True
  166. else:
  167. reset = False
  168. sitedir, sitedircase = makepath(sitedir)
  169. if not sitedircase in known_paths:
  170. sys.path.append(sitedir) # Add path component
  171. known_paths.add(sitedircase)
  172. try:
  173. names = os.listdir(sitedir)
  174. except OSError:
  175. return
  176. names = [name for name in names if name.endswith(".pth")]
  177. for name in sorted(names):
  178. addpackage(sitedir, name, known_paths)
  179. if reset:
  180. known_paths = None
  181. return known_paths
  182. def check_enableusersite():
  183. """Check if user site directory is safe for inclusion
  184. The function tests for the command line flag (including environment var),
  185. process uid/gid equal to effective uid/gid.
  186. None: Disabled for security reasons
  187. False: Disabled by user (command line option)
  188. True: Safe and enabled
  189. """
  190. if sys.flags.no_user_site:
  191. return False
  192. if hasattr(os, "getuid") and hasattr(os, "geteuid"):
  193. # check process uid == effective uid
  194. if os.geteuid() != os.getuid():
  195. return None
  196. if hasattr(os, "getgid") and hasattr(os, "getegid"):
  197. # check process gid == effective gid
  198. if os.getegid() != os.getgid():
  199. return None
  200. return True
  201. # NOTE: sysconfig and it's dependencies are relatively large but site module
  202. # needs very limited part of them.
  203. # To speedup startup time, we have copy of them.
  204. #
  205. # See https://bugs.python.org/issue29585
  206. # Copy of sysconfig._getuserbase()
  207. def _getuserbase():
  208. env_base = os.environ.get("PYTHONUSERBASE", None)
  209. if env_base:
  210. return env_base
  211. def joinuser(*args):
  212. return os.path.expanduser(os.path.join(*args))
  213. if os.name == "nt":
  214. base = os.environ.get("APPDATA") or "~"
  215. return joinuser(base, "Python")
  216. if sys.platform == "darwin" and sys._framework:
  217. return joinuser("~", "Library", sys._framework,
  218. "%d.%d" % sys.version_info[:2])
  219. return joinuser("~", ".local")
  220. # Same to sysconfig.get_path('purelib', os.name+'_user')
  221. def _get_path(userbase):
  222. version = sys.version_info
  223. if os.name == 'nt':
  224. return f'{userbase}\\Python{version[0]}{version[1]}\\site-packages'
  225. if sys.platform == 'darwin' and sys._framework:
  226. return f'{userbase}/lib/python/site-packages'
  227. return f'{userbase}/lib/python{version[0]}.{version[1]}/site-packages'
  228. def getuserbase():
  229. """Returns the `user base` directory path.
  230. The `user base` directory can be used to store data. If the global
  231. variable ``USER_BASE`` is not initialized yet, this function will also set
  232. it.
  233. """
  234. global USER_BASE
  235. if USER_BASE is None:
  236. USER_BASE = _getuserbase()
  237. return USER_BASE
  238. def getusersitepackages():
  239. """Returns the user-specific site-packages directory path.
  240. If the global variable ``USER_SITE`` is not initialized yet, this
  241. function will also set it.
  242. """
  243. global USER_SITE
  244. userbase = getuserbase() # this will also set USER_BASE
  245. if USER_SITE is None:
  246. USER_SITE = _get_path(userbase)
  247. return USER_SITE
  248. def addusersitepackages(known_paths):
  249. """Add a per user site-package to sys.path
  250. Each user has its own python directory with site-packages in the
  251. home directory.
  252. """
  253. # get the per user site-package path
  254. # this call will also make sure USER_BASE and USER_SITE are set
  255. user_site = getusersitepackages()
  256. if ENABLE_USER_SITE and os.path.isdir(user_site):
  257. addsitedir(user_site, known_paths)
  258. return known_paths
  259. def getsitepackages(prefixes=None):
  260. """Returns a list containing all global site-packages directories.
  261. For each directory present in ``prefixes`` (or the global ``PREFIXES``),
  262. this function will find its `site-packages` subdirectory depending on the
  263. system environment, and will return a list of full paths.
  264. """
  265. sitepackages = []
  266. seen = set()
  267. if prefixes is None:
  268. prefixes = PREFIXES
  269. for prefix in prefixes:
  270. if not prefix or prefix in seen:
  271. continue
  272. seen.add(prefix)
  273. if os.sep == '/':
  274. sitepackages.append(os.path.join(prefix, "lib",
  275. "python%d.%d" % sys.version_info[:2],
  276. "site-packages"))
  277. else:
  278. sitepackages.append(prefix)
  279. sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
  280. return sitepackages
  281. def addsitepackages(known_paths, prefixes=None):
  282. """Add site-packages to sys.path"""
  283. for sitedir in getsitepackages(prefixes):
  284. if os.path.isdir(sitedir):
  285. addsitedir(sitedir, known_paths)
  286. return known_paths
  287. def setquit():
  288. """Define new builtins 'quit' and 'exit'.
  289. These are objects which make the interpreter exit when called.
  290. The repr of each object contains a hint at how it works.
  291. """
  292. if os.sep == '\\':
  293. eof = 'Ctrl-Z plus Return'
  294. else:
  295. eof = 'Ctrl-D (i.e. EOF)'
  296. builtins.quit = _sitebuiltins.Quitter('quit', eof)
  297. builtins.exit = _sitebuiltins.Quitter('exit', eof)
  298. def setcopyright():
  299. """Set 'copyright' and 'credits' in builtins"""
  300. builtins.copyright = _sitebuiltins._Printer("copyright", sys.copyright)
  301. if sys.platform[:4] == 'java':
  302. builtins.credits = _sitebuiltins._Printer(
  303. "credits",
  304. "Jython is maintained by the Jython developers (www.jython.org).")
  305. else:
  306. builtins.credits = _sitebuiltins._Printer("credits", """\
  307. Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  308. for supporting Python development. See www.python.org for more information.""")
  309. files, dirs = [], []
  310. # Not all modules are required to have a __file__ attribute. See
  311. # PEP 420 for more details.
  312. if hasattr(os, '__file__'):
  313. here = os.path.dirname(os.__file__)
  314. files.extend(["LICENSE.txt", "LICENSE"])
  315. dirs.extend([os.path.join(here, os.pardir), here, os.curdir])
  316. builtins.license = _sitebuiltins._Printer(
  317. "license",
  318. "See https://www.python.org/psf/license/",
  319. files, dirs)
  320. def sethelper():
  321. builtins.help = _sitebuiltins._Helper()
  322. def enablerlcompleter():
  323. """Enable default readline configuration on interactive prompts, by
  324. registering a sys.__interactivehook__.
  325. If the readline module can be imported, the hook will set the Tab key
  326. as completion key and register ~/.python_history as history file.
  327. This can be overridden in the sitecustomize or usercustomize module,
  328. or in a PYTHONSTARTUP file.
  329. """
  330. def register_readline():
  331. import atexit
  332. try:
  333. import readline
  334. import rlcompleter
  335. except ImportError:
  336. return
  337. # Reading the initialization (config) file may not be enough to set a
  338. # completion key, so we set one first and then read the file.
  339. readline_doc = getattr(readline, '__doc__', '')
  340. if readline_doc is not None and 'libedit' in readline_doc:
  341. readline.parse_and_bind('bind ^I rl_complete')
  342. else:
  343. readline.parse_and_bind('tab: complete')
  344. try:
  345. readline.read_init_file()
  346. except OSError:
  347. # An OSError here could have many causes, but the most likely one
  348. # is that there's no .inputrc file (or .editrc file in the case of
  349. # Mac OS X + libedit) in the expected location. In that case, we
  350. # want to ignore the exception.
  351. pass
  352. if readline.get_current_history_length() == 0:
  353. # If no history was loaded, default to .python_history.
  354. # The guard is necessary to avoid doubling history size at
  355. # each interpreter exit when readline was already configured
  356. # through a PYTHONSTARTUP hook, see:
  357. # http://bugs.python.org/issue5845#msg198636
  358. history = os.path.join(os.path.expanduser('~'),
  359. '.python_history')
  360. try:
  361. readline.read_history_file(history)
  362. except OSError:
  363. pass
  364. def write_history():
  365. try:
  366. readline.write_history_file(history)
  367. except (FileNotFoundError, PermissionError):
  368. # home directory does not exist or is not writable
  369. # https://bugs.python.org/issue19891
  370. pass
  371. atexit.register(write_history)
  372. sys.__interactivehook__ = register_readline
  373. def venv(known_paths):
  374. global PREFIXES, ENABLE_USER_SITE
  375. env = os.environ
  376. if sys.platform == 'darwin' and '__PYVENV_LAUNCHER__' in env:
  377. executable = sys._base_executable = os.environ['__PYVENV_LAUNCHER__']
  378. else:
  379. executable = sys.executable
  380. exe_dir, _ = os.path.split(os.path.abspath(executable))
  381. site_prefix = os.path.dirname(exe_dir)
  382. sys._home = None
  383. conf_basename = 'pyvenv.cfg'
  384. candidate_confs = [
  385. conffile for conffile in (
  386. os.path.join(exe_dir, conf_basename),
  387. os.path.join(site_prefix, conf_basename)
  388. )
  389. if os.path.isfile(conffile)
  390. ]
  391. if candidate_confs:
  392. virtual_conf = candidate_confs[0]
  393. system_site = "true"
  394. # Issue 25185: Use UTF-8, as that's what the venv module uses when
  395. # writing the file.
  396. with open(virtual_conf, encoding='utf-8') as f:
  397. for line in f:
  398. if '=' in line:
  399. key, _, value = line.partition('=')
  400. key = key.strip().lower()
  401. value = value.strip()
  402. if key == 'include-system-site-packages':
  403. system_site = value.lower()
  404. elif key == 'home':
  405. sys._home = value
  406. sys.prefix = sys.exec_prefix = site_prefix
  407. # Doing this here ensures venv takes precedence over user-site
  408. addsitepackages(known_paths, [sys.prefix])
  409. # addsitepackages will process site_prefix again if its in PREFIXES,
  410. # but that's ok; known_paths will prevent anything being added twice
  411. if system_site == "true":
  412. PREFIXES.insert(0, sys.prefix)
  413. else:
  414. PREFIXES = [sys.prefix]
  415. ENABLE_USER_SITE = False
  416. return known_paths
  417. def execsitecustomize():
  418. """Run custom site specific code, if available."""
  419. try:
  420. try:
  421. import sitecustomize
  422. except ImportError as exc:
  423. if exc.name == 'sitecustomize':
  424. pass
  425. else:
  426. raise
  427. except Exception as err:
  428. if sys.flags.verbose:
  429. sys.excepthook(*sys.exc_info())
  430. else:
  431. sys.stderr.write(
  432. "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
  433. "%s: %s\n" %
  434. (err.__class__.__name__, err))
  435. def execusercustomize():
  436. """Run custom user specific code, if available."""
  437. try:
  438. try:
  439. import usercustomize
  440. except ImportError as exc:
  441. if exc.name == 'usercustomize':
  442. pass
  443. else:
  444. raise
  445. except Exception as err:
  446. if sys.flags.verbose:
  447. sys.excepthook(*sys.exc_info())
  448. else:
  449. sys.stderr.write(
  450. "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
  451. "%s: %s\n" %
  452. (err.__class__.__name__, err))
  453. def main():
  454. """Add standard site-specific directories to the module search path.
  455. This function is called automatically when this module is imported,
  456. unless the python interpreter was started with the -S flag.
  457. """
  458. global ENABLE_USER_SITE
  459. orig_path = sys.path[:]
  460. known_paths = removeduppaths()
  461. if orig_path != sys.path:
  462. # removeduppaths() might make sys.path absolute.
  463. # fix __file__ and __cached__ of already imported modules too.
  464. abs_paths()
  465. known_paths = venv(known_paths)
  466. if ENABLE_USER_SITE is None:
  467. ENABLE_USER_SITE = check_enableusersite()
  468. known_paths = addusersitepackages(known_paths)
  469. known_paths = addsitepackages(known_paths)
  470. setquit()
  471. setcopyright()
  472. sethelper()
  473. if not sys.flags.isolated:
  474. enablerlcompleter()
  475. execsitecustomize()
  476. if ENABLE_USER_SITE:
  477. execusercustomize()
  478. # Prevent extending of sys.path when python was started with -S and
  479. # site is imported later.
  480. if not sys.flags.no_site:
  481. main()
  482. def _script():
  483. help = """\
  484. %s [--user-base] [--user-site]
  485. Without arguments print some useful information
  486. With arguments print the value of USER_BASE and/or USER_SITE separated
  487. by '%s'.
  488. Exit codes with --user-base or --user-site:
  489. 0 - user site directory is enabled
  490. 1 - user site directory is disabled by user
  491. 2 - uses site directory is disabled by super user
  492. or for security reasons
  493. >2 - unknown error
  494. """
  495. args = sys.argv[1:]
  496. if not args:
  497. user_base = getuserbase()
  498. user_site = getusersitepackages()
  499. print("sys.path = [")
  500. for dir in sys.path:
  501. print(" %r," % (dir,))
  502. print("]")
  503. print("USER_BASE: %r (%s)" % (user_base,
  504. "exists" if os.path.isdir(user_base) else "doesn't exist"))
  505. print("USER_SITE: %r (%s)" % (user_site,
  506. "exists" if os.path.isdir(user_site) else "doesn't exist"))
  507. print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
  508. sys.exit(0)
  509. buffer = []
  510. if '--user-base' in args:
  511. buffer.append(USER_BASE)
  512. if '--user-site' in args:
  513. buffer.append(USER_SITE)
  514. if buffer:
  515. print(os.pathsep.join(buffer))
  516. if ENABLE_USER_SITE:
  517. sys.exit(0)
  518. elif ENABLE_USER_SITE is False:
  519. sys.exit(1)
  520. elif ENABLE_USER_SITE is None:
  521. sys.exit(2)
  522. else:
  523. sys.exit(3)
  524. else:
  525. import textwrap
  526. print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
  527. sys.exit(10)
  528. if __name__ == '__main__':
  529. _script()