PageRenderTime 64ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/bilab_working/BiLab/libs/jython2.5.2/Lib/site.py

https://github.com/argodev/BiLab
Python | 430 lines | 399 code | 18 blank | 13 comment | 37 complexity | 3681317973a9be6ed07a64cddf94a346 MD5 | raw file
  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. ModuleType = type(os)
  51. def makepath(*paths):
  52. dir = os.path.join(*paths)
  53. if dir == '__classpath__' or dir.startswith('__pyclasspath__'):
  54. return dir, dir
  55. dir = os.path.abspath(dir)
  56. return dir, os.path.normcase(dir)
  57. def abs__file__():
  58. """Set all module' __file__ attribute to an absolute path"""
  59. for m in sys.modules.values():
  60. if not isinstance(m, ModuleType) or hasattr(m, '__loader__'):
  61. # only modules need the abspath in Jython. and don't mess
  62. # with a PEP 302-supplied __file__
  63. continue
  64. f = getattr(m, '__file__', None)
  65. if f is None:
  66. continue
  67. m.__file__ = os.path.abspath(f)
  68. def removeduppaths():
  69. """ Remove duplicate entries from sys.path along with making them
  70. absolute"""
  71. # This ensures that the initial path provided by the interpreter contains
  72. # only absolute pathnames, even if we're running from the build directory.
  73. L = []
  74. known_paths = set()
  75. for dir in sys.path:
  76. # Filter out duplicate paths (on case-insensitive file systems also
  77. # if they only differ in case); turn relative paths into absolute
  78. # paths.
  79. dir, dircase = makepath(dir)
  80. if not dircase in known_paths:
  81. L.append(dir)
  82. known_paths.add(dircase)
  83. sys.path[:] = L
  84. return known_paths
  85. # XXX This should not be part of site.py, since it is needed even when
  86. # using the -S option for Python. See http://www.python.org/sf/586680
  87. def addbuilddir():
  88. """Append ./build/lib.<platform> in case we're running in the build dir
  89. (especially for Guido :-)"""
  90. from distutils.util import get_platform
  91. s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
  92. s = os.path.join(os.path.dirname(sys.path[-1]), s)
  93. sys.path.append(s)
  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. """Add a new path to known_paths by combining sitedir and 'name' or execute
  107. sitedir if it starts with 'import'"""
  108. if known_paths is None:
  109. _init_pathinfo()
  110. reset = 1
  111. else:
  112. reset = 0
  113. fullname = os.path.join(sitedir, name)
  114. try:
  115. f = open(fullname, "rU")
  116. except IOError:
  117. return
  118. try:
  119. for line in f:
  120. if line.startswith("#"):
  121. continue
  122. if line.startswith("import"):
  123. exec line
  124. continue
  125. line = line.rstrip()
  126. dir, dircase = makepath(sitedir, line)
  127. if not dircase in known_paths and os.path.exists(dir):
  128. sys.path.append(dir)
  129. known_paths.add(dircase)
  130. finally:
  131. f.close()
  132. if reset:
  133. known_paths = None
  134. return known_paths
  135. def addsitedir(sitedir, known_paths=None):
  136. """Add 'sitedir' argument to sys.path if missing and handle .pth files in
  137. 'sitedir'"""
  138. if known_paths is None:
  139. known_paths = _init_pathinfo()
  140. reset = 1
  141. else:
  142. reset = 0
  143. sitedir, sitedircase = makepath(sitedir)
  144. if not sitedircase in known_paths:
  145. sys.path.append(sitedir) # Add path component
  146. try:
  147. names = os.listdir(sitedir)
  148. except os.error:
  149. return
  150. names.sort()
  151. for name in names:
  152. if name.endswith(os.extsep + "pth"):
  153. addpackage(sitedir, name, known_paths)
  154. if reset:
  155. known_paths = None
  156. return known_paths
  157. def addsitepackages(known_paths):
  158. """Add site-packages (and possibly site-python) to sys.path"""
  159. prefixes = [sys.prefix]
  160. if sys.exec_prefix != sys.prefix:
  161. prefixes.append(sys.exec_prefix)
  162. for prefix in prefixes:
  163. if prefix:
  164. if sys.platform in ('os2emx', 'riscos') or sys.platform[:4] == 'java':
  165. sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
  166. elif os.sep == '/':
  167. sitedirs = [os.path.join(prefix,
  168. "lib",
  169. "python" + sys.version[:3],
  170. "site-packages"),
  171. os.path.join(prefix, "lib", "site-python")]
  172. else:
  173. sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
  174. if sys.platform == 'darwin':
  175. # for framework builds *only* we add the standard Apple
  176. # locations. Currently only per-user, but /Library and
  177. # /Network/Library could be added too
  178. if 'Python.framework' in prefix:
  179. home = os.environ.get('HOME')
  180. if home:
  181. sitedirs.append(
  182. os.path.join(home,
  183. 'Library',
  184. 'Python',
  185. sys.version[:3],
  186. 'site-packages'))
  187. for sitedir in sitedirs:
  188. if os.path.isdir(sitedir):
  189. addsitedir(sitedir, known_paths)
  190. return None
  191. def setBEGINLIBPATH():
  192. """The OS/2 EMX port has optional extension modules that do double duty
  193. as DLLs (and must use the .DLL file extension) for other extensions.
  194. The library search path needs to be amended so these will be found
  195. during module import. Use BEGINLIBPATH so that these are at the start
  196. of the library search path.
  197. """
  198. dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
  199. libpath = os.environ['BEGINLIBPATH'].split(';')
  200. if libpath[-1]:
  201. libpath.append(dllpath)
  202. else:
  203. libpath[-1] = dllpath
  204. os.environ['BEGINLIBPATH'] = ';'.join(libpath)
  205. def setquit():
  206. """Define new built-ins 'quit' and 'exit'.
  207. These are simply strings that display a hint on how to exit.
  208. """
  209. if os.sep == ':':
  210. eof = 'Cmd-Q'
  211. elif os.sep == '\\':
  212. eof = 'Ctrl-Z plus Return'
  213. else:
  214. eof = 'Ctrl-D (i.e. EOF)'
  215. class Quitter(object):
  216. def __init__(self, name):
  217. self.name = name
  218. def __repr__(self):
  219. return 'Use %s() or %s to exit' % (self.name, eof)
  220. def __call__(self, code=None):
  221. # Shells like IDLE catch the SystemExit, but listen when their
  222. # stdin wrapper is closed.
  223. try:
  224. sys.stdin.close()
  225. except:
  226. pass
  227. raise SystemExit(code)
  228. __builtin__.quit = Quitter('quit')
  229. __builtin__.exit = Quitter('exit')
  230. class _Printer(object):
  231. """interactive prompt objects for printing the license text, a list of
  232. contributors and the copyright notice."""
  233. MAXLINES = 23
  234. def __init__(self, name, data, files=(), dirs=()):
  235. self.__name = name
  236. self.__data = data
  237. self.__files = files
  238. self.__dirs = dirs
  239. self.__lines = None
  240. def __setup(self):
  241. if self.__lines:
  242. return
  243. data = None
  244. for dir in self.__dirs:
  245. for filename in self.__files:
  246. filename = os.path.join(dir, filename)
  247. try:
  248. fp = file(filename, "rU")
  249. data = fp.read()
  250. fp.close()
  251. break
  252. except IOError:
  253. pass
  254. if data:
  255. break
  256. if not data:
  257. data = self.__data
  258. self.__lines = data.split('\n')
  259. self.__linecnt = len(self.__lines)
  260. def __repr__(self):
  261. self.__setup()
  262. if len(self.__lines) <= self.MAXLINES:
  263. return "\n".join(self.__lines)
  264. else:
  265. return "Type %s() to see the full %s text" % ((self.__name,)*2)
  266. def __call__(self):
  267. self.__setup()
  268. prompt = 'Hit Return for more, or q (and Return) to quit: '
  269. lineno = 0
  270. while 1:
  271. try:
  272. for i in range(lineno, lineno + self.MAXLINES):
  273. print self.__lines[i]
  274. except IndexError:
  275. break
  276. else:
  277. lineno += self.MAXLINES
  278. key = None
  279. while key is None:
  280. key = raw_input(prompt)
  281. if key not in ('', 'q'):
  282. key = None
  283. if key == 'q':
  284. break
  285. def setcopyright():
  286. """Set 'copyright' and 'credits' in __builtin__"""
  287. __builtin__.copyright = _Printer("copyright", sys.copyright)
  288. if sys.platform[:4] == 'java':
  289. __builtin__.credits = _Printer(
  290. "credits",
  291. "Jython is maintained by the Jython developers (www.jython.org).")
  292. else:
  293. __builtin__.credits = _Printer("credits", """\
  294. Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  295. for supporting Python development. See www.python.org for more information.""")
  296. here = os.path.dirname(os.__file__)
  297. __builtin__.license = _Printer(
  298. "license", "See http://www.python.org/%.3s/license.html" % sys.version,
  299. ["LICENSE.txt", "LICENSE"],
  300. [os.path.join(here, os.pardir), here, os.curdir])
  301. class _Helper(object):
  302. """Define the built-in 'help'.
  303. This is a wrapper around pydoc.help (with a twist).
  304. """
  305. def __repr__(self):
  306. return "Type help() for interactive help, " \
  307. "or help(object) for help about object."
  308. def __call__(self, *args, **kwds):
  309. import pydoc
  310. return pydoc.help(*args, **kwds)
  311. def sethelper():
  312. __builtin__.help = _Helper()
  313. def aliasmbcs():
  314. """On Windows, some default encodings are not provided by Python,
  315. while they are always available as "mbcs" in each locale. Make
  316. them usable by aliasing to "mbcs" in such a case."""
  317. if sys.platform == 'win32':
  318. import locale, codecs
  319. enc = locale.getdefaultlocale()[1]
  320. if enc.startswith('cp'): # "cp***" ?
  321. try:
  322. codecs.lookup(enc)
  323. except LookupError:
  324. import encodings
  325. encodings._cache[enc] = encodings._unknown
  326. encodings.aliases.aliases[enc] = 'mbcs'
  327. def setencoding():
  328. """Set the string encoding used by the Unicode implementation. The
  329. default is 'ascii', but if you're willing to experiment, you can
  330. change this."""
  331. encoding = "ascii" # Default value set by _PyUnicode_Init()
  332. if 0:
  333. # Enable to support locale aware default string encodings.
  334. import locale
  335. loc = locale.getdefaultlocale()
  336. if loc[1]:
  337. encoding = loc[1]
  338. if 0:
  339. # Enable to switch off string to Unicode coercion and implicit
  340. # Unicode to string conversion.
  341. encoding = "undefined"
  342. if encoding != "ascii":
  343. # On Non-Unicode builds this will raise an AttributeError...
  344. sys.setdefaultencoding(encoding) # Needs Python Unicode build !
  345. def execsitecustomize():
  346. """Run custom site specific code, if available."""
  347. try:
  348. import sitecustomize
  349. except ImportError:
  350. pass
  351. def main():
  352. abs__file__()
  353. paths_in_sys = removeduppaths()
  354. if (os.name == "posix" and sys.path and
  355. os.path.basename(sys.path[-1]) == "Modules"):
  356. addbuilddir()
  357. paths_in_sys = addsitepackages(paths_in_sys)
  358. if sys.platform == 'os2emx':
  359. setBEGINLIBPATH()
  360. setquit()
  361. setcopyright()
  362. sethelper()
  363. aliasmbcs()
  364. setencoding()
  365. execsitecustomize()
  366. # Remove sys.setdefaultencoding() so that users cannot change the
  367. # encoding after initialization. The test for presence is needed when
  368. # this module is run as a script, because this code is executed twice.
  369. if hasattr(sys, "setdefaultencoding"):
  370. del sys.setdefaultencoding
  371. main()
  372. def _test():
  373. print "sys.path = ["
  374. for dir in sys.path:
  375. print " %r," % (dir,)
  376. print "]"
  377. if __name__ == '__main__':
  378. _test()