site.py 27 KB

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