]>
git.proxmox.com Git - mirror_edk2.git/blob - AppPkg/Applications/Python/Python-2.7.10/PyMod-2.7.10/Lib/site.py
1 """Append module search paths for third-party packages to sys.path.
3 ****************************************************************
4 * This module is automatically imported during initialization. *
5 ****************************************************************
7 This is a UEFI-specific version of site.py.
9 In earlier versions of Python (up to 1.5a3), scripts or modules that
10 needed to use site-specific modules would place ``import site''
11 somewhere near the top of their code. Because of the automatic
12 import, this is no longer necessary (but code that does it still
15 This will append site-specific paths to the module search path. It starts with sys.prefix and
16 sys.exec_prefix (if different) and appends
17 lib/python<version>/site-packages as well as lib/site-python.
19 resulting directories, if they exist, are appended to sys.path, and
20 also inspected for path configuration files.
22 A path configuration file is a file whose name has the form
23 <package>.pth; its contents are additional directories (one per line)
24 to be added to sys.path. Non-existing directories (or
25 non-directories) are never added to sys.path; no directory is added to
26 sys.path more than once. Blank lines and lines beginning with
27 '#' are skipped. Lines starting with 'import' are executed.
29 For example, suppose sys.prefix and sys.exec_prefix are set to
30 /Efi/StdLib and there is a directory /Efi/StdLib/lib/python27.10/site-packages
31 with three subdirectories, foo, bar and spam, and two path
32 configuration files, foo.pth and bar.pth. Assume foo.pth contains the
35 # foo package configuration
42 # bar package configuration
45 Then the following directories are added to sys.path, in this order:
47 /Efi/StdLib/lib/python27.10/site-packages/bar
48 /Efi/StdLib/lib/python27.10/site-packages/foo
50 Note that bletch is omitted because it doesn't exist; bar precedes foo
51 because bar.pth comes alphabetically before foo.pth; and spam is
52 omitted because it is not mentioned in either path configuration file.
54 After these path manipulations, an attempt is made to import a module
55 named sitecustomize, which can perform arbitrary additional
56 site-specific customizations. If this import fails with an
57 ImportError exception, it is silently ignored.
59 Copyright (c) 2015, Daryl McDaniel. All rights reserved.<BR>
60 Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>
61 This program and the accompanying materials are licensed and made available under
62 the terms and conditions of the BSD License that accompanies this distribution.
63 The full text of the license may be found at
64 http://opensource.org/licenses/bsd-license.
66 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
67 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
75 # Prefixes for site-packages; add additional prefixes like /usr/local here
76 PREFIXES
= [sys
.prefix
, sys
.exec_prefix
]
77 # Enable per user site-packages directory
78 # set it to False to disable the feature or True to force the feature
79 ENABLE_USER_SITE
= False
81 # for distutils.commands.install
82 # These values are initialized by the getuserbase() and getusersitepackages()
83 # functions, through the main() function when Python starts.
89 dir = os
.path
.join(*paths
)
91 dir = os
.path
.abspath(dir)
94 return dir, os
.path
.normcase(dir)
98 """Set all module' __file__ attribute to an absolute path"""
99 for m
in sys
.modules
.values():
100 if hasattr(m
, '__loader__'):
101 continue # don't mess with a PEP 302-supplied __file__
103 m
.__file
__ = os
.path
.abspath(m
.__file
__)
104 except (AttributeError, OSError):
108 def removeduppaths():
109 """ Remove duplicate entries from sys.path along with making them
111 # This ensures that the initial path provided by the interpreter contains
112 # only absolute pathnames, even if we're running from the build directory.
116 # Filter out duplicate paths (on case-insensitive file systems also
117 # if they only differ in case); turn relative paths into absolute
119 dir, dircase
= makepath(dir)
120 if not dircase
in known_paths
:
122 known_paths
.add(dircase
)
127 def _init_pathinfo():
128 """Return a set containing all existing directory entries from sys.path"""
132 if os
.path
.isdir(dir):
133 dir, dircase
= makepath(dir)
140 def addpackage(sitedir
, name
, known_paths
):
141 """Process a .pth file within the site-packages directory:
142 For each line in the file, either combine it with sitedir to a path
143 and add that to known_paths, or execute it if it starts with 'import '.
145 if known_paths
is None:
150 fullname
= os
.path
.join(sitedir
, name
)
152 f
= open(fullname
, "rU")
156 for n
, line
in enumerate(f
):
157 if line
.startswith("#"):
160 if line
.startswith(("import ", "import\t")):
164 dir, dircase
= makepath(sitedir
, line
)
165 if not dircase
in known_paths
and os
.path
.exists(dir):
167 known_paths
.add(dircase
)
168 except Exception as err
:
169 print >>sys
.stderr
, "Error processing line {:d} of {}:\n".format(
171 for record
in traceback
.format_exception(*sys
.exc_info()):
172 for line
in record
.splitlines():
173 print >>sys
.stderr
, ' '+line
174 print >>sys
.stderr
, "\nRemainder of file ignored"
181 def addsitedir(sitedir
, known_paths
=None):
182 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
184 if known_paths
is None:
185 known_paths
= _init_pathinfo()
189 sitedir
, sitedircase
= makepath(sitedir
)
190 if not sitedircase
in known_paths
:
191 sys
.path
.append(sitedir
) # Add path component
193 names
= os
.listdir(sitedir
)
196 dotpth
= os
.extsep
+ "pth"
197 names
= [name
for name
in names
if name
.endswith(dotpth
)]
198 for name
in sorted(names
):
199 addpackage(sitedir
, name
, known_paths
)
205 def check_enableusersite():
206 """Check if user site directory is safe for inclusion
208 The function tests for the command line flag (including environment var),
209 process uid/gid equal to effective uid/gid.
211 None: Disabled for security reasons
212 False: Disabled by user (command line option)
213 True: Safe and enabled
215 if sys
.flags
.no_user_site
:
218 if hasattr(os
, "getuid") and hasattr(os
, "geteuid"):
219 # check process uid == effective uid
220 if os
.geteuid() != os
.getuid():
222 if hasattr(os
, "getgid") and hasattr(os
, "getegid"):
223 # check process gid == effective gid
224 if os
.getegid() != os
.getgid():
230 """Returns the `user base` directory path.
232 The `user base` directory can be used to store data. If the global
233 variable ``USER_BASE`` is not initialized yet, this function will also set
237 if USER_BASE
is not None:
239 from sysconfig
import get_config_var
240 USER_BASE
= get_config_var('userbase')
243 def getusersitepackages():
244 """Returns the user-specific site-packages directory path.
246 If the global variable ``USER_SITE`` is not initialized yet, this
247 function will also set it.
250 user_base
= getuserbase() # this will also set USER_BASE
252 if USER_SITE
is not None:
255 from sysconfig
import get_path
258 USER_SITE
= get_path('purelib', '%s_user' % os
.name
)
261 def addusersitepackages(known_paths
):
262 """Add a per user site-package to sys.path
264 Each user has its own python directory with site-packages in the
267 if ENABLE_USER_SITE
and os
.path
.isdir(user_site
):
268 # get the per user site-package path
269 # this call will also make sure USER_BASE and USER_SITE are set
270 user_site
= getusersitepackages()
272 addsitedir(user_site
, known_paths
)
275 def getsitepackages():
276 """Returns a list containing all global site-packages directories
277 (and possibly site-python).
279 For each directory present in the global ``PREFIXES``, this function
280 will find its `site-packages` subdirectory depending on the system
281 environment, and will return a list of full paths.
286 for prefix
in PREFIXES
:
287 if not prefix
or prefix
in seen
:
291 ix
= sys
.version
.find(' ')
293 micro
= sys
.version
[4:ix
]
297 sitepackages
.append(os
.path
.join(prefix
, "lib",
298 "python" + sys
.version
[0] + sys
.version
[2] + '.' + micro
,
300 sitepackages
.append(os
.path
.join(prefix
, "lib", "site-python"))
303 def addsitepackages(known_paths
):
304 """Add site-packages (and possibly site-python) to sys.path"""
305 for sitedir
in getsitepackages():
306 if os
.path
.isdir(sitedir
):
307 addsitedir(sitedir
, known_paths
)
311 def setBEGINLIBPATH():
312 """The UEFI port has optional extension modules that do double duty
313 as DLLs (even though they have .efi file extensions) for other extensions.
314 The library search path needs to be amended so these will be found
315 during module import. Use BEGINLIBPATH so that these are at the start
316 of the library search path.
319 dllpath
= os
.path
.join(sys
.prefix
, "Lib", "lib-dynload")
320 libpath
= os
.environ
['BEGINLIBPATH'].split(os
.path
.pathsep
)
322 libpath
.append(dllpath
)
324 libpath
[-1] = dllpath
325 os
.environ
['BEGINLIBPATH'] = os
.path
.pathsep
.join(libpath
)
329 """Define new builtins 'quit' and 'exit'.
331 These are objects which make the interpreter exit when called.
332 The repr of each object contains a hint at how it works.
335 eof
= 'Ctrl-D (i.e. EOF)'
337 class Quitter(object):
338 def __init__(self
, name
):
341 return 'Use %s() or %s to exit' % (self
.name
, eof
)
342 def __call__(self
, code
=None):
343 # Shells like IDLE catch the SystemExit, but listen when their
344 # stdin wrapper is closed.
349 raise SystemExit(code
)
350 __builtin__
.quit
= Quitter('quit')
351 __builtin__
.exit
= Quitter('exit')
354 class _Printer(object):
355 """interactive prompt objects for printing the license text, a list of
356 contributors and the copyright notice."""
360 def __init__(self
, name
, data
, files
=(), dirs
=()):
371 for dir in self
.__dirs
:
372 for filename
in self
.__files
:
373 filename
= os
.path
.join(dir, filename
)
375 fp
= file(filename
, "rU")
385 self
.__lines
= data
.split('\n')
386 self
.__linecnt
= len(self
.__lines
)
390 if len(self
.__lines
) <= self
.MAXLINES
:
391 return "\n".join(self
.__lines
)
393 return "Type %s() to see the full %s text" % ((self
.__name
,)*2)
397 prompt
= 'Hit Return for more, or q (and Return) to quit: '
401 for i
in range(lineno
, lineno
+ self
.MAXLINES
):
402 print self
.__lines
[i
]
406 lineno
+= self
.MAXLINES
409 key
= raw_input(prompt
)
410 if key
not in ('', 'q'):
416 """Set 'copyright' and 'credits' in __builtin__"""
417 __builtin__
.copyright
= _Printer("copyright", sys
.copyright
)
418 __builtin__
.credits
= _Printer("credits", """\
419 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
420 for supporting Python development. See www.python.org for more information.""")
421 here
= os
.path
.dirname(os
.__file
__)
422 __builtin__
.license
= _Printer(
423 "license", "See https://www.python.org/psf/license/",
424 ["LICENSE.txt", "LICENSE"],
425 [os
.path
.join(here
, os
.pardir
), here
, os
.curdir
])
428 class _Helper(object):
429 """Define the builtin 'help'.
430 This is a wrapper around pydoc.help (with a twist).
435 return "Type help() for interactive help, " \
436 "or help(object) for help about object."
437 def __call__(self
, *args
, **kwds
):
439 return pydoc
.help(*args
, **kwds
)
442 __builtin__
.help = _Helper()
445 """Set the string encoding used by the Unicode implementation. The
446 default is 'ascii', but if you're willing to experiment, you can
448 encoding
= "ascii" # Default value set by _PyUnicode_Init()
450 # Enable to support locale aware default string encodings.
452 loc
= locale
.getdefaultlocale()
456 # Enable to switch off string to Unicode coercion and implicit
457 # Unicode to string conversion.
458 encoding
= "undefined"
459 if encoding
!= "ascii":
460 # On Non-Unicode builds this will raise an AttributeError...
461 sys
.setdefaultencoding(encoding
) # Needs Python Unicode build !
464 def execsitecustomize():
465 """Run custom site specific code, if available."""
471 if sys
.flags
.verbose
:
472 sys
.excepthook(*sys
.exc_info())
474 print >>sys
.stderr
, \
475 "'import sitecustomize' failed; use -v for traceback"
478 def execusercustomize():
479 """Run custom user specific code, if available."""
485 if sys
.flags
.verbose
:
486 sys
.excepthook(*sys
.exc_info())
489 "'import usercustomize' failed; use -v for traceback"
493 global ENABLE_USER_SITE
496 known_paths
= removeduppaths()
497 if ENABLE_USER_SITE
is None:
498 ENABLE_USER_SITE
= check_enableusersite()
499 known_paths
= addusersitepackages(known_paths
)
500 known_paths
= addsitepackages(known_paths
)
506 # Remove sys.setdefaultencoding() so that users cannot change the
507 # encoding after initialization. The test for presence is needed when
508 # this module is run as a script, because this code is executed twice.
509 if hasattr(sys
, "setdefaultencoding"):
510 del sys
.setdefaultencoding
518 Path elements are normally separated by '%s'.
523 print " %r," % (dir,)
527 print textwrap
.dedent(help % (sys
.argv
[0], os
.pathsep
))
530 if __name__
== '__main__':