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.

site.py 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 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. On other platforms (mainly Mac and Windows), it uses just sys.prefix
  14. \(and sys.exec_prefix, if different, but this is unlikely). The
  15. resulting directories, if they exist, are appended to sys.path, and
  16. also inspected for path configuration files.
  17. A path configuration file is a file whose name has the form
  18. <package>.pth; its contents are additional directories (one per line)
  19. to be added to sys.path. Non-existing directories (or
  20. non-directories) are never added to sys.path; no directory is added to
  21. sys.path more than once. Blank lines and lines beginning with
  22. \code{#} are skipped. Lines starting with \code{import} are executed.
  23. For example, suppose sys.prefix and sys.exec_prefix are set to
  24. /usr/local and there is a directory /usr/local/lib/python1.5/site-packages
  25. with three subdirectories, foo, bar and spam, and two path
  26. configuration files, foo.pth and bar.pth. Assume foo.pth contains the
  27. following:
  28. # foo package configuration
  29. foo
  30. bar
  31. bletch
  32. and bar.pth contains:
  33. # bar package configuration
  34. bar
  35. Then the following directories are added to sys.path, in this order:
  36. /usr/local/lib/python1.5/site-packages/bar
  37. /usr/local/lib/python1.5/site-packages/foo
  38. Note that bletch is omitted because it doesn't exist; bar precedes foo
  39. because bar.pth comes alphabetically before foo.pth; and spam is
  40. omitted because it is not mentioned in either path configuration file.
  41. After these path manipulations, an attempt is made to import a module
  42. named sitecustomize, which can perform arbitrary additional
  43. site-specific customizations. If this import fails with an
  44. ImportError exception, it is silently ignored.
  45. """
  46. import sys, os
  47. if os.sep==".":
  48. endsep = "/"
  49. else:
  50. endsep = "."
  51. def makepath(*paths):
  52. dir = os.path.abspath(os.path.join(*paths))
  53. return dir, os.path.normcase(dir)
  54. for m in sys.modules.values():
  55. if hasattr(m, "__file__") and m.__file__:
  56. m.__file__ = os.path.abspath(m.__file__)
  57. del m
  58. # This ensures that the initial path provided by the interpreter contains
  59. # only absolute pathnames, even if we're running from the build directory.
  60. L = []
  61. dirs_in_sys_path = {}
  62. for dir in sys.path:
  63. dir, dircase = makepath(dir)
  64. if not dirs_in_sys_path.has_key(dircase):
  65. L.append(dir)
  66. dirs_in_sys_path[dircase] = 1
  67. sys.path[:] = L
  68. del dir, L
  69. # Append ./build/lib.<platform> in case we're running in the build dir
  70. # (especially for Guido :-)
  71. if os.name == "posix" and os.path.basename(sys.path[-1]) == "Modules":
  72. from distutils.util import get_platform
  73. s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
  74. s = os.path.join(os.path.dirname(sys.path[-1]), s)
  75. sys.path.append(s)
  76. del get_platform, s
  77. def addsitedir(sitedir):
  78. sitedir, sitedircase = makepath(sitedir)
  79. if not dirs_in_sys_path.has_key(sitedircase):
  80. sys.path.append(sitedir) # Add path component
  81. try:
  82. names = os.listdir(sitedir)
  83. except os.error:
  84. return
  85. names.sort()
  86. for name in names:
  87. if name[-4:] == endsep + "pth":
  88. addpackage(sitedir, name)
  89. def addpackage(sitedir, name):
  90. fullname = os.path.join(sitedir, name)
  91. try:
  92. f = open(fullname)
  93. except IOError:
  94. return
  95. while 1:
  96. dir = f.readline()
  97. if not dir:
  98. break
  99. if dir[0] == '#':
  100. continue
  101. if dir.startswith("import"):
  102. exec dir
  103. continue
  104. if dir[-1] == '\n':
  105. dir = dir[:-1]
  106. dir, dircase = makepath(sitedir, dir)
  107. if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir):
  108. sys.path.append(dir)
  109. dirs_in_sys_path[dircase] = 1
  110. prefixes = [sys.prefix]
  111. if sys.exec_prefix != sys.prefix:
  112. prefixes.append(sys.exec_prefix)
  113. for prefix in prefixes:
  114. if prefix:
  115. if os.sep == '/':
  116. sitedirs = [os.path.join(prefix,
  117. "lib",
  118. "python" + sys.version[:3],
  119. "site-packages"),
  120. os.path.join(prefix, "lib", "site-python")]
  121. elif os.sep == ':':
  122. sitedirs = [os.path.join(prefix, "lib", "site-packages")]
  123. else:
  124. sitedirs = [prefix]
  125. for sitedir in sitedirs:
  126. if os.path.isdir(sitedir):
  127. addsitedir(sitedir)
  128. # Define new built-ins 'quit' and 'exit'.
  129. # These are simply strings that display a hint on how to exit.
  130. if os.sep == ':':
  131. exit = 'Use Cmd-Q to quit.'
  132. elif os.sep == '\\':
  133. exit = 'Use Ctrl-Z plus Return to exit.'
  134. else:
  135. exit = 'Use Ctrl-D (i.e. EOF) to exit.'
  136. import __builtin__
  137. __builtin__.quit = __builtin__.exit = exit
  138. del exit
  139. # interactive prompt objects for printing the license text, a list of
  140. # contributors and the copyright notice.
  141. class _Printer:
  142. MAXLINES = 23
  143. def __init__(self, name, data, files=(), dirs=()):
  144. self.__name = name
  145. self.__data = data
  146. self.__files = files
  147. self.__dirs = dirs
  148. self.__lines = None
  149. def __setup(self):
  150. if self.__lines:
  151. return
  152. data = None
  153. for dir in self.__dirs:
  154. for file in self.__files:
  155. file = os.path.join(dir, file)
  156. try:
  157. fp = open(file)
  158. data = fp.read()
  159. fp.close()
  160. break
  161. except IOError:
  162. pass
  163. if data:
  164. break
  165. if not data:
  166. data = self.__data
  167. self.__lines = data.split('\n')
  168. self.__linecnt = len(self.__lines)
  169. def __repr__(self):
  170. self.__setup()
  171. if len(self.__lines) <= self.MAXLINES:
  172. return "\n".join(self.__lines)
  173. else:
  174. return "Type %s() to see the full %s text" % ((self.__name,)*2)
  175. def __call__(self):
  176. self.__setup()
  177. prompt = 'Hit Return for more, or q (and Return) to quit: '
  178. lineno = 0
  179. while 1:
  180. try:
  181. for i in range(lineno, lineno + self.MAXLINES):
  182. print self.__lines[i]
  183. except IndexError:
  184. break
  185. else:
  186. lineno += self.MAXLINES
  187. key = None
  188. while key is None:
  189. key = raw_input(prompt)
  190. if key not in ('', 'q'):
  191. key = None
  192. if key == 'q':
  193. break
  194. __builtin__.copyright = _Printer("copyright", sys.copyright)
  195. if sys.platform[:4] == 'java':
  196. __builtin__.credits = _Printer(
  197. "credits",
  198. "Jython is maintained by the Jython developers (www.jython.org).")
  199. else:
  200. __builtin__.credits = _Printer("credits", """\
  201. Thanks to CWI, CNRI, BeOpen.com, Digital Creations and a cast of thousands
  202. for supporting Python development. See www.python.org for more information.""")
  203. here = os.path.dirname(os.__file__)
  204. __builtin__.license = _Printer(
  205. "license", "See http://www.pythonlabs.com/products/python2.0/license.html",
  206. ["LICENSE.txt", "LICENSE"],
  207. [os.path.join(here, os.pardir), here, os.curdir])
  208. # Set the string encoding used by the Unicode implementation. The
  209. # default is 'ascii', but if you're willing to experiment, you can
  210. # change this.
  211. encoding = "ascii" # Default value set by _PyUnicode_Init()
  212. if 0:
  213. # Enable to support locale aware default string encodings.
  214. import locale
  215. loc = locale.getdefaultlocale()
  216. if loc[1]:
  217. encoding = loc[1]
  218. if 0:
  219. # Enable to switch off string to Unicode coercion and implicit
  220. # Unicode to string conversion.
  221. encoding = "undefined"
  222. if encoding != "ascii":
  223. sys.setdefaultencoding(encoding)
  224. #
  225. # Run custom site specific code, if available.
  226. #
  227. try:
  228. import sitecustomize
  229. except ImportError:
  230. pass
  231. #
  232. # Remove sys.setdefaultencoding() so that users cannot change the
  233. # encoding after initialization. The test for presence is needed when
  234. # this module is run as a script, because this code is executed twice.
  235. #
  236. if hasattr(sys, "setdefaultencoding"):
  237. del sys.setdefaultencoding
  238. def _test():
  239. print "sys.path = ["
  240. for dir in sys.path:
  241. print " %s," % `dir`
  242. print "]"
  243. if __name__ == '__main__':
  244. _test()