site.py 21 KB

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