site.py 21 KB

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