diff options
Diffstat (limited to 'Lib/site.py')
| -rw-r--r-- | Lib/site.py | 142 |
1 files changed, 54 insertions, 88 deletions
diff --git a/Lib/site.py b/Lib/site.py index 54e5154..a2c0bec 100644 --- a/Lib/site.py +++ b/Lib/site.py @@ -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,7 +54,7 @@ ImportError exception, it is silently ignored. import sys import os -import __builtin__ +import builtins import traceback # Prefixes for site-packages; add additional prefixes like /usr/local here @@ -85,15 +79,19 @@ def makepath(*paths): return dir, os.path.normcase(dir) -def abs__file__(): - """Set all module' __file__ attribute to an absolute path""" - for m in sys.modules.values(): +def abs_paths(): + """Set all module __file__ and __cached__ attributes to an absolute path""" + for m in set(sys.modules.values()): if hasattr(m, '__loader__'): continue # don't mess with a PEP 302-supplied __file__ try: m.__file__ = os.path.abspath(m.__file__) except (AttributeError, OSError): pass + try: + m.__cached__ = os.path.abspath(m.__cached__) + except (AttributeError, OSError): + pass def removeduppaths(): @@ -114,18 +112,6 @@ def removeduppaths(): sys.path[:] = L return known_paths -# XXX This should not be part of site.py, since it is needed even when -# using the -S option for Python. See http://www.python.org/sf/586680 -def addbuilddir(): - """Append ./build/lib.<platform> in case we're running in the build dir - (especially for Guido :-)""" - from sysconfig 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.pop()), s) - sys.path.append(s) - def _init_pathinfo(): """Return a set containing all existing directory entries from sys.path""" @@ -161,7 +147,7 @@ def addpackage(sitedir, name, known_paths): continue try: if line.startswith(("import ", "import\t")): - exec line + exec(line) continue line = line.rstrip() dir, dircase = makepath(sitedir, line) @@ -169,12 +155,12 @@ def addpackage(sitedir, name, known_paths): sys.path.append(dir) known_paths.add(dircase) except Exception as err: - print >>sys.stderr, "Error processing line {:d} of {}:\n".format( - n+1, fullname) + print("Error processing line {:d} of {}:\n".format(n+1, fullname), + file=sys.stderr) for record in traceback.format_exception(*sys.exc_info()): for line in record.splitlines(): - print >>sys.stderr, ' '+line - print >>sys.stderr, "\nRemainder of file ignored" + print(' '+line, file=sys.stderr) + print("\nRemainder of file ignored", file=sys.stderr) break if reset: known_paths = None @@ -196,8 +182,7 @@ def addsitedir(sitedir, known_paths=None): names = os.listdir(sitedir) except os.error: return - dotpth = os.extsep + "pth" - names = [name for name in names if name.endswith(dotpth)] + names = [name for name in names if name.endswith(".pth")] for name in sorted(names): addpackage(sitedir, name, known_paths) if reset: @@ -366,12 +351,17 @@ def setquit(): # 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): @@ -395,7 +385,7 @@ class _Printer(object): 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 @@ -422,32 +412,32 @@ class _Printer(object): 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]) @@ -467,7 +457,7 @@ class _Helper(object): 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, @@ -484,25 +474,6 @@ def aliasmbcs(): encodings._cache[enc] = encodings._unknown encodings.aliases.aliases[enc] = 'mbcs' -def setencoding(): - """Set the string encoding used by the Unicode implementation. The - default is 'ascii', but if you're willing to experiment, you can - change this.""" - encoding = "ascii" # Default value set by _PyUnicode_Init() - if 0: - # Enable to support locale aware default string encodings. - import locale - loc = locale.getdefaultlocale() - if loc[1]: - encoding = loc[1] - if 0: - # Enable to switch off string to Unicode coercion and implicit - # Unicode to string conversion. - encoding = "undefined" - if encoding != "ascii": - # On Non-Unicode builds this will raise an AttributeError... - sys.setdefaultencoding(encoding) # Needs Python Unicode build ! - def execsitecustomize(): """Run custom site specific code, if available.""" @@ -510,12 +481,14 @@ def execsitecustomize(): import sitecustomize except ImportError: pass - except Exception: - if sys.flags.verbose: + except Exception as err: + if os.environ.get("PYTHONVERBOSE"): sys.excepthook(*sys.exc_info()) else: - print >>sys.stderr, \ - "'import sitecustomize' failed; use -v for traceback" + sys.stderr.write( + "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n" + "%s: %s\n" % + (err.__class__.__name__, err)) def execusercustomize(): @@ -524,22 +497,21 @@ def execusercustomize(): import usercustomize except ImportError: pass - except Exception: - if sys.flags.verbose: + except Exception as err: + if os.environ.get("PYTHONVERBOSE"): sys.excepthook(*sys.exc_info()) else: - print>>sys.stderr, \ - "'import usercustomize' failed; use -v for traceback" + sys.stderr.write( + "Error in usercustomize; set PYTHONVERBOSE for traceback:\n" + "%s: %s\n" % + (err.__class__.__name__, err)) def main(): global ENABLE_USER_SITE - abs__file__() + abs_paths() known_paths = removeduppaths() - if (os.name == "posix" and sys.path and - os.path.basename(sys.path[-1]) == "Modules"): - addbuilddir() if ENABLE_USER_SITE is None: ENABLE_USER_SITE = check_enableusersite() known_paths = addusersitepackages(known_paths) @@ -550,15 +522,9 @@ def main(): setcopyright() sethelper() 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. - if hasattr(sys, "setdefaultencoding"): - del sys.setdefaultencoding main() @@ -579,15 +545,15 @@ def _script(): """ args = sys.argv[1:] if not args: - print "sys.path = [" + 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 + 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 = [] @@ -597,7 +563,7 @@ def _script(): buffer.append(USER_SITE) if buffer: - print os.pathsep.join(buffer) + print(os.pathsep.join(buffer)) if ENABLE_USER_SITE: sys.exit(0) elif ENABLE_USER_SITE is False: @@ -608,7 +574,7 @@ def _script(): sys.exit(3) else: import textwrap - print textwrap.dedent(help % (sys.argv[0], os.pathsep)) + print(textwrap.dedent(help % (sys.argv[0], os.pathsep))) sys.exit(10) if __name__ == '__main__': |
