buildframework/helium/external/python/lib/2.5/linux/site.py
changeset 179 d8ac696cc51f
parent 1 be27ed110b50
child 180 e02a83d4c571
child 592 3215c239276a
equal deleted inserted replaced
1:be27ed110b50 179:d8ac696cc51f
     1 # Duplicating setuptools' site.py...
       
     2 def __boot():
       
     3     PYTHONPATH = []    
       
     4     if sys.platform=='win32':
       
     5         PYTHONPATH.append(os.path.join(sys.prefix, 'lib'))
       
     6     if not (os.environ.get('PYTHONPATH') is None or (sys.platform=='win32' and not os.environ.get('PYTHONPATH'))):
       
     7         PYTHONPATH.extend(os.environ.get('PYTHONPATH').split(os.pathsep))
       
     8     pic = getattr(sys,'path_importer_cache',{})
       
     9     stdpath = sys.path[len(PYTHONPATH):]
       
    10     mydir = os.path.dirname(__file__)
       
    11     known_paths = dict([(makepath(item)[1],1) for item in sys.path]) # 2.2 comp
       
    12 
       
    13     oldpos = getattr(sys,'__egginsert',0)   # save old insertion position
       
    14     sys.__egginsert = 0                     # and reset the current one
       
    15 
       
    16     for item in PYTHONPATH:
       
    17         addsitedir(item)
       
    18         item_site_packages = os.path.join(item, 'site-packages')
       
    19         if os.path.exists(item_site_packages):
       
    20             addsitedir(item_site_packages)
       
    21 
       
    22     sys.__egginsert += oldpos           # restore effective old position
       
    23 
       
    24     d,nd = makepath(stdpath[0])
       
    25     insert_at = None
       
    26     new_path = []
       
    27 
       
    28     for item in sys.path:
       
    29         p,np = makepath(item)
       
    30 
       
    31         if np==nd and insert_at is None:
       
    32             # We've hit the first 'system' path entry, so added entries go here
       
    33             insert_at = len(new_path)
       
    34 
       
    35         if np in known_paths or insert_at is None:
       
    36             new_path.append(item)
       
    37         else:
       
    38             # new path after the insert point, back-insert it
       
    39             new_path.insert(insert_at, item)
       
    40             insert_at += 1
       
    41 
       
    42     sys.path[:] = new_path
       
    43     
       
    44 import sys
       
    45 import os
       
    46 import __builtin__
       
    47 
       
    48 def makepath(*paths):
       
    49     dir = os.path.abspath(os.path.join(*paths))
       
    50     return dir, os.path.normcase(dir)
       
    51 
       
    52 def abs__file__():
       
    53     """Set all module' __file__ attribute to an absolute path"""
       
    54     for m in sys.modules.values():
       
    55         try:
       
    56             m.__file__ = os.path.abspath(m.__file__)
       
    57         except AttributeError:
       
    58             continue
       
    59 
       
    60 try:
       
    61     set
       
    62 except NameError:
       
    63     class set:
       
    64         def __init__(self, args=()):
       
    65             self.d = {}
       
    66             for v in args:
       
    67                 self.d[v] = None
       
    68         def __contains__(self, key):
       
    69             return key in self.d
       
    70         def add(self, key):
       
    71             self.d[key] = None
       
    72 
       
    73 def removeduppaths():
       
    74     """ Remove duplicate entries from sys.path along with making them
       
    75     absolute"""
       
    76     # This ensures that the initial path provided by the interpreter contains
       
    77     # only absolute pathnames, even if we're running from the build directory.
       
    78     L = []
       
    79     known_paths = set()
       
    80     for dir in sys.path:
       
    81         # Filter out duplicate paths (on case-insensitive file systems also
       
    82         # if they only differ in case); turn relative paths into absolute
       
    83         # paths.
       
    84         dir, dircase = makepath(dir)
       
    85         if not dircase in known_paths:
       
    86             L.append(dir)
       
    87             known_paths.add(dircase)
       
    88     sys.path[:] = L
       
    89     return known_paths
       
    90 
       
    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 
       
   103 def addpackage(sitedir, name, known_paths, exclude_packages=()):
       
   104     """Add a new path to known_paths by combining sitedir and 'name' or execute
       
   105     sitedir if it starts with 'import'"""
       
   106     import fnmatch
       
   107     if known_paths is None:
       
   108         _init_pathinfo()
       
   109         reset = 1
       
   110     else:
       
   111         reset = 0
       
   112     fullname = os.path.join(sitedir, name)
       
   113     try:
       
   114         f = open(fullname, "rU")
       
   115     except IOError:
       
   116         return
       
   117     try:
       
   118         for line in f:
       
   119             if line.startswith("#"):
       
   120                 continue
       
   121             found_exclude = False
       
   122             for exclude in exclude_packages:
       
   123                 if exclude(line):
       
   124                     found_exclude = True
       
   125                     break
       
   126             if found_exclude:
       
   127                 continue
       
   128             if line.startswith("import"):
       
   129                 exec line
       
   130                 continue
       
   131             line = line.rstrip()
       
   132             dir, dircase = makepath(sitedir, line)
       
   133             if not dircase in known_paths and os.path.exists(dir):
       
   134                 sys.path.append(dir)
       
   135                 known_paths.add(dircase)
       
   136     finally:
       
   137         f.close()
       
   138     if reset:
       
   139         known_paths = None
       
   140     return known_paths
       
   141 
       
   142 def addsitedir(sitedir, known_paths=None, exclude_packages=()):
       
   143     """Add 'sitedir' argument to sys.path if missing and handle .pth files in
       
   144     'sitedir'"""
       
   145     if known_paths is None:
       
   146         known_paths = _init_pathinfo()
       
   147         reset = 1
       
   148     else:
       
   149         reset = 0
       
   150     sitedir, sitedircase = makepath(sitedir)
       
   151     if not sitedircase in known_paths:
       
   152         sys.path.append(sitedir)        # Add path component
       
   153     try:
       
   154         names = os.listdir(sitedir)
       
   155     except os.error:
       
   156         return
       
   157     names.sort()
       
   158     for name in names:
       
   159         if name.endswith(os.extsep + "pth"):
       
   160             addpackage(sitedir, name, known_paths,
       
   161                        exclude_packages=exclude_packages)
       
   162     if reset:
       
   163         known_paths = None
       
   164     return known_paths
       
   165 
       
   166 def addsitepackages(known_paths):
       
   167     """Add site-packages (and possibly site-python) to sys.path"""
       
   168     prefixes = [os.path.join(sys.prefix, "local"), sys.prefix]
       
   169     if sys.exec_prefix != sys.prefix:
       
   170         prefixes.append(os.path.join(sys.exec_prefix, "local"))
       
   171     for prefix in prefixes:
       
   172         if prefix:
       
   173             if sys.platform in ('os2emx', 'riscos'):
       
   174                 sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
       
   175             elif os.sep == '/':
       
   176                 sitedirs = [os.path.join(prefix,
       
   177                                          "lib",
       
   178                                          "python" + sys.version[:3],
       
   179                                          "site-packages"),
       
   180                             os.path.join(prefix, "lib", "site-python")]
       
   181                 try:
       
   182                     # sys.getobjects only available in --with-pydebug build
       
   183                     # pylint: disable-msg=E1101
       
   184                     sys.getobjects
       
   185                     sitedirs.insert(0, os.path.join(sitedirs[0], 'debug'))
       
   186                 except AttributeError:
       
   187                     pass
       
   188             else:
       
   189                 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
       
   190             if sys.platform == 'darwin':
       
   191                 sitedirs.append( os.path.join('/opt/local', 'lib', 'python' + sys.version[:3], 'site-packages') )
       
   192                 # for framework builds *only* we add the standard Apple
       
   193                 # locations. Currently only per-user, but /Library and
       
   194                 # /Network/Library could be added too
       
   195                 if 'Python.framework' in prefix:
       
   196                     home = os.environ.get('HOME')
       
   197                     if home:
       
   198                         sitedirs.append(
       
   199                             os.path.join(home,
       
   200                                          'Library',
       
   201                                          'Python',
       
   202                                          sys.version[:3],
       
   203                                          'site-packages'))
       
   204             for sitedir in sitedirs:
       
   205                 if os.path.isdir(sitedir):
       
   206                     addsitedir(sitedir, known_paths,
       
   207                                exclude_packages=[lambda line: 'setuptools' in line])
       
   208     return None
       
   209 
       
   210 def setquit():
       
   211     """Define new built-ins 'quit' and 'exit'.
       
   212     These are simply strings that display a hint on how to exit.
       
   213 
       
   214     """
       
   215     if os.sep == ':':
       
   216         exit = 'Use Cmd-Q to quit.'
       
   217     elif os.sep == '\\':
       
   218         exit = 'Use Ctrl-Z plus Return to exit.'
       
   219     else:
       
   220         exit = 'Use Ctrl-D (i.e. EOF) to exit.'
       
   221     __builtin__.quit = __builtin__.exit = exit
       
   222 
       
   223 
       
   224 class _Printer(object):
       
   225     """interactive prompt objects for printing the license text, a list of
       
   226     contributors and the copyright notice."""
       
   227 
       
   228     MAXLINES = 23
       
   229 
       
   230     def __init__(self, name, data, files=(), dirs=()):
       
   231         self.__name = name
       
   232         self.__data = data
       
   233         self.__files = files
       
   234         self.__dirs = dirs
       
   235         self.__lines = None
       
   236 
       
   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 
       
   258     def __repr__(self):
       
   259         self.__setup()
       
   260         if len(self.__lines) <= self.MAXLINES:
       
   261             return "\n".join(self.__lines)
       
   262         else:
       
   263             return "Type %s() to see the full %s text" % ((self.__name,)*2)
       
   264 
       
   265     def __call__(self):
       
   266         self.__setup()
       
   267         prompt = 'Hit Return for more, or q (and Return) to quit: '
       
   268         lineno = 0
       
   269         while 1:
       
   270             try:
       
   271                 for i in range(lineno, lineno + self.MAXLINES):
       
   272                     print self.__lines[i]
       
   273             except IndexError:
       
   274                 break
       
   275             else:
       
   276                 lineno += self.MAXLINES
       
   277                 key = None
       
   278                 while key is None:
       
   279                     key = raw_input(prompt)
       
   280                     if key not in ('', 'q'):
       
   281                         key = None
       
   282                 if key == 'q':
       
   283                     break
       
   284 
       
   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 
       
   302 
       
   303 class _Helper(object):
       
   304     """Define the built-in 'help'.
       
   305     This is a wrapper around pydoc.help (with a twist).
       
   306 
       
   307     """
       
   308 
       
   309     def __repr__(self):
       
   310         return "Type help() for interactive help, " \
       
   311                "or help(object) for help about object."
       
   312     def __call__(self, *args, **kwds):
       
   313         import pydoc
       
   314         return pydoc.help(*args, **kwds)
       
   315 
       
   316 def sethelper():
       
   317     __builtin__.help = _Helper()
       
   318 
       
   319 def aliasmbcs():
       
   320     """On Windows, some default encodings are not provided by Python,
       
   321     while they are always available as "mbcs" in each locale. Make
       
   322     them usable by aliasing to "mbcs" in such a case."""
       
   323     if sys.platform == 'win32':
       
   324         import locale, codecs
       
   325         enc = locale.getdefaultlocale()[1]
       
   326         if enc.startswith('cp'):            # "cp***" ?
       
   327             try:
       
   328                 codecs.lookup(enc)
       
   329             except LookupError:
       
   330                 import encodings
       
   331                 encodings._cache[enc] = encodings._unknown
       
   332                 encodings.aliases.aliases[enc] = 'mbcs'
       
   333 
       
   334 def setencoding():
       
   335     """Set the string encoding used by the Unicode implementation.  The
       
   336     default is 'ascii', but if you're willing to experiment, you can
       
   337     change this."""
       
   338     encoding = "ascii" # Default value set by _PyUnicode_Init()
       
   339     if 0:
       
   340         # Enable to support locale aware default string encodings.
       
   341         import locale
       
   342         loc = locale.getdefaultlocale()
       
   343         if loc[1]:
       
   344             encoding = loc[1]
       
   345     if 0:
       
   346         # Enable to switch off string to Unicode coercion and implicit
       
   347         # Unicode to string conversion.
       
   348         encoding = "undefined"
       
   349     if encoding != "ascii":
       
   350         # On Non-Unicode builds this will raise an AttributeError...
       
   351         sys.setdefaultencoding(encoding) # Needs Python Unicode build !
       
   352 
       
   353 
       
   354 def execsitecustomize():
       
   355     """Run custom site specific code, if available."""
       
   356     try:
       
   357         import sitecustomize
       
   358     except ImportError:
       
   359         pass
       
   360 
       
   361 def fixup_setuptools():
       
   362     """Make sure our setuptools monkeypatch is in place"""
       
   363     for i in range(len(sys.path)):
       
   364         if sys.path[i].find('setuptools') != -1:
       
   365             path = sys.path[i]
       
   366             del sys.path[i]
       
   367             sys.path.append(path)
       
   368 
       
   369 def main():
       
   370     abs__file__()
       
   371     paths_in_sys = removeduppaths()
       
   372     if include_site_packages:
       
   373         paths_in_sys = addsitepackages(paths_in_sys)
       
   374     setquit()
       
   375     setcopyright()
       
   376     sethelper()
       
   377     aliasmbcs()
       
   378     setencoding()
       
   379     execsitecustomize()
       
   380     # Remove sys.setdefaultencoding() so that users cannot change the
       
   381     # encoding after initialization.  The test for presence is needed when
       
   382     # this module is run as a script, because this code is executed twice.
       
   383     if hasattr(sys, "setdefaultencoding"):
       
   384         del sys.setdefaultencoding
       
   385     __boot()
       
   386     fixup_setuptools()
       
   387     
       
   388 
       
   389 
       
   390 include_site_packages = False
       
   391 
       
   392 
       
   393 
       
   394 main()