From: <fwi...@us...> - 2009-01-05 19:07:03
|
Revision: 5853 http://jython.svn.sourceforge.net/jython/?rev=5853&view=rev Author: fwierzbicki Date: 2009-01-05 19:06:58 +0000 (Mon, 05 Jan 2009) Log Message: ----------- Merged with py3k site.py Modified Paths: -------------- branches/jy3k/Lib/site.py Modified: branches/jy3k/Lib/site.py =================================================================== --- branches/jy3k/Lib/site.py 2009-01-05 18:48:54 UTC (rev 5852) +++ branches/jy3k/Lib/site.py 2009-01-05 19:06:58 UTC (rev 5853) @@ -4,12 +4,6 @@ * This module is automatically imported during initialization. * **************************************************************** -In earlier versions of Python (up to 1.5a3), scripts or modules that -needed to use site-specific modules would place ``import site'' -somewhere near the top of their code. Because of the automatic -import, this is no longer necessary (but code that does it still -works). - This will append site-specific paths to the module search path. On Unix (including Mac OSX), it starts with sys.prefix and sys.exec_prefix (if different) and appends @@ -60,9 +54,18 @@ import sys import os -import __builtin__ +import builtins +# Prefixes for site-packages; add additional prefixes like /usr/local here +PREFIXES = [sys.prefix, sys.exec_prefix] +# Enable per user site-packages directory +# set it to False to disable the feature or True to force the feature +ENABLE_USER_SITE = None +# for distutils.commands.install +USER_SITE = None +USER_BASE = None + def makepath(*paths): dir = os.path.join(*paths) if dir == '__classpath__' or dir.startswith('__pyclasspath__'): @@ -72,7 +75,7 @@ def abs__file__(): """Set all module' __file__ attribute to an absolute path""" - for m in sys.modules.values(): + for m in set(sys.modules.values()): if hasattr(m, '__loader__'): continue # don't mess with a PEP 302-supplied __file__ f = getattr(m, '__file__', None) @@ -105,9 +108,12 @@ (especially for Guido :-)""" from distutils.util import get_platform s = "build/lib.%s-%.3s" % (get_platform(), sys.version) + if hasattr(sys, 'gettotalrefcount'): + s += '-pydebug' s = os.path.join(os.path.dirname(sys.path[-1]), s) sys.path.append(s) + def _init_pathinfo(): """Return a set containing all existing directory entries from sys.path""" d = set() @@ -120,9 +126,12 @@ continue return d + def addpackage(sitedir, name, known_paths): - """Add a new path to known_paths by combining sitedir and 'name' or execute - sitedir if it starts with 'import'""" + """Process a .pth file within the site-packages directory: + For each line in the file, either combine it with sitedir to a path + and add that to known_paths, or execute it if it starts with 'import '. + """ if known_paths is None: _init_pathinfo() reset = 1 @@ -133,24 +142,23 @@ f = open(fullname, "rU") except IOError: return - try: + with f: for line in f: if line.startswith("#"): continue - if line.startswith("import"): - exec line + if line.startswith(("import ", "import\t")): + exec(line) continue line = line.rstrip() dir, dircase = makepath(sitedir, line) if not dircase in known_paths and os.path.exists(dir): sys.path.append(dir) known_paths.add(dircase) - finally: - f.close() if reset: known_paths = None return known_paths + def addsitedir(sitedir, known_paths=None): """Add 'sitedir' argument to sys.path if missing and handle .pth files in 'sitedir'""" @@ -166,50 +174,116 @@ names = os.listdir(sitedir) except os.error: return - names.sort() - for name in names: - if name.endswith(os.extsep + "pth"): - addpackage(sitedir, name, known_paths) + names = [name for name in names if name.endswith(".pth")] + for name in sorted(names): + addpackage(sitedir, name, known_paths) if reset: known_paths = None return known_paths + +def check_enableusersite(): + """Check if user site directory is safe for inclusion + + The function tests for the command line flag (including environment var), + process uid/gid equal to effective uid/gid. + + None: Disabled for security reasons + False: Disabled by user (command line option) + True: Safe and enabled + """ + if sys.flags.no_user_site: + return False + + if hasattr(os, "getuid") and hasattr(os, "geteuid"): + # check process uid == effective uid + if os.geteuid() != os.getuid(): + return None + if hasattr(os, "getgid") and hasattr(os, "getegid"): + # check process gid == effective gid + if os.getegid() != os.getgid(): + return None + + return True + + +def addusersitepackages(known_paths): + """Add a per user site-package to sys.path + + Each user has its own python directory with site-packages in the + home directory. + + USER_BASE is the root directory for all Python versions + + USER_SITE is the user specific site-packages directory + + USER_SITE/.. can be used for data. + """ + global USER_BASE, USER_SITE, ENABLE_USER_SITE + env_base = os.environ.get("PYTHONUSERBASE", None) + + def joinuser(*args): + return os.path.expanduser(os.path.join(*args)) + + #if sys.platform in ('os2emx', 'riscos'): + # # Don't know what to put here + # USER_BASE = '' + # USER_SITE = '' + if os.name == "nt": + base = os.environ.get("APPDATA") or "~" + USER_BASE = env_base if env_base else joinuser(base, "Python") + USER_SITE = os.path.join(USER_BASE, + "Python" + sys.version[0] + sys.version[2], + "site-packages") + else: + USER_BASE = env_base if env_base else joinuser("~", ".local") + USER_SITE = os.path.join(USER_BASE, "lib", + "python" + sys.version[:3], + "site-packages") + + if ENABLE_USER_SITE and os.path.isdir(USER_SITE): + addsitedir(USER_SITE, known_paths) + return known_paths + + def addsitepackages(known_paths): """Add site-packages (and possibly site-python) to sys.path""" - prefixes = [sys.prefix] - if sys.exec_prefix != sys.prefix: - prefixes.append(sys.exec_prefix) - for prefix in prefixes: - if prefix: - if sys.platform in ('os2emx', 'riscos') or sys.platform[:4] == 'java': - sitedirs = [os.path.join(prefix, "Lib", "site-packages")] - elif os.sep == '/': - sitedirs = [os.path.join(prefix, - "lib", - "python" + sys.version[:3], - "site-packages"), - os.path.join(prefix, "lib", "site-python")] - else: - sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")] - if sys.platform == 'darwin': - # for framework builds *only* we add the standard Apple - # locations. Currently only per-user, but /Library and - # /Network/Library could be added too - if 'Python.framework' in prefix: - home = os.environ.get('HOME') - if home: - sitedirs.append( - os.path.join(home, - 'Library', - 'Python', - sys.version[:3], - 'site-packages')) - for sitedir in sitedirs: - if os.path.isdir(sitedir): - addsitedir(sitedir, known_paths) - return None + sitedirs = [] + seen = [] + for prefix in PREFIXES: + if not prefix or prefix in seen: + continue + seen.append(prefix) + if sys.platform in ('os2emx', 'riscos') or sys.platform[:4] == 'java': + sitedirs.append(os.path.join(prefix, "Lib", "site-packages")) + elif os.sep == '/': + sitedirs.append(os.path.join(prefix, "lib", + "python" + sys.version[:3], + "site-packages")) + sitedirs.append(os.path.join(prefix, "lib", "site-python")) + else: + sitedirs.append(prefix) + sitedirs.append(os.path.join(prefix, "lib", "site-packages")) + + if sys.platform == "darwin": + # for framework builds *only* we add the standard Apple + # locations. Currently only per-user, but /Library and + # /Network/Library could be added too + if 'Python.framework' in prefix: + sitedirs.append( + os.path.expanduser( + os.path.join("~", "Library", "Python", + sys.version[:3], "site-packages"))) + + for sitedir in sitedirs: + if os.path.isdir(sitedir): + addsitedir(sitedir, known_paths) + + return known_paths + + def setBEGINLIBPATH(): """The OS/2 EMX port has optional extension modules that do double duty as DLLs (and must use the .DLL file extension) for other extensions. @@ -248,12 +322,17 @@ # Shells like IDLE catch the SystemExit, but listen when their # stdin wrapper is closed. try: - sys.stdin.close() + fd = -1 + if hasattr(sys.stdin, "fileno"): + fd = sys.stdin.fileno() + if fd != 0: + # Don't close stdin if it wraps fd 0 + sys.stdin.close() except: pass raise SystemExit(code) - __builtin__.quit = Quitter('quit') - __builtin__.exit = Quitter('exit') + builtins.quit = Quitter('quit') + builtins.exit = Quitter('exit') class _Printer(object): @@ -277,7 +356,7 @@ for filename in self.__files: filename = os.path.join(dir, filename) try: - fp = file(filename, "rU") + fp = open(filename, "rU") data = fp.read() fp.close() break @@ -304,32 +383,32 @@ while 1: try: for i in range(lineno, lineno + self.MAXLINES): - print self.__lines[i] + print(self.__lines[i]) except IndexError: break else: lineno += self.MAXLINES key = None while key is None: - key = raw_input(prompt) + key = input(prompt) if key not in ('', 'q'): key = None if key == 'q': break def setcopyright(): - """Set 'copyright' and 'credits' in __builtin__""" - __builtin__.copyright = _Printer("copyright", sys.copyright) + """Set 'copyright' and 'credits' in builtins""" + builtins.copyright = _Printer("copyright", sys.copyright) if sys.platform[:4] == 'java': - __builtin__.credits = _Printer( + builtins.credits = _Printer( "credits", "Jython is maintained by the Jython developers (www.jython.org).") else: - __builtin__.credits = _Printer("credits", """\ + builtins.credits = _Printer("credits", """\ Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands for supporting Python development. See www.python.org for more information.""") here = os.path.dirname(os.__file__) - __builtin__.license = _Printer( + builtins.license = _Printer( "license", "See http://www.python.org/%.3s/license.html" % sys.version, ["LICENSE.txt", "LICENSE"], [os.path.join(here, os.pardir), here, os.curdir]) @@ -349,7 +428,7 @@ return pydoc.help(*args, **kwds) def sethelper(): - __builtin__.help = _Helper() + builtins.help = _Helper() def aliasmbcs(): """On Windows, some default encodings are not provided by Python, @@ -392,15 +471,35 @@ import sitecustomize except ImportError: pass + except Exception as err: + if os.environ.get("PYTHONVERBOSE"): + raise + sys.stderr.write( + "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n" + "%s: %s\n" % + (err.__class__.__name__, err)) +def execusercustomize(): + """Run custom user specific code, if available.""" + try: + import usercustomize + except ImportError: + pass + + def main(): + global ENABLE_USER_SITE + abs__file__() - paths_in_sys = removeduppaths() + known_paths = removeduppaths() if (os.name == "posix" and sys.path and os.path.basename(sys.path[-1]) == "Modules"): addbuilddir() - paths_in_sys = addsitepackages(paths_in_sys) + if ENABLE_USER_SITE is None: + ENABLE_USER_SITE = check_enableusersite() + known_paths = addusersitepackages(known_paths) + known_paths = addsitepackages(known_paths) if sys.platform == 'os2emx': setBEGINLIBPATH() setquit() @@ -409,6 +508,8 @@ aliasmbcs() setencoding() execsitecustomize() + if ENABLE_USER_SITE: + execusercustomize() # Remove sys.setdefaultencoding() so that users cannot change the # encoding after initialization. The test for presence is needed when # this module is run as a script, because this code is executed twice. @@ -417,11 +518,54 @@ main() -def _test(): - print "sys.path = [" - for dir in sys.path: - print " %r," % (dir,) - print "]" +def _script(): + help = """\ + %s [--user-base] [--user-site] + Without arguments print some useful information + With arguments print the value of USER_BASE and/or USER_SITE separated + by '%s'. + + Exit codes with --user-base or --user-site: + 0 - user site directory is enabled + 1 - user site directory is disabled by user + 2 - uses site directory is disabled by super user + or for security reasons + >2 - unknown error + """ + args = sys.argv[1:] + if not args: + print("sys.path = [") + for dir in sys.path: + print(" %r," % (dir,)) + print("]") + print("USER_BASE: %r (%s)" % (USER_BASE, + "exists" if os.path.isdir(USER_BASE) else "doesn't exist")) + print("USER_SITE: %r (%s)" % (USER_SITE, + "exists" if os.path.isdir(USER_SITE) else "doesn't exist")) + print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE) + sys.exit(0) + + buffer = [] + if '--user-base' in args: + buffer.append(USER_BASE) + if '--user-site' in args: + buffer.append(USER_SITE) + + if buffer: + print(os.pathsep.join(buffer)) + if ENABLE_USER_SITE: + sys.exit(0) + elif ENABLE_USER_SITE is False: + sys.exit(1) + elif ENABLE_USER_SITE is None: + sys.exit(2) + else: + sys.exit(3) + else: + import textwrap + print(textwrap.dedent(help % (sys.argv[0], os.pathsep))) + sys.exit(10) + if __name__ == '__main__': - _test() + _script() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |