You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

851 lines
29 KiB

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