Back to index

python3.2  3.2.2
Classes | Functions | Variables
site Namespace Reference

Classes

class  _Printer
class  _Helper

Functions

def makepath
def abs_paths
def removeduppaths
def _init_pathinfo
def addpackage
def addsitedir
def check_enableusersite
def getuserbase
def getusersitepackages
def addusersitepackages
def getsitepackages
def addsitepackages
def setBEGINLIBPATH
def setquit
def setcopyright
def sethelper
def aliasmbcs
def execsitecustomize
def execusercustomize
def main
def _script

Variables

list PREFIXES = [sys.prefix, sys.exec_prefix]
 ENABLE_USER_SITE = None
 USER_SITE = None
 USER_BASE = None
 name

Detailed Description

Append module search paths for third-party packages to sys.path.

****************************************************************
* This module is automatically imported during initialization. *
****************************************************************

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
lib/python<version>/site-packages as well as lib/site-python.
On other platforms (such as Windows), it tries each of the
prefixes directly, as well as with lib/site-packages appended.  The
resulting directories, if they exist, are appended to sys.path, and
also inspected for path configuration files.

A path configuration file is a file whose name has the form
<package>.pth; its contents are additional directories (one per line)
to be added to sys.path.  Non-existing directories (or
non-directories) are never added to sys.path; no directory is added to
sys.path more than once.  Blank lines and lines beginning with
'#' are skipped. Lines starting with 'import' are executed.

For example, suppose sys.prefix and sys.exec_prefix are set to
/usr/local and there is a directory /usr/local/lib/python2.5/site-packages
with three subdirectories, foo, bar and spam, and two path
configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
following:

  # foo package configuration
  foo
  bar
  bletch

and bar.pth contains:

  # bar package configuration
  bar

Then the following directories are added to sys.path, in this order:

  /usr/local/lib/python2.5/site-packages/bar
  /usr/local/lib/python2.5/site-packages/foo

Note that bletch is omitted because it doesn't exist; bar precedes foo
because bar.pth comes alphabetically before foo.pth; and spam is
omitted because it is not mentioned in either path configuration file.

After these path manipulations, an attempt is made to import a module
named sitecustomize, which can perform arbitrary additional
site-specific customizations.  If this import fails with an
ImportError exception, it is silently ignored.

Function Documentation

def site._init_pathinfo ( ) [private]
Return a set containing all existing directory entries from sys.path

Definition at line 116 of file site.py.

00116 
00117 def _init_pathinfo():
00118     """Return a set containing all existing directory entries from sys.path"""
00119     d = set()
00120     for dir in sys.path:
00121         try:
00122             if os.path.isdir(dir):
00123                 dir, dircase = makepath(dir)
00124                 d.add(dircase)
00125         except TypeError:
00126             continue
00127     return d
00128 

Here is the call graph for this function:

Here is the caller graph for this function:

def site._script ( ) [private]

Definition at line 531 of file site.py.

