PageRenderTime 61ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/extensions/jython/module/MOD-INF/lib/jython/site.py

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