site.py 27 KB

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