summaryrefslogtreecommitdiff
path: root/Lib/site.py
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/site.py')
-rw-r--r--Lib/site.py176
1 files changed, 81 insertions, 95 deletions
diff --git a/Lib/site.py b/Lib/site.py
index a0489fa461..a2c0becbc1 100644
--- a/Lib/site.py
+++ b/Lib/site.py
@@ -62,7 +62,10 @@ PREFIXES = [sys.prefix, sys.exec_prefix]
# Enable per user site-packages directory
# set it to False to disable the feature or True to force the feature
ENABLE_USER_SITE = None
+
# for distutils.commands.install
+# These values are initialized by the getuserbase() and getusersitepackages()
+# functions, through the main() function when Python starts.
USER_SITE = None
USER_BASE = None
@@ -76,8 +79,8 @@ def makepath(*paths):
return dir, os.path.normcase(dir)
-def abs__file__():
- """Set all module' __file__ attribute to an absolute path"""
+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__
@@ -85,6 +88,10 @@ def abs__file__():
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():
@@ -105,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 distutils.util 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[-1]), s)
- sys.path.append(s)
-
def _init_pathinfo():
"""Return a set containing all existing directory entries from sys.path"""
@@ -219,86 +214,103 @@ def check_enableusersite():
return True
+def getuserbase():
+ """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.
+ """
+ global USER_BASE
+ if USER_BASE is not None:
+ return USER_BASE
+ from sysconfig import get_config_var
+ USER_BASE = get_config_var('userbase')
+ return USER_BASE
+
+def getusersitepackages():
+ """Returns the user-specific site-packages directory path.
+
+ If the global variable ``USER_SITE`` is not initialized yet, this
+ function will also set it.
+ """
+ global USER_SITE
+ user_base = getuserbase() # this will also set USER_BASE
+
+ if USER_SITE is not None:
+ return USER_SITE
+
+ from sysconfig import get_path
+ import os
+
+ if sys.platform == 'darwin':
+ from sysconfig import get_config_var
+ if get_config_var('PYTHONFRAMEWORK'):
+ USER_SITE = get_path('purelib', 'osx_framework_user')
+ return USER_SITE
+
+ USER_SITE = get_path('purelib', '%s_user' % os.name)
+ return USER_SITE
def 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.
-
- USER_BASE is the root directory for all Python versions
-
- USER_SITE is the user specific site-packages directory
-
- USER_SITE/.. can be used for data.
"""
- global USER_BASE, USER_SITE, ENABLE_USER_SITE
- env_base = os.environ.get("PYTHONUSERBASE", None)
-
- def joinuser(*args):
- return os.path.expanduser(os.path.join(*args))
-
- #if sys.platform in ('os2emx', 'riscos'):
- # # Don't know what to put here
- # USER_BASE = ''
- # USER_SITE = ''
- if os.name == "nt":
- base = os.environ.get("APPDATA") or "~"
- USER_BASE = env_base if env_base else joinuser(base, "Python")
- USER_SITE = os.path.join(USER_BASE,
- "Python" + sys.version[0] + sys.version[2],
- "site-packages")
- else:
- USER_BASE = env_base if env_base else joinuser("~", ".local")
- USER_SITE = os.path.join(USER_BASE, "lib",
- "python" + sys.version[:3],
- "site-packages")
+ # get the per user site-package path
+ # this call will also make sure USER_BASE and USER_SITE are set
+ user_site = getusersitepackages()
- if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
- addsitedir(USER_SITE, known_paths)
+ if ENABLE_USER_SITE and os.path.isdir(user_site):
+ addsitedir(user_site, known_paths)
return known_paths
+def getsitepackages():
+ """Returns a list containing all global site-packages directories
+ (and possibly site-python).
-def addsitepackages(known_paths):
- """Add site-packages (and possibly site-python) to sys.path"""
- sitedirs = []
- seen = []
+ 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.
+ """
+ sitepackages = []
+ seen = set()
for prefix in PREFIXES:
if not prefix or prefix in seen:
continue
- seen.append(prefix)
+ seen.add(prefix)
if sys.platform in ('os2emx', 'riscos'):
- sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
+ sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
elif os.sep == '/':
- sitedirs.append(os.path.join(prefix, "lib",
+ sitepackages.append(os.path.join(prefix, "lib",
"python" + sys.version[:3],
"site-packages"))
- sitedirs.append(os.path.join(prefix, "lib", "site-python"))
+ sitepackages.append(os.path.join(prefix, "lib", "site-python"))
else:
- sitedirs.append(prefix)
- sitedirs.append(os.path.join(prefix, "lib", "site-packages"))
-
+ sitepackages.append(prefix)
+ sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
if sys.platform == "darwin":
# for framework builds *only* we add the standard Apple
# locations.
- if 'Python.framework' in prefix:
- sitedirs.append(
- os.path.expanduser(
- os.path.join("~", "Library", "Python",
- sys.version[:3], "site-packages")))
- sitedirs.append(
- os.path.join("/Library", "Python",
+ from sysconfig import get_config_var
+ framework = get_config_var("PYTHONFRAMEWORK")
+ if framework:
+ sitepackages.append(
+ os.path.join("/Library", framework,
sys.version[:3], "site-packages"))
+ return sitepackages
- for sitedir in sitedirs:
+def addsitepackages(known_paths):
+ """Add site-packages (and possibly site-python) to sys.path"""
+ for sitedir in getsitepackages():
if os.path.isdir(sitedir):
addsitedir(sitedir, known_paths)
return known_paths
-
def setBEGINLIBPATH():
"""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.
@@ -317,8 +329,10 @@ def setBEGINLIBPATH():
def setquit():
- """Define new built-ins 'quit' and 'exit'.
- These are simply strings that display a hint on how to exit.
+ """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.
"""
if os.sep == ':':
@@ -430,7 +444,7 @@ def setcopyright():
class _Helper(object):
- """Define the built-in 'help'.
+ """Define the builtin 'help'.
This is a wrapper around pydoc.help (with a twist).
"""
@@ -460,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."""
@@ -515,11 +510,8 @@ def execusercustomize():
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)
@@ -530,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()