00531 
00532 def _script():
00533     help = """\
00534     %s [--user-base] [--user-site]
00535 
00536     Without arguments print some useful information
00537     With arguments print the value of USER_BASE and/or USER_SITE separated
00538     by '%s'.
00539 
00540     Exit codes with --user-base or --user-site:
00541       0 - user site directory is enabled
00542       1 - user site directory is disabled by user
00543       2 - uses site directory is disabled by super user
00544           or for security reasons
00545      >2 - unknown error
00546     """
00547     args = sys.argv[1:]
00548     if not args:
00549         print("sys.path = [")
00550         for dir in sys.path:
00551             print("    %r," % (dir,))
00552         print("]")
00553         print("USER_BASE: %r (%s)" % (USER_BASE,
00554             "exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
00555         print("USER_SITE: %r (%s)" % (USER_SITE,
00556             "exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
00557         print("ENABLE_USER_SITE: %r" %  ENABLE_USER_SITE)
00558         sys.exit(0)
00559 
00560     buffer = []
00561     if '--user-base' in args:
00562         buffer.append(USER_BASE)
00563     if '--user-site' in args:
00564         buffer.append(USER_SITE)
00565 
00566     if buffer:
00567         print(os.pathsep.join(buffer))
00568         if ENABLE_USER_SITE:
00569             sys.exit(0)
00570         elif ENABLE_USER_SITE is False:
00571             sys.exit(1)
00572         elif ENABLE_USER_SITE is None:
00573             sys.exit(2)
00574         else:
00575             sys.exit(3)
00576     else:
00577         import textwrap
00578         print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
00579         sys.exit(10)

Here is the call graph for this function:

def site.abs_paths ( )
Set all module __file__ and __cached__ attributes to an absolute path

Definition at line 82 of file site.py.

00082 
00083 def abs_paths():
00084     """Set all module __file__ and __cached__ attributes to an absolute path"""
00085     for m in set(sys.modules.values()):
00086         if hasattr(m, '__loader__'):
00087             continue   # don't mess with a PEP 302-supplied __file__
00088         try:
00089             m.__file__ = os.path.abspath(m.__file__)
00090         except (AttributeError, OSError):
00091             pass
00092         try:
00093             m.__cached__ = os.path.abspath(m.__cached__)
00094         except (AttributeError, OSError):
00095             pass
00096 

Here is the call graph for this function:

Here is the caller graph for this function:

def site.addpackage (   sitedir,
  name,
  known_paths 
)
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 '.

Definition at line 129 of file site.py.

00129 
00130 def addpackage(sitedir, name, known_paths):
00131     """Process a .pth file within the site-packages directory:
00132        For each line in the file, either combine it with sitedir to a path
00133        and add that to known_paths, or execute it if it starts with 'import '.
00134     """
00135     if known_paths is None:
00136         _init_pathinfo()
00137         reset = 1
00138     else:
00139         reset = 0
00140     fullname = os.path.join(sitedir, name)
00141     try:
00142         f = open(fullname, "rU")
00143     except IOError:
00144         return
00145     with f:
00146         for n, line in enumerate(f):
00147             if line.startswith("#"):
00148                 continue
00149             try:
00150                 if line.startswith(("import ", "import\t")):
00151                     exec(line)
00152                     continue
00153                 line = line.rstrip()
00154                 dir, dircase = makepath(sitedir, line)
00155                 if not dircase in known_paths and os.path.exists(dir):
00156                     sys.path.append(dir)
00157                     known_paths.add(dircase)
00158             except Exception as err:
00159                 print("Error processing line {:d} of {}:\n".format(n+1, fullname),
00160                       file=sys.stderr)
00161                 for record in traceback.format_exception(*sys.exc_info()):
00162                     for line in record.splitlines():
00163                         print('  '+line, file=sys.stderr)
00164                 print("\nRemainder of file ignored", file=sys.stderr)
00165                 break
00166     if reset:
00167         known_paths = None
00168     return known_paths
00169 

Here is the call graph for this function:

Here is the caller graph for this function:

def site.addsitedir (   sitedir,
  known_paths = None 
)
Add 'sitedir' argument to sys.path if missing and handle .pth files in
'sitedir'

Definition at line 170 of file site.py.

00170 
00171 def addsitedir(sitedir, known_paths=None):
00172     """Add 'sitedir' argument to sys.path if missing and handle .pth files in
00173     'sitedir'"""
00174     if known_paths is None:
00175         known_paths = _init_pathinfo()
00176         reset = 1
00177     else:
00178         reset = 0
00179     sitedir, sitedircase = makepath(sitedir)
00180     if not sitedircase in known_paths:
00181         sys.path.append(sitedir)        # Add path component
00182     try:
00183         names = os.listdir(sitedir)
00184     except os.error:
00185         return
00186     names = [name for name in names if name.endswith(".pth")]
00187     for name in sorted(names):
00188         addpackage(sitedir, name, known_paths)
00189     if reset:
00190         known_paths = None
00191     return known_paths
00192 

Here is the call graph for this function:

Here is the caller graph for this function:

def site.addsitepackages (   known_paths)
Add site-packages (and possibly site-python) to sys.path

Definition at line 306 of file site.py.

00306 
00307 def addsitepackages(known_paths):
00308     """Add site-packages (and possibly site-python) to sys.path"""
00309     for sitedir in getsitepackages():
00310         if os.path.isdir(sitedir):
00311             addsitedir(sitedir, known_paths)
00312 
00313     return known_paths

Here is the call graph for this function:

Here is the caller graph for this function:

def site.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.

Definition at line 255 of file site.py.

00255 
00256 def addusersitepackages(known_paths):
00257     """Add a per user site-package to sys.path
00258 
00259     Each user has its own python directory with site-packages in the
00260     home directory.
00261     """
00262     # get the per user site-package path
00263     # this call will also make sure USER_BASE and USER_SITE are set
00264     user_site = getusersitepackages()
00265 
00266     if ENABLE_USER_SITE and os.path.isdir(user_site):
00267         addsitedir(user_site, known_paths)
00268     return known_paths

Here is the call graph for this function:

Here is the caller graph for this function:

def site.aliasmbcs ( )
On Windows, some default encodings are not provided by Python,
while they are always available as "mbcs" in each locale. Make
them usable by aliasing to "mbcs" in such a case.

Definition at line 462 of file site.py.

00462 
00463 def aliasmbcs():
00464     """On Windows, some default encodings are not provided by Python,
00465     while they are always available as "mbcs" in each locale. Make
00466     them usable by aliasing to "mbcs" in such a case."""
00467     if sys.platform == 'win32':
00468         import locale, codecs
00469         enc = locale.getdefaultlocale()[1]
00470         if enc.startswith('cp'):            # "cp***" ?
00471             try:
00472                 codecs.lookup(enc)
00473             except LookupError:
00474                 import encodings
00475                 encodings._cache[enc] = encodings._unknown
00476                 encodings.aliases.aliases[enc] = 'mbcs'
00477 

Here is the call graph for this function:

Here is the caller graph for this function:

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

Definition at line 193 of file site.py.

00193 
00194 def check_enableusersite():
00195     """Check if user site directory is safe for inclusion
00196 
00197     The function tests for the command line flag (including environment var),
00198     process uid/gid equal to effective uid/gid.
00199 
00200     None: Disabled for security reasons
00201     False: Disabled by user (command line option)
00202     True: Safe and enabled
00203     """
00204     if sys.flags.no_user_site:
00205         return False
00206 
00207     if hasattr(os, "getuid") and hasattr(os, "geteuid"):
00208         # check process uid == effective uid
00209         if os.geteuid() != os.getuid():
00210             return None
00211     if hasattr(os, "getgid") and hasattr(os, "getegid"):
00212         # check process gid == effective gid
00213         if os.getegid() != os.getgid():
00214             return None
00215 
00216     return True

Here is the caller graph for this function:

Run custom site specific code, if available.

Definition at line 478 of file site.py.

00478 
00479 def execsitecustomize():
00480     """Run custom site specific code, if available."""
00481     try:
00482         import sitecustomize
00483     except ImportError:
00484         pass
00485     except Exception as err:
00486         if os.environ.get("PYTHONVERBOSE"):
00487             sys.excepthook(*sys.exc_info())
00488         else:
00489             sys.stderr.write(
00490                 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
00491                 "%s: %s\n" %
00492                 (err.__class__.__name__, err))
00493 

Here is the caller graph for this function:

Run custom user specific code, if available.

Definition at line 494 of file site.py.

00494 
00495 def execusercustomize():
00496     """Run custom user specific code, if available."""
00497     try:
00498         import usercustomize
00499     except ImportError:
00500         pass
00501     except Exception as err:
00502         if os.environ.get("PYTHONVERBOSE"):
00503             sys.excepthook(*sys.exc_info())
00504         else:
00505             sys.stderr.write(
00506                 "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
00507                 "%s: %s\n" %
00508                 (err.__class__.__name__, err))
00509 

Here is the caller graph for this function:

Returns a list containing all global site-packages directories
(and possibly site-python).

For each directory present in the global ``PREFIXES``, this function
will find its `site-packages` subdirectory depending on the system
environment, and will return a list of full paths.

Definition at line 269 of file site.py.

00269 
00270 def getsitepackages():
00271     """Returns a list containing all global site-packages directories
00272     (and possibly site-python).
00273 
00274     For each directory present in the global ``PREFIXES``, this function
00275     will find its `site-packages` subdirectory depending on the system
00276     environment, and will return a list of full paths.
00277     """
00278     sitepackages = []
00279     seen = set()
00280 
00281     for prefix in PREFIXES:
00282         if not prefix or prefix in seen:
00283             continue
00284         seen.add(prefix)
00285 
00286         if sys.platform in ('os2emx', 'riscos'):
00287             sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
00288         elif os.sep == '/':
00289             sitepackages.append(os.path.join(prefix, "lib",
00290                                         "python" + sys.version[:3],
00291                                         "site-packages"))
00292             sitepackages.append(os.path.join(prefix, "lib", "site-python"))
00293         else:
00294             sitepackages.append(prefix)
00295             sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
00296         if sys.platform == "darwin":
00297             # for framework builds *only* we add the standard Apple
00298             # locations.
00299             from sysconfig import get_config_var
00300             framework = get_config_var("PYTHONFRAMEWORK")
00301             if framework:
00302                 sitepackages.append(
00303                         os.path.join("/Library", framework,
00304                             sys.version[:3], "site-packages"))
00305     return sitepackages

Here is the call graph for this function:

Here is the caller graph for this function:

Returns the `user base` directory path.

The `user base` directory can be used to store data. If the global
variable ``USER_BASE`` is not initialized yet, this function will also set
it.

Definition at line 217 of file site.py.

00217 
00218 def getuserbase():
00219     """Returns the `user base` directory path.
00220 
00221     The `user base` directory can be used to store data. If the global
00222     variable ``USER_BASE`` is not initialized yet, this function will also set
00223     it.
00224     """
00225     global USER_BASE
00226     if USER_BASE is not None:
00227         return USER_BASE
00228     from sysconfig import get_config_var
00229     USER_BASE = get_config_var('userbase')
00230     return USER_BASE

Here is the call graph for this function:

Here is the caller graph for this function:

Returns the user-specific site-packages directory path.

If the global variable ``USER_SITE`` is not initialized yet, this
function will also set it.

Definition at line 231 of file site.py.

00231 
00232 def getusersitepackages():
00233     """Returns the user-specific site-packages directory path.
00234 
00235     If the global variable ``USER_SITE`` is not initialized yet, this
00236     function will also set it.
00237     """
00238     global USER_SITE
00239     user_base = getuserbase() # this will also set USER_BASE
00240 
00241     if USER_SITE is not None:
00242         return USER_SITE
00243 
00244     from sysconfig import get_path
00245     import os
00246 
00247     if sys.platform == 'darwin':
00248         from sysconfig import get_config_var
00249         if get_config_var('PYTHONFRAMEWORK'):
00250             USER_SITE = get_path('purelib', 'osx_framework_user')
00251             return USER_SITE
00252 
00253     USER_SITE = get_path('purelib', '%s_user' % os.name)
00254     return USER_SITE

Here is the call graph for this function:

Here is the caller graph for this function:

def site.main ( void  )

Definition at line 510 of file site.py.

00510 
00511 def main():
00512     global ENABLE_USER_SITE
00513 
00514     abs_paths()
00515     known_paths = removeduppaths()
00516     if ENABLE_USER_SITE is None:
00517         ENABLE_USER_SITE = check_enableusersite()
00518     known_paths = addusersitepackages(known_paths)
00519     known_paths = addsitepackages(known_paths)
00520     if sys.platform == 'os2emx':
00521         setBEGINLIBPATH()
00522     setquit()
00523     setcopyright()
00524     sethelper()
00525     aliasmbcs()
00526     execsitecustomize()
00527     if ENABLE_USER_SITE:
00528         execusercustomize()
00529 
00530 main()

Here is the call graph for this function:

def site.makepath (   paths)

Definition at line 73 of file site.py.

00073 
00074 def makepath(*paths):
00075     dir = os.path.join(*paths)
00076     try:
00077         dir = os.path.abspath(dir)
00078     except OSError:
00079         pass
00080     return dir, os.path.normcase(dir)
00081 

Here is the caller graph for this function:

Remove duplicate entries from sys.path along with making them
absolute

Definition at line 97 of file site.py.

00097 
00098 def removeduppaths():
00099     """ Remove duplicate entries from sys.path along with making them
00100     absolute"""
00101     # This ensures that the initial path provided by the interpreter contains
00102     # only absolute pathnames, even if we're running from the build directory.
00103     L = []
00104     known_paths = set()
00105     for dir in sys.path:
00106         # Filter out duplicate paths (on case-insensitive file systems also
00107         # if they only differ in case); turn relative paths into absolute
00108         # paths.
00109         dir, dircase = makepath(dir)
00110         if not dircase in known_paths:
00111             L.append(dir)
00112             known_paths.add(dircase)
00113     sys.path[:] = L
00114     return known_paths
00115 

Here is the call graph for this function:

Here is the caller graph for this function:

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.
The library search path needs to be amended so these will be found
during module import.  Use BEGINLIBPATH so that these are at the start
of the library search path.

Definition at line 314 of file site.py.

00314 
00315 def setBEGINLIBPATH():
00316     """The OS/2 EMX port has optional extension modules that do double duty
00317     as DLLs (and must use the .DLL file extension) for other extensions.
00318     The library search path needs to be amended so these will be found
00319     during module import.  Use BEGINLIBPATH so that these are at the start
00320     of the library search path.
00321 
00322     """
00323     dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
00324     libpath = os.environ['BEGINLIBPATH'].split(';')
00325     if libpath[-1]:
00326         libpath.append(dllpath)
00327     else:
00328         libpath[-1] = dllpath
00329     os.environ['BEGINLIBPATH'] = ';'.join(libpath)
00330 

Here is the call graph for this function:

Here is the caller graph for this function:

Set 'copyright' and 'credits' in builtins

Definition at line 428 of file site.py.

00428 
00429 def setcopyright():
00430     """Set 'copyright' and 'credits' in builtins"""
00431     builtins.copyright = _Printer("copyright", sys.copyright)
00432     if sys.platform[:4] == 'java':
00433         builtins.credits = _Printer(
00434             "credits",
00435             "Jython is maintained by the Jython developers (www.jython.org).")
00436     else:
00437         builtins.credits = _Printer("credits", """\
00438     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
00439     for supporting Python development.  See www.python.org for more information.""")
00440     here = os.path.dirname(os.__file__)
00441     builtins.license = _Printer(
00442         "license", "See http://www.python.org/%.3s/license.html" % sys.version,
00443         ["LICENSE.txt", "LICENSE"],
00444         [os.path.join(here, os.pardir), here, os.curdir])
00445 

Here is the caller graph for this function:

def site.sethelper ( )

Definition at line 459 of file site.py.

00459 
00460 def sethelper():
00461     builtins.help = _Helper()

Here is the caller graph for this function:

def site.setquit ( )
Define new builtins 'quit' and 'exit'.

These are objects which make the interpreter exit when called.
The repr of each object contains a hint at how it works.

Definition at line 331 of file site.py.

00331 
00332 def setquit():
00333     """Define new builtins 'quit' and 'exit'.
00334 
00335     These are objects which make the interpreter exit when called.
00336     The repr of each object contains a hint at how it works.
00337 
00338     """
00339     if os.sep == ':':
00340         eof = 'Cmd-Q'
00341     elif os.sep == '\\':
00342         eof = 'Ctrl-Z plus Return'
00343     else:
00344         eof = 'Ctrl-D (i.e. EOF)'
00345 
00346     class Quitter(object):
00347         def __init__(self, name):
00348             self.name = name
00349         def __repr__(self):
00350             return 'Use %s() or %s to exit' % (self.name, eof)
00351         def __call__(self, code=None):
00352             # Shells like IDLE catch the SystemExit, but listen when their
00353             # stdin wrapper is closed.
00354             try:
00355                 fd = -1
00356                 if hasattr(sys.stdin, "fileno"):
00357                     fd = sys.stdin.fileno()
00358                 if fd != 0:
00359                     # Don't close stdin if it wraps fd 0
00360                     sys.stdin.close()
00361             except:
00362                 pass
00363             raise SystemExit(code)
00364     builtins.quit = Quitter('quit')
00365     builtins.exit = Quitter('exit')
00366 

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Definition at line 64 of file site.py.

Definition at line 347 of file site.py.

Definition at line 61 of file site.py.

Definition at line 70 of file site.py.

Definition at line 69 of file site.py.