site.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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 (including Mac OSX), it starts with sys.prefix and
  12. sys.exec_prefix (if different) and appends
  13. lib/python<version>/site-packages as well as lib/site-python.
  14. On other platforms (such as Windows), it tries each of the
  15. prefixes directly, as well as with lib/site-packages appended. The
  16. resulting directories, if they exist, are appended to sys.path, and
  17. also inspected for path configuration files.
  18. A path configuration file is a file whose name has the form
  19. <package>.pth; its contents are additional directories (one per line)
  20. to be added to sys.path. Non-existing directories (or
  21. non-directories) are never added to sys.path; no directory is added to
  22. sys.path more than once. Blank lines and lines beginning with
  23. '#' are skipped. Lines starting with 'import' are executed.
  24. For example, suppose sys.prefix and sys.exec_prefix are set to
  25. /usr/local and there is a directory /usr/local/lib/python2.5/site-packages
  26. with three subdirectories, foo, bar and spam, and two path
  27. configuration files, foo.pth and bar.pth. Assume foo.pth contains the
  28. following:
  29. # foo package configuration
  30. foo
  31. bar
  32. bletch
  33. and bar.pth contains:
  34. # bar package configuration
  35. bar
  36. Then the following directories are added to sys.path, in this order:
  37. /usr/local/lib/python2.5/site-packages/bar
  38. /usr/local/lib/python2.5/site-packages/foo
  39. Note that bletch is omitted because it doesn't exist; bar precedes foo
  40. because bar.pth comes alphabetically before foo.pth; and spam is
  41. omitted because it is not mentioned in either path configuration file.
  42. After these path manipulations, an attempt is made to import a module
  43. named sitecustomize, which can perform arbitrary additional
  44. site-specific customizations. If this import fails with an
  45. ImportError exception, it is silently ignored.
  46. """
  47. import sys
  48. import os
  49. import __builtin__
  50. import traceback
  51. # Prefixes for site-packages; add additional prefixes like /usr/local here
  52. PREFIXES = [sys.prefix, sys.exec_prefix]
  53. # Enable per user site-packages directory
  54. # set it to False to disable the feature or True to force the feature
  55. ENABLE_USER_SITE = None
  56. # for distutils.commands.install
  57. # These values are initialized by the getuserbase() and getusersitepackages()
  58. # functions, through the main() function when Python starts.
  59. USER_SITE = None
  60. USER_BASE = None
  61. def makepath(*paths):
  62. dir = os.path.join(*paths)
  63. try:
  64. dir = os.path.abspath(dir)
  65. except OSError:
  66. pass
  67. return dir, os.path.normcase(dir)
  68. def abs__file__():
  69. """Set all module' __file__ attribute to an absolute path"""
  70. for m in sys.modules.values():
  71. if hasattr(m, '__loader__'):
  72. continue # don't mess with a PEP 302-supplied __file__
  73. try:
  74. m.__file__ = os.path.abspath(m.__file__)
  75. except (AttributeError, OSError):
  76. pass
  77. def removeduppaths():
  78. """ Remove duplicate entries from sys.path along with making them
  79. absolute"""
  80. # This ensures that the initial path provided by the interpreter contains
  81. # only absolute pathnames, even if we're running from the build directory.
  82. L = []
  83. known_paths = set()
  84. for dir in sys.path:
  85. # Filter out duplicate paths (on case-insensitive file systems also
  86. # if they only differ in case); turn relative paths into absolute
  87. # paths.
  88. dir, dircase = makepath(dir)
  89. if not dircase in known_paths:
  90. L.append(dir)
  91. known_paths.add(dircase)
  92. sys.path[:] = L
  93. return known_paths
  94. def _init_pathinfo():
  95. """Return a set containing all existing directory entries from sys.path"""
  96. d = set()
  97. for dir in sys.path:
  98. try:
  99. if os.path.isdir(dir):
  100. dir, dircase = makepath(dir)
  101. d.add(dircase)
  102. except TypeError:
  103. continue
  104. return d
  105. def addpackage(sitedir, name, known_paths):
  106. """Process a .pth file within the site-packages directory:
  107. For each line in the file, either combine it with sitedir to a path
  108. and add that to known_paths, or execute it if it starts with 'import '.
  109. """
  110. if known_paths is None:
  111. _init_pathinfo()
  112. reset = 1
  113. else:
  114. reset = 0
  115. fullname = os.path.join(sitedir, name)
  116. try:
  117. f = open(fullname, "rU")
  118. except IOError:
  119. return
  120. with f:
  121. for n, line in enumerate(f):
  122. if line.startswith("#"):
  123. continue
  124. try:
  125. if line.startswith(("import ", "import\t")):
  126. exec line
  127. continue
  128. line = line.rstrip()
  129. dir, dircase = makepath(sitedir, line)
  130. if not dircase in known_paths and os.path.exists(dir):
  131. sys.path.append(dir)
  132. known_paths.add(dircase)
  133. except Exception as err:
  134. print >>sys.stderr, "Error processing line {:d} of {}:\n".format(
  135. n+1, fullname)
  136. for record in traceback.format_exception(*sys.exc_info()):
  137. for line in record.splitlines():
  138. print >>sys.stderr, ' '+line
  139. print >>sys.stderr, "\nRemainder of file ignored"
  140. break
  141. if reset:
  142. known_paths = None
  143. return known_paths
  144. def addsitedir(sitedir, known_paths=None):
  145. """Add 'sitedir' argument to sys.path if missing and handle .pth files in
  146. 'sitedir'"""
  147. if known_paths is None:
  148. known_paths = _init_pathinfo()
  149. reset = 1
  150. else:
  151. reset = 0
  152. sitedir, sitedircase = makepath(sitedir)
  153. if not sitedircase in known_paths:
  154. sys.path.append(sitedir) # Add path component
  155. try:
  156. names = os.listdir(sitedir)
  157. except os.error:
  158. return
  159. dotpth = os.extsep + "pth"
  160. names = [name for name in names if name.endswith(dotpth)]
  161. for name in sorted(names):
  162. addpackage(sitedir, name, known_paths)
  163. if reset:
  164. known_paths = None
  165. return known_paths
  166. def check_enableusersite():
  167. """Check if user site directory is safe for inclusion
  168. The function tests for the command line flag (including environment var),
  169. process uid/gid equal to effective uid/gid.
  170. None: Disabled for security reasons
  171. False: Disabled by user (command line option)
  172. True: Safe and enabled
  173. """
  174. if sys.flags.no_user_site:
  175. return False
  176. if hasattr(os, "getuid") and hasattr(os, "geteuid"):
  177. # check process uid == effective uid
  178. if os.geteuid() != os.getuid():
  179. return None
  180. if hasattr(os, "getgid") and hasattr(os, "getegid"):
  181. # check process gid == effective gid
  182. if os.getegid() != os.getgid():
  183. return None
  184. return True
  185. def getuserbase():
  186. """Returns the `user base` directory path.
  187. The `user base` directory can be used to store data. If the global
  188. variable ``USER_BASE`` is not initialized yet, this function will also set
  189. it.
  190. """
  191. global USER_BASE
  192. if USER_BASE is not None:
  193. return USER_BASE
  194. from sysconfig import get_config_var
  195. USER_BASE = get_config_var('userbase')
  196. return USER_BASE
  197. def getusersitepackages():
  198. """Returns the user-specific site-packages directory path.
  199. If the global variable ``USER_SITE`` is not initialized yet, this
  200. function will also set it.
  201. """
  202. global USER_SITE
  203. user_base = getuserbase() # this will also set USER_BASE
  204. if USER_SITE is not None:
  205. return USER_SITE
  206. from sysconfig import get_path
  207. import os
  208. if sys.platform == 'darwin':
  209. from sysconfig import get_config_var
  210. if get_config_var('PYTHONFRAMEWORK'):
  211. USER_SITE = get_path('purelib', 'osx_framework_user')
  212. return USER_SITE
  213. USER_SITE = get_path('purelib', '%s_user' % os.name)
  214. return USER_SITE
  215. def addusersitepackages(known_paths):
  216. """Add a per user site-package to sys.path
  217. Each user has its own python directory with site-packages in the
  218. home directory.
  219. """
  220. # get the per user site-package path
  221. # this call will also make sure USER_BASE and USER_SITE are set
  222. user_site = getusersitepackages()
  223. if ENABLE_USER_SITE and os.path.isdir(user_site):
  224. addsitedir(user_site, known_paths)
  225. return known_paths
  226. def getsitepackages():
  227. """Returns a list containing all global site-packages directories
  228. (and possibly site-python).
  229. For each directory present in the global ``PREFIXES``, this function
  230. will find its `site-packages` subdirectory depending on the system
  231. environment, and will return a list of full paths.
  232. """
  233. sitepackages = []
  234. seen = set()
  235. for prefix in PREFIXES:
  236. if not prefix or prefix in seen:
  237. continue
  238. seen.add(prefix)
  239. if sys.platform in ('os2emx', 'riscos'):
  240. sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
  241. elif os.sep == '/':
  242. sitepackages.append(os.path.join(prefix, sys.lib,
  243. "python" + sys.version[:3],
  244. "site-packages"))
  245. sitepackages.append(os.path.join(prefix, sys.lib, "site-python"))
  246. if sys.lib != "lib":
  247. sitepackages.append(os.path.join(prefix, "lib",
  248. "python" + sys.version[:3],
  249. "site-packages"))
  250. sitepackages.append(os.path.join(prefix, "lib", "site-python"))
  251. else:
  252. sitepackages.append(prefix)
  253. sitepackages.append(os.path.join(prefix, sys.lib, "site-packages"))
  254. if sys.platform == "darwin":
  255. # for framework builds *only* we add the standard Apple
  256. # locations.
  257. from sysconfig import get_config_var
  258. framework = get_config_var("PYTHONFRAMEWORK")
  259. if framework:
  260. sitepackages.append(
  261. os.path.join("/Library", framework,
  262. sys.version[:3], "site-packages"))
  263. return sitepackages
  264. def addsitepackages(known_paths):
  265. """Add site-packages (and possibly site-python) to sys.path"""
  266. for sitedir in getsitepackages():
  267. if os.path.isdir(sitedir):
  268. addsitedir(sitedir, known_paths)
  269. return known_paths
  270. def setBEGINLIBPATH():
  271. """The OS/2 EMX port has optional extension modules that do double duty
  272. as DLLs (and must use the .DLL file extension) for other extensions.
  273. The library search path needs to be amended so these will be found
  274. during module import. Use BEGINLIBPATH so that these are at the start
  275. of the library search path.
  276. """
  277. dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
  278. libpath = os.environ['BEGINLIBPATH'].split(';')
  279. if libpath[-1]:
  280. libpath.append(dllpath)
  281. else:
  282. libpath[-1] = dllpath
  283. os.environ['BEGINLIBPATH'] = ';'.join(libpath)
  284. def setquit():
  285. """Define new builtins 'quit' and 'exit'.
  286. These are objects which make the interpreter exit when called.
  287. The repr of each object contains a hint at how it works.
  288. """
  289. if os.sep == ':':
  290. eof = 'Cmd-Q'
  291. elif os.sep == '\\':
  292. eof = 'Ctrl-Z plus Return'
  293. else:
  294. eof = 'Ctrl-D (i.e. EOF)'
  295. class Quitter(object):
  296. def __init__(self, name):
  297. self.name = name
  298. def __repr__(self):
  299. return 'Use %s() or %s to exit' % (self.name, eof)
  300. def __call__(self, code=None):
  301. # Shells like IDLE catch the SystemExit, but listen when their
  302. # stdin wrapper is closed.
  303. try:
  304. sys.stdin.close()
  305. except:
  306. pass
  307. raise SystemExit(code)
  308. __builtin__.quit = Quitter('quit')
  309. __builtin__.exit = Quitter('exit')
  310. class _Printer(object):
  311. """interactive prompt objects for printing the license text, a list of
  312. contributors and the copyright notice."""
  313. MAXLINES = 23
  314. def __init__(self, name, data, files=(), dirs=()):
  315. self.__name = name
  316. self.__data = data
  317. self.__files = files
  318. self.__dirs = dirs
  319. self.__lines = None
  320. def __setup(self):
  321. if self.__lines:
  322. return
  323. data = None
  324. for dir in self.__dirs:
  325. for filename in self.__files:
  326. filename = os.path.join(dir, filename)
  327. try:
  328. fp = file(filename, "rU")
  329. data = fp.read()
  330. fp.close()
  331. break
  332. except IOError:
  333. pass
  334. if data:
  335. break
  336. if not data:
  337. data = self.__data
  338. self.__lines = data.split('\n')
  339. self.__linecnt = len(self.__lines)
  340. def __repr__(self):
  341. self.__setup()
  342. if len(self.__lines) <= self.MAXLINES:
  343. return "\n".join(self.__lines)
  344. else:
  345. return "Type %s() to see the full %s text" % ((self.__name,)*2)
  346. def __call__(self):
  347. self.__setup()
  348. prompt = 'Hit Return for more, or q (and Return) to quit: '
  349. lineno = 0
  350. while 1:
  351. try:
  352. for i in range(lineno, lineno + self.MAXLINES):
  353. print self.__lines[i]
  354. except IndexError:
  355. break
  356. else:
  357. lineno += self.MAXLINES
  358. key = None
  359. while key is None:
  360. key = raw_input(prompt)
  361. if key not in ('', 'q'):
  362. key = None
  363. if key == 'q':
  364. break
  365. def setcopyright():
  366. """Set 'copyright' and 'credits' in __builtin__"""
  367. __builtin__.copyright = _Printer("copyright", sys.copyright)
  368. if sys.platform[:4] == 'java':
  369. __builtin__.credits = _Printer(
  370. "credits",
  371. "Jython is maintained by the Jython developers (www.jython.org).")
  372. else:
  373. __builtin__.credits = _Printer("credits", """\
  374. Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  375. for supporting Python development. See www.python.org for more information.""")
  376. here = os.path.dirname(os.__file__)
  377. __builtin__.license = _Printer(
  378. "license", "See https://www.python.org/psf/license/",
  379. ["LICENSE.txt", "LICENSE"],
  380. [os.path.join(here, os.pardir), here, os.curdir])
  381. class _Helper(object):
  382. """Define the builtin 'help'.
  383. This is a wrapper around pydoc.help (with a twist).
  384. """
  385. def __repr__(self):
  386. return "Type help() for interactive help, " \
  387. "or help(object) for help about object."
  388. def __call__(self, *args, **kwds):
  389. import pydoc
  390. return pydoc.help(*args, **kwds)
  391. def sethelper():
  392. __builtin__.help = _Helper()
  393. def aliasmbcs():
  394. """On Windows, some default encodings are not provided by Python,
  395. while they are always available as "mbcs" in each locale. Make
  396. them usable by aliasing to "mbcs" in such a case."""
  397. if sys.platform == 'win32':
  398. import locale, codecs
  399. enc = locale.getdefaultlocale()[1]
  400. if enc.startswith('cp'): # "cp***" ?
  401. try:
  402. codecs.lookup(enc)
  403. except LookupError:
  404. import encodings
  405. encodings._cache[enc] = encodings._unknown
  406. encodings.aliases.aliases[enc] = 'mbcs'
  407. def setencoding():
  408. """Set the string encoding used by the Unicode implementation. The
  409. default is 'ascii', but if you're willing to experiment, you can
  410. change this."""
  411. encoding = "ascii" # Default value set by _PyUnicode_Init()
  412. if 0:
  413. # Enable to support locale aware default string encodings.
  414. import locale
  415. loc = locale.getdefaultlocale()
  416. if loc[1]:
  417. encoding = loc[1]
  418. if 0:
  419. # Enable to switch off string to Unicode coercion and implicit
  420. # Unicode to string conversion.
  421. encoding = "undefined"
  422. if encoding != "ascii":
  423. # On Non-Unicode builds this will raise an AttributeError...
  424. sys.setdefaultencoding(encoding) # Needs Python Unicode build !
  425. def execsitecustomize():
  426. """Run custom site specific code, if available."""
  427. try:
  428. import sitecustomize
  429. except ImportError:
  430. pass
  431. except Exception:
  432. if sys.flags.verbose:
  433. sys.excepthook(*sys.exc_info())
  434. else:
  435. print >>sys.stderr, \
  436. "'import sitecustomize' failed; use -v for traceback"
  437. def execusercustomize():
  438. """Run custom user specific code, if available."""
  439. try:
  440. import usercustomize
  441. except ImportError:
  442. pass
  443. except Exception:
  444. if sys.flags.verbose:
  445. sys.excepthook(*sys.exc_info())
  446. else:
  447. print>>sys.stderr, \
  448. "'import usercustomize' failed; use -v for traceback"
  449. def main():
  450. global ENABLE_USER_SITE
  451. abs__file__()
  452. known_paths = removeduppaths()
  453. if ENABLE_USER_SITE is None:
  454. ENABLE_USER_SITE = check_enableusersite()
  455. known_paths = addusersitepackages(known_paths)
  456. known_paths = addsitepackages(known_paths)
  457. if sys.platform == 'os2emx':
  458. setBEGINLIBPATH()
  459. setquit()
  460. setcopyright()
  461. sethelper()
  462. aliasmbcs()
  463. setencoding()
  464. execsitecustomize()
  465. if ENABLE_USER_SITE:
  466. execusercustomize()
  467. # Remove sys.setdefaultencoding() so that users cannot change the
  468. # encoding after initialization. The test for presence is needed when
  469. # this module is run as a script, because this code is executed twice.
  470. if hasattr(sys, "setdefaultencoding"):
  471. del sys.setdefaultencoding
  472. main()
  473. def _script():
  474. help = """\
  475. %s [--user-base] [--user-site]
  476. Without arguments print some useful information
  477. With arguments print the value of USER_BASE and/or USER_SITE separated
  478. by '%s'.
  479. Exit codes with --user-base or --user-site:
  480. 0 - user site directory is enabled
  481. 1 - user site directory is disabled by user
  482. 2 - uses site directory is disabled by super user
  483. or for security reasons
  484. >2 - unknown error
  485. """
  486. args = sys.argv[1:]
  487. if not args:
  488. print "sys.path = ["
  489. for dir in sys.path:
  490. print " %r," % (dir,)
  491. print "]"
  492. print "USER_BASE: %r (%s)" % (USER_BASE,
  493. "exists" if os.path.isdir(USER_BASE) else "doesn't exist")
  494. print "USER_SITE: %r (%s)" % (USER_SITE,
  495. "exists" if os.path.isdir(USER_SITE) else "doesn't exist")
  496. print "ENABLE_USER_SITE: %r" % ENABLE_USER_SITE
  497. sys.exit(0)
  498. buffer = []
  499. if '--user-base' in args:
  500. buffer.append(USER_BASE)
  501. if '--user-site' in args:
  502. buffer.append(USER_SITE)
  503. if buffer:
  504. print os.pathsep.join(buffer)
  505. if ENABLE_USER_SITE:
  506. sys.exit(0)
  507. elif ENABLE_USER_SITE is False:
  508. sys.exit(1)
  509. elif ENABLE_USER_SITE is None:
  510. sys.exit(2)
  511. else:
  512. sys.exit(3)
  513. else:
  514. import textwrap
  515. print textwrap.dedent(help % (sys.argv[0], os.pathsep))
  516. sys.exit(10)
  517. if __name__ == '__main__':
  518. _script()