michael@0: """Append module search paths for third-party packages to sys.path. michael@0: michael@0: **************************************************************** michael@0: * This module is automatically imported during initialization. * michael@0: **************************************************************** michael@0: michael@0: In earlier versions of Python (up to 1.5a3), scripts or modules that michael@0: needed to use site-specific modules would place ``import site'' michael@0: somewhere near the top of their code. Because of the automatic michael@0: import, this is no longer necessary (but code that does it still michael@0: works). michael@0: michael@0: This will append site-specific paths to the module search path. On michael@0: Unix, it starts with sys.prefix and sys.exec_prefix (if different) and michael@0: appends lib/python/site-packages as well as lib/site-python. michael@0: It also supports the Debian convention of michael@0: lib/python/dist-packages. On other platforms (mainly Mac and michael@0: Windows), it uses just sys.prefix (and sys.exec_prefix, if different, michael@0: but this is unlikely). The resulting directories, if they exist, are michael@0: appended to sys.path, and also inspected for path configuration files. michael@0: michael@0: FOR DEBIAN, this sys.path is augmented with directories in /usr/local. michael@0: Local addons go into /usr/local/lib/python/site-packages michael@0: (resp. /usr/local/lib/site-python), Debian addons install into michael@0: /usr/{lib,share}/python/dist-packages. michael@0: michael@0: A path configuration file is a file whose name has the form michael@0: .pth; its contents are additional directories (one per line) michael@0: to be added to sys.path. Non-existing directories (or michael@0: non-directories) are never added to sys.path; no directory is added to michael@0: sys.path more than once. Blank lines and lines beginning with michael@0: '#' are skipped. Lines starting with 'import' are executed. michael@0: michael@0: For example, suppose sys.prefix and sys.exec_prefix are set to michael@0: /usr/local and there is a directory /usr/local/lib/python2.X/site-packages michael@0: with three subdirectories, foo, bar and spam, and two path michael@0: configuration files, foo.pth and bar.pth. Assume foo.pth contains the michael@0: following: michael@0: michael@0: # foo package configuration michael@0: foo michael@0: bar michael@0: bletch michael@0: michael@0: and bar.pth contains: michael@0: michael@0: # bar package configuration michael@0: bar michael@0: michael@0: Then the following directories are added to sys.path, in this order: michael@0: michael@0: /usr/local/lib/python2.X/site-packages/bar michael@0: /usr/local/lib/python2.X/site-packages/foo michael@0: michael@0: Note that bletch is omitted because it doesn't exist; bar precedes foo michael@0: because bar.pth comes alphabetically before foo.pth; and spam is michael@0: omitted because it is not mentioned in either path configuration file. michael@0: michael@0: After these path manipulations, an attempt is made to import a module michael@0: named sitecustomize, which can perform arbitrary additional michael@0: site-specific customizations. If this import fails with an michael@0: ImportError exception, it is silently ignored. michael@0: michael@0: """ michael@0: michael@0: import sys michael@0: import os michael@0: try: michael@0: import __builtin__ as builtins michael@0: except ImportError: michael@0: import builtins michael@0: try: michael@0: set michael@0: except NameError: michael@0: from sets import Set as set michael@0: michael@0: # Prefixes for site-packages; add additional prefixes like /usr/local here michael@0: PREFIXES = [sys.prefix, sys.exec_prefix] michael@0: # Enable per user site-packages directory michael@0: # set it to False to disable the feature or True to force the feature michael@0: ENABLE_USER_SITE = None michael@0: # for distutils.commands.install michael@0: USER_SITE = None michael@0: USER_BASE = None michael@0: michael@0: _is_64bit = (getattr(sys, 'maxsize', None) or getattr(sys, 'maxint')) > 2**32 michael@0: _is_pypy = hasattr(sys, 'pypy_version_info') michael@0: _is_jython = sys.platform[:4] == 'java' michael@0: if _is_jython: michael@0: ModuleType = type(os) michael@0: michael@0: def makepath(*paths): michael@0: dir = os.path.join(*paths) michael@0: if _is_jython and (dir == '__classpath__' or michael@0: dir.startswith('__pyclasspath__')): michael@0: return dir, dir michael@0: dir = os.path.abspath(dir) michael@0: return dir, os.path.normcase(dir) michael@0: michael@0: def abs__file__(): michael@0: """Set all module' __file__ attribute to an absolute path""" michael@0: for m in sys.modules.values(): michael@0: if ((_is_jython and not isinstance(m, ModuleType)) or michael@0: hasattr(m, '__loader__')): michael@0: # only modules need the abspath in Jython. and don't mess michael@0: # with a PEP 302-supplied __file__ michael@0: continue michael@0: f = getattr(m, '__file__', None) michael@0: if f is None: michael@0: continue michael@0: m.__file__ = os.path.abspath(f) michael@0: michael@0: def removeduppaths(): michael@0: """ Remove duplicate entries from sys.path along with making them michael@0: absolute""" michael@0: # This ensures that the initial path provided by the interpreter contains michael@0: # only absolute pathnames, even if we're running from the build directory. michael@0: L = [] michael@0: known_paths = set() michael@0: for dir in sys.path: michael@0: # Filter out duplicate paths (on case-insensitive file systems also michael@0: # if they only differ in case); turn relative paths into absolute michael@0: # paths. michael@0: dir, dircase = makepath(dir) michael@0: if not dircase in known_paths: michael@0: L.append(dir) michael@0: known_paths.add(dircase) michael@0: sys.path[:] = L michael@0: return known_paths michael@0: michael@0: # XXX This should not be part of site.py, since it is needed even when michael@0: # using the -S option for Python. See http://www.python.org/sf/586680 michael@0: def addbuilddir(): michael@0: """Append ./build/lib. in case we're running in the build dir michael@0: (especially for Guido :-)""" michael@0: from distutils.util import get_platform michael@0: s = "build/lib.%s-%.3s" % (get_platform(), sys.version) michael@0: if hasattr(sys, 'gettotalrefcount'): michael@0: s += '-pydebug' michael@0: s = os.path.join(os.path.dirname(sys.path[-1]), s) michael@0: sys.path.append(s) michael@0: michael@0: def _init_pathinfo(): michael@0: """Return a set containing all existing directory entries from sys.path""" michael@0: d = set() michael@0: for dir in sys.path: michael@0: try: michael@0: if os.path.isdir(dir): michael@0: dir, dircase = makepath(dir) michael@0: d.add(dircase) michael@0: except TypeError: michael@0: continue michael@0: return d michael@0: michael@0: def addpackage(sitedir, name, known_paths): michael@0: """Add a new path to known_paths by combining sitedir and 'name' or execute michael@0: sitedir if it starts with 'import'""" michael@0: if known_paths is None: michael@0: _init_pathinfo() michael@0: reset = 1 michael@0: else: michael@0: reset = 0 michael@0: fullname = os.path.join(sitedir, name) michael@0: try: michael@0: f = open(fullname, "rU") michael@0: except IOError: michael@0: return michael@0: try: michael@0: for line in f: michael@0: if line.startswith("#"): michael@0: continue michael@0: if line.startswith("import"): michael@0: exec(line) michael@0: continue michael@0: line = line.rstrip() michael@0: dir, dircase = makepath(sitedir, line) michael@0: if not dircase in known_paths and os.path.exists(dir): michael@0: sys.path.append(dir) michael@0: known_paths.add(dircase) michael@0: finally: michael@0: f.close() michael@0: if reset: michael@0: known_paths = None michael@0: return known_paths michael@0: michael@0: def addsitedir(sitedir, known_paths=None): michael@0: """Add 'sitedir' argument to sys.path if missing and handle .pth files in michael@0: 'sitedir'""" michael@0: if known_paths is None: michael@0: known_paths = _init_pathinfo() michael@0: reset = 1 michael@0: else: michael@0: reset = 0 michael@0: sitedir, sitedircase = makepath(sitedir) michael@0: if not sitedircase in known_paths: michael@0: sys.path.append(sitedir) # Add path component michael@0: try: michael@0: names = os.listdir(sitedir) michael@0: except os.error: michael@0: return michael@0: names.sort() michael@0: for name in names: michael@0: if name.endswith(os.extsep + "pth"): michael@0: addpackage(sitedir, name, known_paths) michael@0: if reset: michael@0: known_paths = None michael@0: return known_paths michael@0: michael@0: def addsitepackages(known_paths, sys_prefix=sys.prefix, exec_prefix=sys.exec_prefix): michael@0: """Add site-packages (and possibly site-python) to sys.path""" michael@0: prefixes = [os.path.join(sys_prefix, "local"), sys_prefix] michael@0: if exec_prefix != sys_prefix: michael@0: prefixes.append(os.path.join(exec_prefix, "local")) michael@0: michael@0: for prefix in prefixes: michael@0: if prefix: michael@0: if sys.platform in ('os2emx', 'riscos') or _is_jython: michael@0: sitedirs = [os.path.join(prefix, "Lib", "site-packages")] michael@0: elif _is_pypy: michael@0: sitedirs = [os.path.join(prefix, 'site-packages')] michael@0: elif sys.platform == 'darwin' and prefix == sys_prefix: michael@0: michael@0: if prefix.startswith("/System/Library/Frameworks/"): # Apple's Python michael@0: michael@0: sitedirs = [os.path.join("/Library/Python", sys.version[:3], "site-packages"), michael@0: os.path.join(prefix, "Extras", "lib", "python")] michael@0: michael@0: else: # any other Python distros on OSX work this way michael@0: sitedirs = [os.path.join(prefix, "lib", michael@0: "python" + sys.version[:3], "site-packages")] michael@0: michael@0: elif os.sep == '/': michael@0: sitedirs = [os.path.join(prefix, michael@0: "lib", michael@0: "python" + sys.version[:3], michael@0: "site-packages"), michael@0: os.path.join(prefix, "lib", "site-python"), michael@0: os.path.join(prefix, "python" + sys.version[:3], "lib-dynload")] michael@0: lib64_dir = os.path.join(prefix, "lib64", "python" + sys.version[:3], "site-packages") michael@0: if (os.path.exists(lib64_dir) and michael@0: os.path.realpath(lib64_dir) not in [os.path.realpath(p) for p in sitedirs]): michael@0: if _is_64bit: michael@0: sitedirs.insert(0, lib64_dir) michael@0: else: michael@0: sitedirs.append(lib64_dir) michael@0: try: michael@0: # sys.getobjects only available in --with-pydebug build michael@0: sys.getobjects michael@0: sitedirs.insert(0, os.path.join(sitedirs[0], 'debug')) michael@0: except AttributeError: michael@0: pass michael@0: # Debian-specific dist-packages directories: michael@0: if sys.version[0] == '2': michael@0: sitedirs.append(os.path.join(prefix, "lib", michael@0: "python" + sys.version[:3], michael@0: "dist-packages")) michael@0: else: michael@0: sitedirs.append(os.path.join(prefix, "lib", michael@0: "python" + sys.version[0], michael@0: "dist-packages")) michael@0: sitedirs.append(os.path.join(prefix, "local/lib", michael@0: "python" + sys.version[:3], michael@0: "dist-packages")) michael@0: sitedirs.append(os.path.join(prefix, "lib", "dist-python")) michael@0: else: michael@0: sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")] michael@0: if sys.platform == 'darwin': michael@0: # for framework builds *only* we add the standard Apple michael@0: # locations. Currently only per-user, but /Library and michael@0: # /Network/Library could be added too michael@0: if 'Python.framework' in prefix: michael@0: home = os.environ.get('HOME') michael@0: if home: michael@0: sitedirs.append( michael@0: os.path.join(home, michael@0: 'Library', michael@0: 'Python', michael@0: sys.version[:3], michael@0: 'site-packages')) michael@0: for sitedir in sitedirs: michael@0: if os.path.isdir(sitedir): michael@0: addsitedir(sitedir, known_paths) michael@0: return None michael@0: michael@0: def check_enableusersite(): michael@0: """Check if user site directory is safe for inclusion michael@0: michael@0: The function tests for the command line flag (including environment var), michael@0: process uid/gid equal to effective uid/gid. michael@0: michael@0: None: Disabled for security reasons michael@0: False: Disabled by user (command line option) michael@0: True: Safe and enabled michael@0: """ michael@0: if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False): michael@0: return False michael@0: michael@0: if hasattr(os, "getuid") and hasattr(os, "geteuid"): michael@0: # check process uid == effective uid michael@0: if os.geteuid() != os.getuid(): michael@0: return None michael@0: if hasattr(os, "getgid") and hasattr(os, "getegid"): michael@0: # check process gid == effective gid michael@0: if os.getegid() != os.getgid(): michael@0: return None michael@0: michael@0: return True michael@0: michael@0: def addusersitepackages(known_paths): michael@0: """Add a per user site-package to sys.path michael@0: michael@0: Each user has its own python directory with site-packages in the michael@0: home directory. michael@0: michael@0: USER_BASE is the root directory for all Python versions michael@0: michael@0: USER_SITE is the user specific site-packages directory michael@0: michael@0: USER_SITE/.. can be used for data. michael@0: """ michael@0: global USER_BASE, USER_SITE, ENABLE_USER_SITE michael@0: env_base = os.environ.get("PYTHONUSERBASE", None) michael@0: michael@0: def joinuser(*args): michael@0: return os.path.expanduser(os.path.join(*args)) michael@0: michael@0: #if sys.platform in ('os2emx', 'riscos'): michael@0: # # Don't know what to put here michael@0: # USER_BASE = '' michael@0: # USER_SITE = '' michael@0: if os.name == "nt": michael@0: base = os.environ.get("APPDATA") or "~" michael@0: if env_base: michael@0: USER_BASE = env_base michael@0: else: michael@0: USER_BASE = joinuser(base, "Python") michael@0: USER_SITE = os.path.join(USER_BASE, michael@0: "Python" + sys.version[0] + sys.version[2], michael@0: "site-packages") michael@0: else: michael@0: if env_base: michael@0: USER_BASE = env_base michael@0: else: michael@0: USER_BASE = joinuser("~", ".local") michael@0: USER_SITE = os.path.join(USER_BASE, "lib", michael@0: "python" + sys.version[:3], michael@0: "site-packages") michael@0: michael@0: if ENABLE_USER_SITE and os.path.isdir(USER_SITE): michael@0: addsitedir(USER_SITE, known_paths) michael@0: if ENABLE_USER_SITE: michael@0: for dist_libdir in ("lib", "local/lib"): michael@0: user_site = os.path.join(USER_BASE, dist_libdir, michael@0: "python" + sys.version[:3], michael@0: "dist-packages") michael@0: if os.path.isdir(user_site): michael@0: addsitedir(user_site, known_paths) michael@0: return known_paths michael@0: michael@0: michael@0: michael@0: def setBEGINLIBPATH(): michael@0: """The OS/2 EMX port has optional extension modules that do double duty michael@0: as DLLs (and must use the .DLL file extension) for other extensions. michael@0: The library search path needs to be amended so these will be found michael@0: during module import. Use BEGINLIBPATH so that these are at the start michael@0: of the library search path. michael@0: michael@0: """ michael@0: dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload") michael@0: libpath = os.environ['BEGINLIBPATH'].split(';') michael@0: if libpath[-1]: michael@0: libpath.append(dllpath) michael@0: else: michael@0: libpath[-1] = dllpath michael@0: os.environ['BEGINLIBPATH'] = ';'.join(libpath) michael@0: michael@0: michael@0: def setquit(): michael@0: """Define new built-ins 'quit' and 'exit'. michael@0: These are simply strings that display a hint on how to exit. michael@0: michael@0: """ michael@0: if os.sep == ':': michael@0: eof = 'Cmd-Q' michael@0: elif os.sep == '\\': michael@0: eof = 'Ctrl-Z plus Return' michael@0: else: michael@0: eof = 'Ctrl-D (i.e. EOF)' michael@0: michael@0: class Quitter(object): michael@0: def __init__(self, name): michael@0: self.name = name michael@0: def __repr__(self): michael@0: return 'Use %s() or %s to exit' % (self.name, eof) michael@0: def __call__(self, code=None): michael@0: # Shells like IDLE catch the SystemExit, but listen when their michael@0: # stdin wrapper is closed. michael@0: try: michael@0: sys.stdin.close() michael@0: except: michael@0: pass michael@0: raise SystemExit(code) michael@0: builtins.quit = Quitter('quit') michael@0: builtins.exit = Quitter('exit') michael@0: michael@0: michael@0: class _Printer(object): michael@0: """interactive prompt objects for printing the license text, a list of michael@0: contributors and the copyright notice.""" michael@0: michael@0: MAXLINES = 23 michael@0: michael@0: def __init__(self, name, data, files=(), dirs=()): michael@0: self.__name = name michael@0: self.__data = data michael@0: self.__files = files michael@0: self.__dirs = dirs michael@0: self.__lines = None michael@0: michael@0: def __setup(self): michael@0: if self.__lines: michael@0: return michael@0: data = None michael@0: for dir in self.__dirs: michael@0: for filename in self.__files: michael@0: filename = os.path.join(dir, filename) michael@0: try: michael@0: fp = open(filename, "rU") michael@0: data = fp.read() michael@0: fp.close() michael@0: break michael@0: except IOError: michael@0: pass michael@0: if data: michael@0: break michael@0: if not data: michael@0: data = self.__data michael@0: self.__lines = data.split('\n') michael@0: self.__linecnt = len(self.__lines) michael@0: michael@0: def __repr__(self): michael@0: self.__setup() michael@0: if len(self.__lines) <= self.MAXLINES: michael@0: return "\n".join(self.__lines) michael@0: else: michael@0: return "Type %s() to see the full %s text" % ((self.__name,)*2) michael@0: michael@0: def __call__(self): michael@0: self.__setup() michael@0: prompt = 'Hit Return for more, or q (and Return) to quit: ' michael@0: lineno = 0 michael@0: while 1: michael@0: try: michael@0: for i in range(lineno, lineno + self.MAXLINES): michael@0: print(self.__lines[i]) michael@0: except IndexError: michael@0: break michael@0: else: michael@0: lineno += self.MAXLINES michael@0: key = None michael@0: while key is None: michael@0: try: michael@0: key = raw_input(prompt) michael@0: except NameError: michael@0: key = input(prompt) michael@0: if key not in ('', 'q'): michael@0: key = None michael@0: if key == 'q': michael@0: break michael@0: michael@0: def setcopyright(): michael@0: """Set 'copyright' and 'credits' in __builtin__""" michael@0: builtins.copyright = _Printer("copyright", sys.copyright) michael@0: if _is_jython: michael@0: builtins.credits = _Printer( michael@0: "credits", michael@0: "Jython is maintained by the Jython developers (www.jython.org).") michael@0: elif _is_pypy: michael@0: builtins.credits = _Printer( michael@0: "credits", michael@0: "PyPy is maintained by the PyPy developers: http://pypy.org/") michael@0: else: michael@0: builtins.credits = _Printer("credits", """\ michael@0: Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands michael@0: for supporting Python development. See www.python.org for more information.""") michael@0: here = os.path.dirname(os.__file__) michael@0: builtins.license = _Printer( michael@0: "license", "See http://www.python.org/%.3s/license.html" % sys.version, michael@0: ["LICENSE.txt", "LICENSE"], michael@0: [os.path.join(here, os.pardir), here, os.curdir]) michael@0: michael@0: michael@0: class _Helper(object): michael@0: """Define the built-in 'help'. michael@0: This is a wrapper around pydoc.help (with a twist). michael@0: michael@0: """ michael@0: michael@0: def __repr__(self): michael@0: return "Type help() for interactive help, " \ michael@0: "or help(object) for help about object." michael@0: def __call__(self, *args, **kwds): michael@0: import pydoc michael@0: return pydoc.help(*args, **kwds) michael@0: michael@0: def sethelper(): michael@0: builtins.help = _Helper() michael@0: michael@0: def aliasmbcs(): michael@0: """On Windows, some default encodings are not provided by Python, michael@0: while they are always available as "mbcs" in each locale. Make michael@0: them usable by aliasing to "mbcs" in such a case.""" michael@0: if sys.platform == 'win32': michael@0: import locale, codecs michael@0: enc = locale.getdefaultlocale()[1] michael@0: if enc.startswith('cp'): # "cp***" ? michael@0: try: michael@0: codecs.lookup(enc) michael@0: except LookupError: michael@0: import encodings michael@0: encodings._cache[enc] = encodings._unknown michael@0: encodings.aliases.aliases[enc] = 'mbcs' michael@0: michael@0: def setencoding(): michael@0: """Set the string encoding used by the Unicode implementation. The michael@0: default is 'ascii', but if you're willing to experiment, you can michael@0: change this.""" michael@0: encoding = "ascii" # Default value set by _PyUnicode_Init() michael@0: if 0: michael@0: # Enable to support locale aware default string encodings. michael@0: import locale michael@0: loc = locale.getdefaultlocale() michael@0: if loc[1]: michael@0: encoding = loc[1] michael@0: if 0: michael@0: # Enable to switch off string to Unicode coercion and implicit michael@0: # Unicode to string conversion. michael@0: encoding = "undefined" michael@0: if encoding != "ascii": michael@0: # On Non-Unicode builds this will raise an AttributeError... michael@0: sys.setdefaultencoding(encoding) # Needs Python Unicode build ! michael@0: michael@0: michael@0: def execsitecustomize(): michael@0: """Run custom site specific code, if available.""" michael@0: try: michael@0: import sitecustomize michael@0: except ImportError: michael@0: pass michael@0: michael@0: def virtual_install_main_packages(): michael@0: f = open(os.path.join(os.path.dirname(__file__), 'orig-prefix.txt')) michael@0: sys.real_prefix = f.read().strip() michael@0: f.close() michael@0: pos = 2 michael@0: hardcoded_relative_dirs = [] michael@0: if sys.path[0] == '': michael@0: pos += 1 michael@0: if _is_jython: michael@0: paths = [os.path.join(sys.real_prefix, 'Lib')] michael@0: elif _is_pypy: michael@0: if sys.version_info > (3, 2): michael@0: cpyver = '%d' % sys.version_info[0] michael@0: elif sys.pypy_version_info >= (1, 5): michael@0: cpyver = '%d.%d' % sys.version_info[:2] michael@0: else: michael@0: cpyver = '%d.%d.%d' % sys.version_info[:3] michael@0: paths = [os.path.join(sys.real_prefix, 'lib_pypy'), michael@0: os.path.join(sys.real_prefix, 'lib-python', cpyver)] michael@0: if sys.pypy_version_info < (1, 9): michael@0: paths.insert(1, os.path.join(sys.real_prefix, michael@0: 'lib-python', 'modified-%s' % cpyver)) michael@0: hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below michael@0: # michael@0: # This is hardcoded in the Python executable, but relative to sys.prefix: michael@0: for path in paths[:]: michael@0: plat_path = os.path.join(path, 'plat-%s' % sys.platform) michael@0: if os.path.exists(plat_path): michael@0: paths.append(plat_path) michael@0: elif sys.platform == 'win32': michael@0: paths = [os.path.join(sys.real_prefix, 'Lib'), os.path.join(sys.real_prefix, 'DLLs')] michael@0: else: michael@0: paths = [os.path.join(sys.real_prefix, 'lib', 'python'+sys.version[:3])] michael@0: hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below michael@0: lib64_path = os.path.join(sys.real_prefix, 'lib64', 'python'+sys.version[:3]) michael@0: if os.path.exists(lib64_path): michael@0: if _is_64bit: michael@0: paths.insert(0, lib64_path) michael@0: else: michael@0: paths.append(lib64_path) michael@0: # This is hardcoded in the Python executable, but relative to michael@0: # sys.prefix. Debian change: we need to add the multiarch triplet michael@0: # here, which is where the real stuff lives. As per PEP 421, in michael@0: # Python 3.3+, this lives in sys.implementation, while in Python 2.7 michael@0: # it lives in sys. michael@0: try: michael@0: arch = getattr(sys, 'implementation', sys)._multiarch michael@0: except AttributeError: michael@0: # This is a non-multiarch aware Python. Fallback to the old way. michael@0: arch = sys.platform michael@0: plat_path = os.path.join(sys.real_prefix, 'lib', michael@0: 'python'+sys.version[:3], michael@0: 'plat-%s' % arch) michael@0: if os.path.exists(plat_path): michael@0: paths.append(plat_path) michael@0: # This is hardcoded in the Python executable, but michael@0: # relative to sys.prefix, so we have to fix up: michael@0: for path in list(paths): michael@0: tk_dir = os.path.join(path, 'lib-tk') michael@0: if os.path.exists(tk_dir): michael@0: paths.append(tk_dir) michael@0: michael@0: # These are hardcoded in the Apple's Python executable, michael@0: # but relative to sys.prefix, so we have to fix them up: michael@0: if sys.platform == 'darwin': michael@0: hardcoded_paths = [os.path.join(relative_dir, module) michael@0: for relative_dir in hardcoded_relative_dirs michael@0: for module in ('plat-darwin', 'plat-mac', 'plat-mac/lib-scriptpackages')] michael@0: michael@0: for path in hardcoded_paths: michael@0: if os.path.exists(path): michael@0: paths.append(path) michael@0: michael@0: sys.path.extend(paths) michael@0: michael@0: def force_global_eggs_after_local_site_packages(): michael@0: """ michael@0: Force easy_installed eggs in the global environment to get placed michael@0: in sys.path after all packages inside the virtualenv. This michael@0: maintains the "least surprise" result that packages in the michael@0: virtualenv always mask global packages, never the other way michael@0: around. michael@0: michael@0: """ michael@0: egginsert = getattr(sys, '__egginsert', 0) michael@0: for i, path in enumerate(sys.path): michael@0: if i > egginsert and path.startswith(sys.prefix): michael@0: egginsert = i michael@0: sys.__egginsert = egginsert + 1 michael@0: michael@0: def virtual_addsitepackages(known_paths): michael@0: force_global_eggs_after_local_site_packages() michael@0: return addsitepackages(known_paths, sys_prefix=sys.real_prefix) michael@0: michael@0: def fixclasspath(): michael@0: """Adjust the special classpath sys.path entries for Jython. These michael@0: entries should follow the base virtualenv lib directories. michael@0: """ michael@0: paths = [] michael@0: classpaths = [] michael@0: for path in sys.path: michael@0: if path == '__classpath__' or path.startswith('__pyclasspath__'): michael@0: classpaths.append(path) michael@0: else: michael@0: paths.append(path) michael@0: sys.path = paths michael@0: sys.path.extend(classpaths) michael@0: michael@0: def execusercustomize(): michael@0: """Run custom user specific code, if available.""" michael@0: try: michael@0: import usercustomize michael@0: except ImportError: michael@0: pass michael@0: michael@0: michael@0: def main(): michael@0: global ENABLE_USER_SITE michael@0: virtual_install_main_packages() michael@0: abs__file__() michael@0: paths_in_sys = removeduppaths() michael@0: if (os.name == "posix" and sys.path and michael@0: os.path.basename(sys.path[-1]) == "Modules"): michael@0: addbuilddir() michael@0: if _is_jython: michael@0: fixclasspath() michael@0: GLOBAL_SITE_PACKAGES = not os.path.exists(os.path.join(os.path.dirname(__file__), 'no-global-site-packages.txt')) michael@0: if not GLOBAL_SITE_PACKAGES: michael@0: ENABLE_USER_SITE = False michael@0: if ENABLE_USER_SITE is None: michael@0: ENABLE_USER_SITE = check_enableusersite() michael@0: paths_in_sys = addsitepackages(paths_in_sys) michael@0: paths_in_sys = addusersitepackages(paths_in_sys) michael@0: if GLOBAL_SITE_PACKAGES: michael@0: paths_in_sys = virtual_addsitepackages(paths_in_sys) michael@0: if sys.platform == 'os2emx': michael@0: setBEGINLIBPATH() michael@0: setquit() michael@0: setcopyright() michael@0: sethelper() michael@0: aliasmbcs() michael@0: setencoding() michael@0: execsitecustomize() michael@0: if ENABLE_USER_SITE: michael@0: execusercustomize() michael@0: # Remove sys.setdefaultencoding() so that users cannot change the michael@0: # encoding after initialization. The test for presence is needed when michael@0: # this module is run as a script, because this code is executed twice. michael@0: if hasattr(sys, "setdefaultencoding"): michael@0: del sys.setdefaultencoding michael@0: michael@0: main() michael@0: michael@0: def _script(): michael@0: help = """\ michael@0: %s [--user-base] [--user-site] michael@0: michael@0: Without arguments print some useful information michael@0: With arguments print the value of USER_BASE and/or USER_SITE separated michael@0: by '%s'. michael@0: michael@0: Exit codes with --user-base or --user-site: michael@0: 0 - user site directory is enabled michael@0: 1 - user site directory is disabled by user michael@0: 2 - uses site directory is disabled by super user michael@0: or for security reasons michael@0: >2 - unknown error michael@0: """ michael@0: args = sys.argv[1:] michael@0: if not args: michael@0: print("sys.path = [") michael@0: for dir in sys.path: michael@0: print(" %r," % (dir,)) michael@0: print("]") michael@0: def exists(path): michael@0: if os.path.isdir(path): michael@0: return "exists" michael@0: else: michael@0: return "doesn't exist" michael@0: print("USER_BASE: %r (%s)" % (USER_BASE, exists(USER_BASE))) michael@0: print("USER_SITE: %r (%s)" % (USER_SITE, exists(USER_BASE))) michael@0: print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE) michael@0: sys.exit(0) michael@0: michael@0: buffer = [] michael@0: if '--user-base' in args: michael@0: buffer.append(USER_BASE) michael@0: if '--user-site' in args: michael@0: buffer.append(USER_SITE) michael@0: michael@0: if buffer: michael@0: print(os.pathsep.join(buffer)) michael@0: if ENABLE_USER_SITE: michael@0: sys.exit(0) michael@0: elif ENABLE_USER_SITE is False: michael@0: sys.exit(1) michael@0: elif ENABLE_USER_SITE is None: michael@0: sys.exit(2) michael@0: else: michael@0: sys.exit(3) michael@0: else: michael@0: import textwrap michael@0: print(textwrap.dedent(help % (sys.argv[0], os.pathsep))) michael@0: sys.exit(10) michael@0: michael@0: if __name__ == '__main__': michael@0: _script()