site.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. """Append module search paths for third-party packages to sys.path.
  2. ****************************************************************
  3. * This module is automatically imported during initialization. *
  4. ****************************************************************
  5. In earlier versions of Python (up to 1.5a3), scripts or modules that
  6. needed to use site-specific modules would place ``import site''
  7. somewhere near the top of their code. Because of the automatic
  8. import, this is no longer necessary (but code that does it still
  9. works).
  10. This will append site-specific paths to the module search path. On
  11. Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
  12. appends lib/python<version>/site-packages as well as lib/site-python.
  13. It also supports the Debian convention of
  14. lib/python<version>/dist-packages. On other platforms (mainly Mac and
  15. Windows), it uses just sys.prefix (and sys.exec_prefix, if different,
  16. but this is unlikely). The resulting directories, if they exist, are
  17. appended to sys.path, and also inspected for path configuration files.
  18. FOR DEBIAN, this sys.path is augmented with directories in /usr/local.
  19. Local addons go into /usr/local/lib/python<version>/site-packages
  20. (resp. /usr/local/lib/site-python), Debian addons install into
  21. /usr/{lib,share}/python<version>/dist-packages.
  22. A path configuration file is a file whose name has the form
  23. <package>.pth; its contents are additional directories (one per line)
  24. to be added to sys.path. Non-existing directories (or
  25. non-directories) are never added to sys.path; no directory is added to
  26. sys.path more than once. Blank lines and lines beginning with
  27. '#' are skipped. Lines starting with 'import' are executed.
  28. For example, suppose sys.prefix and sys.exec_prefix are set to
  29. /usr/local and there is a directory /usr/local/lib/python2.X/site-packages
  30. with three subdirectories, foo, bar and spam, and two path
  31. configuration files, foo.pth and bar.pth. Assume foo.pth contains the
  32. following:
  33. # foo package configuration
  34. foo
  35. bar
  36. bletch
  37. and bar.pth contains:
  38. # bar package configuration
  39. bar
  40. Then the following directories are added to sys.path, in this order:
  41. /usr/local/lib/python2.X/site-packages/bar
  42. /usr/local/lib/python2.X/site-packages/foo
  43. Note that bletch is omitted because it doesn't exist; bar precedes foo
  44. because bar.pth comes alphabetically before foo.pth; and spam is
  45. omitted because it is not mentioned in either path configuration file.
  46. After these path manipulations, an attempt is made to import a module
  47. named sitecustomize, which can perform arbitrary additional
  48. site-specific customizations. If this import fails with an
  49. ImportError exception, it is silently ignored.
  50. """
  51. import os
  52. import sys
  53. try:
  54. import __builtin__ as builtins
  55. except ImportError:
  56. import builtins
  57. try:
  58. set
  59. except NameError:
  60. from sets import Set as set
  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. USER_SITE = None
  68. USER_BASE = None
  69. _is_64bit = (getattr(sys, "maxsize", None) or getattr(sys, "maxint")) > 2 ** 32
  70. _is_pypy = hasattr(sys, "pypy_version_info")
  71. def makepath(*paths):
  72. dir = os.path.join(*paths)
  73. dir = os.path.abspath(dir)
  74. return dir, os.path.normcase(dir)
  75. def abs__file__():
  76. """Set all module' __file__ attribute to an absolute path"""
  77. for m in sys.modules.values():
  78. f = getattr(m, "__file__", None)
  79. if f is None:
  80. continue
  81. m.__file__ = os.path.abspath(f)
  82. def removeduppaths():
  83. """ Remove duplicate entries from sys.path along with making them
  84. absolute"""
  85. # This ensures that the initial path provided by the interpreter contains
  86. # only absolute pathnames, even if we're running from the build directory.
  87. L = []
  88. known_paths = set()
  89. for dir in sys.path:
  90. # Filter out duplicate paths (on case-insensitive file systems also
  91. # if they only differ in case); turn relative paths into absolute
  92. # paths.
  93. dir, dircase = makepath(dir)
  94. if not dircase in known_paths:
  95. L.append(dir)
  96. known_paths.add(dircase)
  97. sys.path[:] = L
  98. return known_paths
  99. # XXX This should not be part of site.py, since it is needed even when
  100. # using the -S option for Python. See http://www.python.org/sf/586680
  101. def addbuilddir():
  102. """Append ./build/lib.<platform> in case we're running in the build dir
  103. (especially for Guido :-)"""
  104. from distutils.util import get_platform
  105. s = "build/lib.{}-{}.{}".format(get_platform(), *sys.version_info)
  106. if hasattr(sys, "gettotalrefcount"):
  107. s += "-pydebug"
  108. s = os.path.join(os.path.dirname(sys.path[-1]), s)
  109. sys.path.append(s)
  110. def _init_pathinfo():
  111. """Return a set containing all existing directory entries from sys.path"""
  112. d = set()
  113. for dir in sys.path:
  114. try:
  115. if os.path.isdir(dir):
  116. dir, dircase = makepath(dir)
  117. d.add(dircase)
  118. except TypeError:
  119. continue
  120. return d
  121. def addpackage(sitedir, name, known_paths):
  122. """Add a new path to known_paths by combining sitedir and 'name' or execute
  123. sitedir if it starts with 'import'"""
  124. if known_paths is None:
  125. _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 IOError:
  133. return
  134. try:
  135. for line in f:
  136. if line.startswith("#"):
  137. continue
  138. if line.startswith("import"):
  139. exec(line)
  140. continue
  141. line = line.rstrip()
  142. dir, dircase = makepath(sitedir, line)
  143. if not dircase in known_paths and os.path.exists(dir):
  144. sys.path.append(dir)
  145. known_paths.add(dircase)
  146. finally:
  147. f.close()
  148. if reset:
  149. known_paths = None
  150. return known_paths
  151. def addsitedir(sitedir, known_paths=None):
  152. """Add 'sitedir' argument to sys.path if missing and handle .pth files in
  153. 'sitedir'"""
  154. if known_paths is None:
  155. known_paths = _init_pathinfo()
  156. reset = 1
  157. else:
  158. reset = 0
  159. sitedir, sitedircase = makepath(sitedir)
  160. if not sitedircase in known_paths:
  161. sys.path.append(sitedir) # Add path component
  162. try:
  163. names = os.listdir(sitedir)
  164. except os.error:
  165. return
  166. names.sort()
  167. for name in names:
  168. if name.endswith(os.extsep + "pth"):
  169. addpackage(sitedir, name, known_paths)
  170. if reset:
  171. known_paths = None
  172. return known_paths
  173. def addsitepackages(known_paths, sys_prefix=sys.prefix, exec_prefix=sys.exec_prefix):
  174. """Add site-packages (and possibly site-python) to sys.path"""
  175. prefixes = [os.path.join(sys_prefix, "local"), sys_prefix]
  176. if exec_prefix != sys_prefix:
  177. prefixes.append(os.path.join(exec_prefix, "local"))
  178. for prefix in prefixes:
  179. if prefix:
  180. if sys.platform in ("os2emx", "riscos"):
  181. sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
  182. elif _is_pypy:
  183. sitedirs = [os.path.join(prefix, "site-packages")]
  184. elif sys.platform == "darwin" and prefix == sys_prefix:
  185. if prefix.startswith("/System/Library/Frameworks/"): # Apple's Python
  186. sitedirs = [
  187. os.path.join("/Library/Python", "{}.{}".format(*sys.version_info), "site-packages"),
  188. os.path.join(prefix, "Extras", "lib", "python"),
  189. ]
  190. else: # any other Python distros on OSX work this way
  191. sitedirs = [os.path.join(prefix, "lib", "python{}.{}".format(*sys.version_info), "site-packages")]
  192. elif os.sep == "/":
  193. sitedirs = [
  194. os.path.join(prefix, "lib", "python{}.{}".format(*sys.version_info), "site-packages"),
  195. os.path.join(prefix, "lib", "site-python"),
  196. os.path.join(prefix, "python{}.{}".format(*sys.version_info), "lib-dynload"),
  197. ]
  198. lib64_dir = os.path.join(prefix, "lib64", "python{}.{}".format(*sys.version_info), "site-packages")
  199. if os.path.exists(lib64_dir) and os.path.realpath(lib64_dir) not in [
  200. os.path.realpath(p) for p in sitedirs
  201. ]:
  202. if _is_64bit:
  203. sitedirs.insert(0, lib64_dir)
  204. else:
  205. sitedirs.append(lib64_dir)
  206. try:
  207. # sys.getobjects only available in --with-pydebug build
  208. sys.getobjects
  209. sitedirs.insert(0, os.path.join(sitedirs[0], "debug"))
  210. except AttributeError:
  211. pass
  212. # Debian-specific dist-packages directories:
  213. sitedirs.append(
  214. os.path.join(prefix, "local/lib", "python{}.{}".format(*sys.version_info), "dist-packages")
  215. )
  216. if sys.version_info[0] == 2:
  217. sitedirs.append(
  218. os.path.join(prefix, "lib", "python{}.{}".format(*sys.version_info), "dist-packages")
  219. )
  220. else:
  221. sitedirs.append(
  222. os.path.join(prefix, "lib", "python{}".format(sys.version_info[0]), "dist-packages")
  223. )
  224. sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
  225. else:
  226. sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
  227. if sys.platform == "darwin":
  228. # for framework builds *only* we add the standard Apple
  229. # locations. Currently only per-user, but /Library and
  230. # /Network/Library could be added too
  231. if "Python.framework" in prefix or "Python3.framework" in prefix:
  232. home = os.environ.get("HOME")
  233. if home:
  234. sitedirs.append(
  235. os.path.join(home, "Library", "Python", "{}.{}".format(*sys.version_info), "site-packages")
  236. )
  237. for sitedir in sitedirs:
  238. if os.path.isdir(sitedir):
  239. addsitedir(sitedir, known_paths)
  240. return None
  241. def check_enableusersite():
  242. """Check if user site directory is safe for inclusion
  243. The function tests for the command line flag (including environment var),
  244. process uid/gid equal to effective uid/gid.
  245. None: Disabled for security reasons
  246. False: Disabled by user (command line option)
  247. True: Safe and enabled
  248. """
  249. if hasattr(sys, "flags") and getattr(sys.flags, "no_user_site", False):
  250. return False
  251. if hasattr(os, "getuid") and hasattr(os, "geteuid"):
  252. # check process uid == effective uid
  253. if os.geteuid() != os.getuid():
  254. return None
  255. if hasattr(os, "getgid") and hasattr(os, "getegid"):
  256. # check process gid == effective gid
  257. if os.getegid() != os.getgid():
  258. return None
  259. return True
  260. def addusersitepackages(known_paths):
  261. """Add a per user site-package to sys.path
  262. Each user has its own python directory with site-packages in the
  263. home directory.
  264. USER_BASE is the root directory for all Python versions
  265. USER_SITE is the user specific site-packages directory
  266. USER_SITE/.. can be used for data.
  267. """
  268. global USER_BASE, USER_SITE, ENABLE_USER_SITE
  269. env_base = os.environ.get("PYTHONUSERBASE", None)
  270. def joinuser(*args):
  271. return os.path.expanduser(os.path.join(*args))
  272. # if sys.platform in ('os2emx', 'riscos'):
  273. # # Don't know what to put here
  274. # USER_BASE = ''
  275. # USER_SITE = ''
  276. if os.name == "nt":
  277. base = os.environ.get("APPDATA") or "~"
  278. if env_base:
  279. USER_BASE = env_base
  280. else:
  281. USER_BASE = joinuser(base, "Python")
  282. USER_SITE = os.path.join(USER_BASE, "Python{}{}".format(*sys.version_info), "site-packages")
  283. else:
  284. if env_base:
  285. USER_BASE = env_base
  286. else:
  287. USER_BASE = joinuser("~", ".local")
  288. USER_SITE = os.path.join(USER_BASE, "lib", "python{}.{}".format(*sys.version_info), "site-packages")
  289. if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
  290. addsitedir(USER_SITE, known_paths)
  291. if ENABLE_USER_SITE:
  292. for dist_libdir in ("lib", "local/lib"):
  293. user_site = os.path.join(USER_BASE, dist_libdir, "python{}.{}".format(*sys.version_info), "dist-packages")
  294. if os.path.isdir(user_site):
  295. addsitedir(user_site, known_paths)
  296. return known_paths
  297. def setBEGINLIBPATH():
  298. """The OS/2 EMX port has optional extension modules that do double duty
  299. as DLLs (and must use the .DLL file extension) for other extensions.
  300. The library search path needs to be amended so these will be found
  301. during module import. Use BEGINLIBPATH so that these are at the start
  302. of the library search path.
  303. """
  304. dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
  305. libpath = os.environ["BEGINLIBPATH"].split(";")
  306. if libpath[-1]:
  307. libpath.append(dllpath)
  308. else:
  309. libpath[-1] = dllpath
  310. os.environ["BEGINLIBPATH"] = ";".join(libpath)
  311. def setquit():
  312. """Define new built-ins 'quit' and 'exit'.
  313. These are simply strings that display a hint on how to exit.
  314. """
  315. if os.sep == ":":
  316. eof = "Cmd-Q"
  317. elif os.sep == "\\":
  318. eof = "Ctrl-Z plus Return"
  319. else:
  320. eof = "Ctrl-D (i.e. EOF)"
  321. class Quitter(object):
  322. def __init__(self, name):
  323. self.name = name
  324. def __repr__(self):
  325. return "Use {}() or {} to exit".format(self.name, eof)
  326. def __call__(self, code=None):
  327. # Shells like IDLE catch the SystemExit, but listen when their
  328. # stdin wrapper is closed.
  329. try:
  330. sys.stdin.close()
  331. except:
  332. pass
  333. raise SystemExit(code)
  334. builtins.quit = Quitter("quit")
  335. builtins.exit = Quitter("exit")
  336. class _Printer(object):
  337. """interactive prompt objects for printing the license text, a list of
  338. contributors and the copyright notice."""
  339. MAXLINES = 23
  340. def __init__(self, name, data, files=(), dirs=()):
  341. self.__name = name
  342. self.__data = data
  343. self.__files = files
  344. self.__dirs = dirs
  345. self.__lines = None
  346. def __setup(self):
  347. if self.__lines:
  348. return
  349. data = None
  350. for dir in self.__dirs:
  351. for filename in self.__files:
  352. filename = os.path.join(dir, filename)
  353. try:
  354. fp = open(filename, "r")
  355. data = fp.read()
  356. fp.close()
  357. break
  358. except IOError:
  359. pass
  360. if data:
  361. break
  362. if not data:
  363. data = self.__data
  364. self.__lines = data.split("\n")
  365. self.__linecnt = len(self.__lines)
  366. def __repr__(self):
  367. self.__setup()
  368. if len(self.__lines) <= self.MAXLINES:
  369. return "\n".join(self.__lines)
  370. else:
  371. return "Type %s() to see the full %s text" % ((self.__name,) * 2)
  372. def __call__(self):
  373. self.__setup()
  374. prompt = "Hit Return for more, or q (and Return) to quit: "
  375. lineno = 0
  376. while 1:
  377. try:
  378. for i in range(lineno, lineno + self.MAXLINES):
  379. print(self.__lines[i])
  380. except IndexError:
  381. break
  382. else:
  383. lineno += self.MAXLINES
  384. key = None
  385. while key is None:
  386. try:
  387. key = raw_input(prompt)
  388. except NameError:
  389. key = input(prompt)
  390. if key not in ("", "q"):
  391. key = None
  392. if key == "q":
  393. break
  394. def setcopyright():
  395. """Set 'copyright' and 'credits' in __builtin__"""
  396. builtins.copyright = _Printer("copyright", sys.copyright)
  397. if _is_pypy:
  398. builtins.credits = _Printer("credits", "PyPy is maintained by the PyPy developers: http://pypy.org/")
  399. else:
  400. builtins.credits = _Printer(
  401. "credits",
  402. """\
  403. Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  404. for supporting Python development. See www.python.org for more information.""",
  405. )
  406. here = os.path.dirname(os.__file__)
  407. builtins.license = _Printer(
  408. "license",
  409. "See https://www.python.org/psf/license/",
  410. ["LICENSE.txt", "LICENSE"],
  411. [sys.prefix, os.path.join(here, os.pardir), here, os.curdir],
  412. )
  413. class _Helper(object):
  414. """Define the built-in 'help'.
  415. This is a wrapper around pydoc.help (with a twist).
  416. """
  417. def __repr__(self):
  418. return "Type help() for interactive help, " "or help(object) for help about object."
  419. def __call__(self, *args, **kwds):
  420. import pydoc
  421. return pydoc.help(*args, **kwds)
  422. def sethelper():
  423. builtins.help = _Helper()
  424. def aliasmbcs():
  425. """On Windows, some default encodings are not provided by Python,
  426. while they are always available as "mbcs" in each locale. Make
  427. them usable by aliasing to "mbcs" in such a case."""
  428. if sys.platform == "win32":
  429. import locale, codecs
  430. enc = locale.getdefaultlocale()[1]
  431. if enc.startswith("cp"): # "cp***" ?
  432. try:
  433. codecs.lookup(enc)
  434. except LookupError:
  435. import encodings
  436. encodings._cache[enc] = encodings._unknown
  437. encodings.aliases.aliases[enc] = "mbcs"
  438. def setencoding():
  439. """Set the string encoding used by the Unicode implementation. The
  440. default is 'ascii', but if you're willing to experiment, you can
  441. change this."""
  442. encoding = "ascii" # Default value set by _PyUnicode_Init()
  443. if 0:
  444. # Enable to support locale aware default string encodings.
  445. import locale
  446. loc = locale.getdefaultlocale()
  447. if loc[1]:
  448. encoding = loc[1]
  449. if 0:
  450. # Enable to switch off string to Unicode coercion and implicit
  451. # Unicode to string conversion.
  452. encoding = "undefined"
  453. if encoding != "ascii":
  454. # On Non-Unicode builds this will raise an AttributeError...
  455. sys.setdefaultencoding(encoding) # Needs Python Unicode build !
  456. def execsitecustomize():
  457. """Run custom site specific code, if available."""
  458. try:
  459. import sitecustomize
  460. except ImportError:
  461. pass
  462. def virtual_install_main_packages():
  463. f = open(os.path.join(os.path.dirname(__file__), "orig-prefix.txt"))
  464. sys.real_prefix = f.read().strip()
  465. f.close()
  466. pos = 2
  467. hardcoded_relative_dirs = []
  468. if sys.path[0] == "":
  469. pos += 1
  470. if _is_pypy:
  471. if sys.version_info > (3, 2):
  472. cpyver = "%d" % sys.version_info[0]
  473. elif sys.pypy_version_info >= (1, 5):
  474. cpyver = "%d.%d" % sys.version_info[:2]
  475. else:
  476. cpyver = "%d.%d.%d" % sys.version_info[:3]
  477. paths = [os.path.join(sys.real_prefix, "lib_pypy"), os.path.join(sys.real_prefix, "lib-python", cpyver)]
  478. if sys.pypy_version_info < (1, 9):
  479. paths.insert(1, os.path.join(sys.real_prefix, "lib-python", "modified-%s" % cpyver))
  480. hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below
  481. #
  482. # This is hardcoded in the Python executable, but relative to sys.prefix:
  483. for path in paths[:]:
  484. plat_path = os.path.join(path, "plat-%s" % sys.platform)
  485. if os.path.exists(plat_path):
  486. paths.append(plat_path)
  487. elif sys.platform == "win32":
  488. paths = [os.path.join(sys.real_prefix, "Lib"), os.path.join(sys.real_prefix, "DLLs")]
  489. else:
  490. paths = [os.path.join(sys.real_prefix, "lib", "python{}.{}".format(*sys.version_info))]
  491. hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below
  492. lib64_path = os.path.join(sys.real_prefix, "lib64", "python{}.{}".format(*sys.version_info))
  493. if os.path.exists(lib64_path):
  494. if _is_64bit:
  495. paths.insert(0, lib64_path)
  496. else:
  497. paths.append(lib64_path)
  498. # This is hardcoded in the Python executable, but relative to
  499. # sys.prefix. Debian change: we need to add the multiarch triplet
  500. # here, which is where the real stuff lives. As per PEP 421, in
  501. # Python 3.3+, this lives in sys.implementation, while in Python 2.7
  502. # it lives in sys.
  503. try:
  504. arch = getattr(sys, "implementation", sys)._multiarch
  505. except AttributeError:
  506. # This is a non-multiarch aware Python. Fallback to the old way.
  507. arch = sys.platform
  508. plat_path = os.path.join(sys.real_prefix, "lib", "python{}.{}".format(*sys.version_info), "plat-%s" % arch)
  509. if os.path.exists(plat_path):
  510. paths.append(plat_path)
  511. # This is hardcoded in the Python executable, but
  512. # relative to sys.prefix, so we have to fix up:
  513. for path in list(paths):
  514. tk_dir = os.path.join(path, "lib-tk")
  515. if os.path.exists(tk_dir):
  516. paths.append(tk_dir)
  517. # These are hardcoded in the Apple's Python executable,
  518. # but relative to sys.prefix, so we have to fix them up:
  519. if sys.platform == "darwin":
  520. hardcoded_paths = [
  521. os.path.join(relative_dir, module)
  522. for relative_dir in hardcoded_relative_dirs
  523. for module in ("plat-darwin", "plat-mac", "plat-mac/lib-scriptpackages")
  524. ]
  525. for path in hardcoded_paths:
  526. if os.path.exists(path):
  527. paths.append(path)
  528. sys.path.extend(paths)
  529. def force_global_eggs_after_local_site_packages():
  530. """
  531. Force easy_installed eggs in the global environment to get placed
  532. in sys.path after all packages inside the virtualenv. This
  533. maintains the "least surprise" result that packages in the
  534. virtualenv always mask global packages, never the other way
  535. around.
  536. """
  537. egginsert = getattr(sys, "__egginsert", 0)
  538. for i, path in enumerate(sys.path):
  539. if i > egginsert and path.startswith(sys.prefix):
  540. egginsert = i
  541. sys.__egginsert = egginsert + 1
  542. def virtual_addsitepackages(known_paths):
  543. force_global_eggs_after_local_site_packages()
  544. return addsitepackages(known_paths, sys_prefix=sys.real_prefix)
  545. def execusercustomize():
  546. """Run custom user specific code, if available."""
  547. try:
  548. import usercustomize
  549. except ImportError:
  550. pass
  551. def enablerlcompleter():
  552. """Enable default readline configuration on interactive prompts, by
  553. registering a sys.__interactivehook__.
  554. If the readline module can be imported, the hook will set the Tab key
  555. as completion key and register ~/.python_history as history file.
  556. This can be overridden in the sitecustomize or usercustomize module,
  557. or in a PYTHONSTARTUP file.
  558. """
  559. def register_readline():
  560. import atexit
  561. try:
  562. import readline
  563. import rlcompleter
  564. except ImportError:
  565. return
  566. # Reading the initialization (config) file may not be enough to set a
  567. # completion key, so we set one first and then read the file.
  568. readline_doc = getattr(readline, "__doc__", "")
  569. if readline_doc is not None and "libedit" in readline_doc:
  570. readline.parse_and_bind("bind ^I rl_complete")
  571. else:
  572. readline.parse_and_bind("tab: complete")
  573. try:
  574. readline.read_init_file()
  575. except OSError:
  576. # An OSError here could have many causes, but the most likely one
  577. # is that there's no .inputrc file (or .editrc file in the case of
  578. # Mac OS X + libedit) in the expected location. In that case, we
  579. # want to ignore the exception.
  580. pass
  581. if readline.get_current_history_length() == 0:
  582. # If no history was loaded, default to .python_history.
  583. # The guard is necessary to avoid doubling history size at
  584. # each interpreter exit when readline was already configured
  585. # through a PYTHONSTARTUP hook, see:
  586. # http://bugs.python.org/issue5845#msg198636
  587. history = os.path.join(os.path.expanduser("~"), ".python_history")
  588. try:
  589. readline.read_history_file(history)
  590. except OSError:
  591. pass
  592. def write_history():
  593. try:
  594. readline.write_history_file(history)
  595. except (FileNotFoundError, PermissionError):
  596. # home directory does not exist or is not writable
  597. # https://bugs.python.org/issue19891
  598. pass
  599. atexit.register(write_history)
  600. sys.__interactivehook__ = register_readline
  601. if _is_pypy:
  602. def import_builtin_stuff():
  603. """PyPy specific: some built-in modules should be pre-imported because
  604. some programs expect them to be in sys.modules on startup. This is ported
  605. from PyPy's site.py.
  606. """
  607. import encodings
  608. if "exceptions" in sys.builtin_module_names:
  609. import exceptions
  610. if "zipimport" in sys.builtin_module_names:
  611. import zipimport
  612. def main():
  613. global ENABLE_USER_SITE
  614. virtual_install_main_packages()
  615. if _is_pypy:
  616. import_builtin_stuff()
  617. abs__file__()
  618. paths_in_sys = removeduppaths()
  619. if os.name == "posix" and sys.path and os.path.basename(sys.path[-1]) == "Modules":
  620. addbuilddir()
  621. GLOBAL_SITE_PACKAGES = not os.path.exists(os.path.join(os.path.dirname(__file__), "no-global-site-packages.txt"))
  622. if not GLOBAL_SITE_PACKAGES:
  623. ENABLE_USER_SITE = False
  624. if ENABLE_USER_SITE is None:
  625. ENABLE_USER_SITE = check_enableusersite()
  626. paths_in_sys = addsitepackages(paths_in_sys)
  627. paths_in_sys = addusersitepackages(paths_in_sys)
  628. if GLOBAL_SITE_PACKAGES:
  629. paths_in_sys = virtual_addsitepackages(paths_in_sys)
  630. if sys.platform == "os2emx":
  631. setBEGINLIBPATH()
  632. setquit()
  633. setcopyright()
  634. sethelper()
  635. if sys.version_info[0] == 3:
  636. enablerlcompleter()
  637. aliasmbcs()
  638. setencoding()
  639. execsitecustomize()
  640. if ENABLE_USER_SITE:
  641. execusercustomize()
  642. # Remove sys.setdefaultencoding() so that users cannot change the
  643. # encoding after initialization. The test for presence is needed when
  644. # this module is run as a script, because this code is executed twice.
  645. if hasattr(sys, "setdefaultencoding"):
  646. del sys.setdefaultencoding
  647. main()
  648. def _script():
  649. help = """\
  650. %s [--user-base] [--user-site]
  651. Without arguments print some useful information
  652. With arguments print the value of USER_BASE and/or USER_SITE separated
  653. by '%s'.
  654. Exit codes with --user-base or --user-site:
  655. 0 - user site directory is enabled
  656. 1 - user site directory is disabled by user
  657. 2 - uses site directory is disabled by super user
  658. or for security reasons
  659. >2 - unknown error
  660. """
  661. args = sys.argv[1:]
  662. if not args:
  663. print("sys.path = [")
  664. for dir in sys.path:
  665. print(" {!r},".format(dir))
  666. print("]")
  667. def exists(path):
  668. if os.path.isdir(path):
  669. return "exists"
  670. else:
  671. return "doesn't exist"
  672. print("USER_BASE: {!r} ({})".format(USER_BASE, exists(USER_BASE)))
  673. print("USER_SITE: {!r} ({})".format(USER_SITE, exists(USER_SITE)))
  674. print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
  675. sys.exit(0)
  676. buffer = []
  677. if "--user-base" in args:
  678. buffer.append(USER_BASE)
  679. if "--user-site" in args:
  680. buffer.append(USER_SITE)
  681. if buffer:
  682. print(os.pathsep.join(buffer))
  683. if ENABLE_USER_SITE:
  684. sys.exit(0)
  685. elif ENABLE_USER_SITE is False:
  686. sys.exit(1)
  687. elif ENABLE_USER_SITE is None:
  688. sys.exit(2)
  689. else:
  690. sys.exit(3)
  691. else:
  692. import textwrap
  693. print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
  694. sys.exit(10)
  695. if __name__ == "__main__":
  696. _script()