+++ /dev/null
-"""Append module search paths for third-party packages to sys.path.\r
-\r
-****************************************************************\r
-* This module is automatically imported during initialization. *\r
-****************************************************************\r
-\r
-This is a UEFI-specific version of site.py.\r
-\r
-In earlier versions of Python (up to 1.5a3), scripts or modules that\r
-needed to use site-specific modules would place ``import site''\r
-somewhere near the top of their code. Because of the automatic\r
-import, this is no longer necessary (but code that does it still\r
-works).\r
-\r
-This will append site-specific paths to the module search path. It\r
-starts with sys.prefix and sys.exec_prefix (if different) and appends\r
-lib/python<version>/site-packages as well as lib/site-python.\r
-The resulting directories, if they exist, are appended to sys.path,\r
-and also inspected for path configuration files.\r
-\r
-A path configuration file is a file whose name has the form\r
-<package>.pth; its contents are additional directories (one per line)\r
-to be added to sys.path. Non-existing directories (or\r
-non-directories) are never added to sys.path; no directory is added to\r
-sys.path more than once. Blank lines and lines beginning with\r
-'#' are skipped. Lines starting with 'import' are executed.\r
-\r
-For example, suppose sys.prefix and sys.exec_prefix are set to\r
-/Efi/StdLib and there is a directory /Efi/StdLib/lib/python2.7/site-packages\r
-with three subdirectories, foo, bar and spam, and two path\r
-configuration files, foo.pth and bar.pth. Assume foo.pth contains the\r
-following:\r
-\r
- # foo package configuration\r
- foo\r
- bar\r
- bletch\r
-\r
-and bar.pth contains:\r
-\r
- # bar package configuration\r
- bar\r
-\r
-Then the following directories are added to sys.path, in this order:\r
-\r
- /Efi/StdLib/lib/python2.7/site-packages/bar\r
- /Efi/StdLib/lib/python2.7/site-packages/foo\r
-\r
-Note that bletch is omitted because it doesn't exist; bar precedes foo\r
-because bar.pth comes alphabetically before foo.pth; and spam is\r
-omitted because it is not mentioned in either path configuration file.\r
-\r
-After these path manipulations, an attempt is made to import a module\r
-named sitecustomize, which can perform arbitrary additional\r
-site-specific customizations. If this import fails with an\r
-ImportError exception, it is silently ignored.\r
-\r
-Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>\r
-This program and the accompanying materials are licensed and made available under\r
-the terms and conditions of the BSD License that accompanies this distribution.\r
-The full text of the license may be found at\r
-http://opensource.org/licenses/bsd-license.\r
-\r
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
-"""\r
-\r
-import sys\r
-import os\r
-import __builtin__\r
-import traceback\r
-\r
-# Prefixes for site-packages; add additional prefixes like /usr/local here\r
-PREFIXES = [sys.prefix, sys.exec_prefix]\r
-# Enable per user site-packages directory\r
-# set it to False to disable the feature or True to force the feature\r
-ENABLE_USER_SITE = False\r
-\r
-# for distutils.commands.install\r
-# These values are initialized by the getuserbase() and getusersitepackages()\r
-# functions, through the main() function when Python starts.\r
-USER_SITE = None\r
-USER_BASE = None\r
-\r
-\r
-def makepath(*paths):\r
- dir = os.path.join(*paths)\r
- try:\r
- dir = os.path.abspath(dir)\r
- except OSError:\r
- pass\r
- return dir, os.path.normcase(dir)\r
-\r
-\r
-def abs__file__():\r
- """Set all module' __file__ attribute to an absolute path"""\r
- for m in sys.modules.values():\r
- if hasattr(m, '__loader__'):\r
- continue # don't mess with a PEP 302-supplied __file__\r
- try:\r
- m.__file__ = os.path.abspath(m.__file__)\r
- except (AttributeError, OSError):\r
- pass\r
-\r
-\r
-def removeduppaths():\r
- """ Remove duplicate entries from sys.path along with making them\r
- absolute"""\r
- # This ensures that the initial path provided by the interpreter contains\r
- # only absolute pathnames, even if we're running from the build directory.\r
- L = []\r
- known_paths = set()\r
- for dir in sys.path:\r
- # Filter out duplicate paths (on case-insensitive file systems also\r
- # if they only differ in case); turn relative paths into absolute\r
- # paths.\r
- dir, dircase = makepath(dir)\r
- if not dircase in known_paths:\r
- L.append(dir)\r
- known_paths.add(dircase)\r
- sys.path[:] = L\r
- return known_paths\r
-\r
-\r
-def _init_pathinfo():\r
- """Return a set containing all existing directory entries from sys.path"""\r
- d = set()\r
- for dir in sys.path:\r
- try:\r
- if os.path.isdir(dir):\r
- dir, dircase = makepath(dir)\r
- d.add(dircase)\r
- except TypeError:\r
- continue\r
- return d\r
-\r
-\r
-def addpackage(sitedir, name, known_paths):\r
- """Process a .pth file within the site-packages directory:\r
- For each line in the file, either combine it with sitedir to a path\r
- and add that to known_paths, or execute it if it starts with 'import '.\r
- """\r
- if known_paths is None:\r
- _init_pathinfo()\r
- reset = 1\r
- else:\r
- reset = 0\r
- fullname = os.path.join(sitedir, name)\r
- try:\r
- f = open(fullname, "rU")\r
- except IOError:\r
- return\r
- with f:\r
- for n, line in enumerate(f):\r
- if line.startswith("#"):\r
- continue\r
- try:\r
- if line.startswith(("import ", "import\t")):\r
- exec line\r
- continue\r
- line = line.rstrip()\r
- dir, dircase = makepath(sitedir, line)\r
- if not dircase in known_paths and os.path.exists(dir):\r
- sys.path.append(dir)\r
- known_paths.add(dircase)\r
- except Exception as err:\r
- print >>sys.stderr, "Error processing line {:d} of {}:\n".format(\r
- n+1, fullname)\r
- for record in traceback.format_exception(*sys.exc_info()):\r
- for line in record.splitlines():\r
- print >>sys.stderr, ' '+line\r
- print >>sys.stderr, "\nRemainder of file ignored"\r
- break\r
- if reset:\r
- known_paths = None\r
- return known_paths\r
-\r
-\r
-def addsitedir(sitedir, known_paths=None):\r
- """Add 'sitedir' argument to sys.path if missing and handle .pth files in\r
- 'sitedir'"""\r
- if known_paths is None:\r
- known_paths = _init_pathinfo()\r
- reset = 1\r
- else:\r
- reset = 0\r
- sitedir, sitedircase = makepath(sitedir)\r
- if not sitedircase in known_paths:\r
- sys.path.append(sitedir) # Add path component\r
- try:\r
- names = os.listdir(sitedir)\r
- except os.error:\r
- return\r
- dotpth = os.extsep + "pth"\r
- names = [name for name in names if name.endswith(dotpth)]\r
- for name in sorted(names):\r
- addpackage(sitedir, name, known_paths)\r
- if reset:\r
- known_paths = None\r
- return known_paths\r
-\r
-\r
-def check_enableusersite():\r
- """Check if user site directory is safe for inclusion\r
-\r
- The function tests for the command line flag (including environment var),\r
- process uid/gid equal to effective uid/gid.\r
-\r
- None: Disabled for security reasons\r
- False: Disabled by user (command line option)\r
- True: Safe and enabled\r
- """\r
- if sys.flags.no_user_site:\r
- return False\r
-\r
- if hasattr(os, "getuid") and hasattr(os, "geteuid"):\r
- # check process uid == effective uid\r
- if os.geteuid() != os.getuid():\r
- return None\r
- if hasattr(os, "getgid") and hasattr(os, "getegid"):\r
- # check process gid == effective gid\r
- if os.getegid() != os.getgid():\r
- return None\r
-\r
- return True\r
-\r
-def getuserbase():\r
- """Returns the `user base` directory path.\r
-\r
- The `user base` directory can be used to store data. If the global\r
- variable ``USER_BASE`` is not initialized yet, this function will also set\r
- it.\r
- """\r
- global USER_BASE\r
- if USER_BASE is not None:\r
- return USER_BASE\r
- from sysconfig import get_config_var\r
- USER_BASE = get_config_var('userbase')\r
- return USER_BASE\r
-\r
-def getusersitepackages():\r
- """Returns the user-specific site-packages directory path.\r
-\r
- If the global variable ``USER_SITE`` is not initialized yet, this\r
- function will also set it.\r
- """\r
- global USER_SITE\r
- user_base = getuserbase() # this will also set USER_BASE\r
-\r
- if USER_SITE is not None:\r
- return USER_SITE\r
-\r
- from sysconfig import get_path\r
- import os\r
-\r
- USER_SITE = get_path('purelib', '%s_user' % os.name)\r
- return USER_SITE\r
-\r
-def addusersitepackages(known_paths):\r
- """Add a per user site-package to sys.path\r
-\r
- Each user has its own python directory with site-packages in the\r
- home directory.\r
- """\r
- # get the per user site-package path\r
- # this call will also make sure USER_BASE and USER_SITE are set\r
- user_site = getusersitepackages()\r
-\r
- if ENABLE_USER_SITE and os.path.isdir(user_site):\r
- addsitedir(user_site, known_paths)\r
- return known_paths\r
-\r
-def getsitepackages():\r
- """Returns a list containing all global site-packages directories\r
- (and possibly site-python).\r
-\r
- For each directory present in the global ``PREFIXES``, this function\r
- will find its `site-packages` subdirectory depending on the system\r
- environment, and will return a list of full paths.\r
- """\r
- sitepackages = []\r
- seen = set()\r
-\r
- for prefix in PREFIXES:\r
- if not prefix or prefix in seen:\r
- continue\r
- seen.add(prefix)\r
-\r
- sitepackages.append(os.path.join(prefix, "lib",\r
- "python." + sys.version[0] + sys.version[2],\r
- "site-packages"))\r
- sitepackages.append(os.path.join(prefix, "lib", "site-python"))\r
- return sitepackages\r
-\r
-def addsitepackages(known_paths):\r
- """Add site-packages (and possibly site-python) to sys.path"""\r
- for sitedir in getsitepackages():\r
- if os.path.isdir(sitedir):\r
- addsitedir(sitedir, known_paths)\r
-\r
- return known_paths\r
-\r
-def setBEGINLIBPATH():\r
- """The UEFI port has optional extension modules that do double duty\r
- as DLLs (even though they have .efi file extensions) for other extensions.\r
- The library search path needs to be amended so these will be found\r
- during module import. Use BEGINLIBPATH so that these are at the start\r
- of the library search path.\r
-\r
- """\r
- dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")\r
- libpath = os.environ['BEGINLIBPATH'].split(os.path.pathsep)\r
- if libpath[-1]:\r
- libpath.append(dllpath)\r
- else:\r
- libpath[-1] = dllpath\r
- os.environ['BEGINLIBPATH'] = os.path.pathsep.join(libpath)\r
-\r
-\r
-def setquit():\r
- """Define new builtins 'quit' and 'exit'.\r
-\r
- These are objects which make the interpreter exit when called.\r
- The repr of each object contains a hint at how it works.\r
-\r
- """\r
- eof = 'Ctrl-D (i.e. EOF)'\r
-\r
- class Quitter(object):\r
- def __init__(self, name):\r
- self.name = name\r
- def __repr__(self):\r
- return 'Use %s() or %s to exit' % (self.name, eof)\r
- def __call__(self, code=None):\r
- # Shells like IDLE catch the SystemExit, but listen when their\r
- # stdin wrapper is closed.\r
- try:\r
- sys.stdin.close()\r
- except:\r
- pass\r
- raise SystemExit(code)\r
- __builtin__.quit = Quitter('quit')\r
- __builtin__.exit = Quitter('exit')\r
-\r
-\r
-class _Printer(object):\r
- """interactive prompt objects for printing the license text, a list of\r
- contributors and the copyright notice."""\r
-\r
- MAXLINES = 23\r
-\r
- def __init__(self, name, data, files=(), dirs=()):\r
- self.__name = name\r
- self.__data = data\r
- self.__files = files\r
- self.__dirs = dirs\r
- self.__lines = None\r
-\r
- def __setup(self):\r
- if self.__lines:\r
- return\r
- data = None\r
- for dir in self.__dirs:\r
- for filename in self.__files:\r
- filename = os.path.join(dir, filename)\r
- try:\r
- fp = file(filename, "rU")\r
- data = fp.read()\r
- fp.close()\r
- break\r
- except IOError:\r
- pass\r
- if data:\r
- break\r
- if not data:\r
- data = self.__data\r
- self.__lines = data.split('\n')\r
- self.__linecnt = len(self.__lines)\r
-\r
- def __repr__(self):\r
- self.__setup()\r
- if len(self.__lines) <= self.MAXLINES:\r
- return "\n".join(self.__lines)\r
- else:\r
- return "Type %s() to see the full %s text" % ((self.__name,)*2)\r
-\r
- def __call__(self):\r
- self.__setup()\r
- prompt = 'Hit Return for more, or q (and Return) to quit: '\r
- lineno = 0\r
- while 1:\r
- try:\r
- for i in range(lineno, lineno + self.MAXLINES):\r
- print self.__lines[i]\r
- except IndexError:\r
- break\r
- else:\r
- lineno += self.MAXLINES\r
- key = None\r
- while key is None:\r
- key = raw_input(prompt)\r
- if key not in ('', 'q'):\r
- key = None\r
- if key == 'q':\r
- break\r
-\r
-def setcopyright():\r
- """Set 'copyright' and 'credits' in __builtin__"""\r
- __builtin__.copyright = _Printer("copyright", sys.copyright)\r
- __builtin__.credits = _Printer("credits", """\\r
- Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands\r
- for supporting Python development. See www.python.org for more information.""")\r
- here = os.path.dirname(os.__file__)\r
- __builtin__.license = _Printer(\r
- "license", "See http://www.python.org/%.3s/license.html" % sys.version,\r
- ["LICENSE.txt", "LICENSE"],\r
- [os.path.join(here, os.pardir), here, os.curdir])\r
-\r
-\r
-class _Helper(object):\r
- """Define the builtin 'help'.\r
- This is a wrapper around pydoc.help (with a twist).\r
-\r
- """\r
-\r
- def __repr__(self):\r
- return "Type help() for interactive help, " \\r
- "or help(object) for help about object."\r
-\r
- def __call__(self, *args, **kwds):\r
- import pydoc\r
- return pydoc.help(*args, **kwds)\r
-\r
-def sethelper():\r
- __builtin__.help = _Helper()\r
-\r
-####\r
-# Keep around for future mbcs support.\r
-####\r
-#def aliasmbcs():\r
-# """On Windows, some default encodings are not provided by Python,\r
-# while they are always available as "mbcs" in each locale. Make\r
-# them usable by aliasing to "mbcs" in such a case."""\r
-# if sys.platform == 'win32':\r
-# import locale, codecs\r
-# enc = locale.getdefaultlocale()[1]\r
-# if enc.startswith('cp'): # "cp***" ?\r
-# try:\r
-# codecs.lookup(enc)\r
-# except LookupError:\r
-# import encodings\r
-# encodings._cache[enc] = encodings._unknown\r
-# encodings.aliases.aliases[enc] = 'mbcs'\r
-\r
-def setencoding():\r
- """Set the string encoding used by the Unicode implementation. The\r
- default is 'ascii', but if you're willing to experiment, you can\r
- change this."""\r
- encoding = "ascii" # Default value set by _PyUnicode_Init()\r
- if 0:\r
- # Enable to support locale aware default string encodings.\r
- import locale\r
- loc = locale.getdefaultlocale()\r
- if loc[1]:\r
- encoding = loc[1]\r
- if 0:\r
- # Enable to switch off string to Unicode coercion and implicit\r
- # Unicode to string conversion.\r
- encoding = "undefined"\r
- if encoding != "ascii":\r
- # On Non-Unicode builds this will raise an AttributeError...\r
- sys.setdefaultencoding(encoding) # Needs Python Unicode build !\r
-\r
-\r
-def execsitecustomize():\r
- """Run custom site specific code, if available."""\r
- try:\r
- import sitecustomize\r
- except ImportError:\r
- pass\r
- except Exception:\r
- if sys.flags.verbose:\r
- sys.excepthook(*sys.exc_info())\r
- else:\r
- print >>sys.stderr, \\r
- "'import sitecustomize' failed; use -v for traceback"\r
-\r
-\r
-def execusercustomize():\r
- """Run custom user specific code, if available."""\r
- try:\r
- import usercustomize\r
- except ImportError:\r
- pass\r
- except Exception:\r
- if sys.flags.verbose:\r
- sys.excepthook(*sys.exc_info())\r
- else:\r
- print>>sys.stderr, \\r
- "'import usercustomize' failed; use -v for traceback"\r
-\r
-\r
-def main():\r
- abs__file__()\r
- known_paths = removeduppaths()\r
- known_paths = addsitepackages(known_paths)\r
- setquit()\r
- setcopyright()\r
- sethelper()\r
-# aliasmbcs()\r
- setencoding()\r
- execsitecustomize()\r
- # Remove sys.setdefaultencoding() so that users cannot change the\r
- # encoding after initialization. The test for presence is needed when\r
- # this module is run as a script, because this code is executed twice.\r
- if hasattr(sys, "setdefaultencoding"):\r
- del sys.setdefaultencoding\r
-\r
-main()\r
-\r
-def _script():\r
- help = """\\r
- %s\r
-\r
- Path elements are normally separated by '%s'.\r
- """\r
- print "sys.path = ["\r
- for dir in sys.path:\r
- print " %r," % (dir,)\r
- print "]"\r
-\r
- import textwrap\r
- print textwrap.dedent(help % (sys.argv[0], os.pathsep))\r
- sys.exit(0)\r
-\r
-if __name__ == '__main__':\r
- _script()\r