Path: blob/master/venv/Lib/site-packages/pip/_internal/locations.py
811 views
"""Locations where we look for configs, install stuff, etc"""12# The following comment should be removed at some point in the future.3# mypy: strict-optional=False45from __future__ import absolute_import67import os8import os.path9import platform10import site11import sys12import sysconfig13from distutils import sysconfig as distutils_sysconfig14from distutils.command.install import SCHEME_KEYS # type: ignore15from distutils.command.install import install as distutils_install_command1617from pip._internal.models.scheme import Scheme18from pip._internal.utils import appdirs19from pip._internal.utils.compat import WINDOWS20from pip._internal.utils.typing import MYPY_CHECK_RUNNING, cast21from pip._internal.utils.virtualenv import running_under_virtualenv2223if MYPY_CHECK_RUNNING:24from typing import Dict, List, Optional, Union2526from distutils.cmd import Command as DistutilsCommand272829# Application Directories30USER_CACHE_DIR = appdirs.user_cache_dir("pip")313233def get_major_minor_version():34# type: () -> str35"""36Return the major-minor version of the current Python as a string, e.g.37"3.7" or "3.10".38"""39return '{}.{}'.format(*sys.version_info)404142def get_src_prefix():43# type: () -> str44if running_under_virtualenv():45src_prefix = os.path.join(sys.prefix, 'src')46else:47# FIXME: keep src in cwd for now (it is not a temporary folder)48try:49src_prefix = os.path.join(os.getcwd(), 'src')50except OSError:51# In case the current working directory has been renamed or deleted52sys.exit(53"The folder you are executing pip from can no longer be found."54)5556# under macOS + virtualenv sys.prefix is not properly resolved57# it is something like /path/to/python/bin/..58return os.path.abspath(src_prefix)596061# FIXME doesn't account for venv linked to global site-packages6263site_packages = sysconfig.get_path("purelib") # type: Optional[str]6465# This is because of a bug in PyPy's sysconfig module, see66# https://bitbucket.org/pypy/pypy/issues/2506/sysconfig-returns-incorrect-paths67# for more information.68if platform.python_implementation().lower() == "pypy":69site_packages = distutils_sysconfig.get_python_lib()70try:71# Use getusersitepackages if this is present, as it ensures that the72# value is initialised properly.73user_site = site.getusersitepackages()74except AttributeError:75user_site = site.USER_SITE7677if WINDOWS:78bin_py = os.path.join(sys.prefix, 'Scripts')79bin_user = os.path.join(user_site, 'Scripts')80# buildout uses 'bin' on Windows too?81if not os.path.exists(bin_py):82bin_py = os.path.join(sys.prefix, 'bin')83bin_user = os.path.join(user_site, 'bin')84else:85bin_py = os.path.join(sys.prefix, 'bin')86bin_user = os.path.join(user_site, 'bin')8788# Forcing to use /usr/local/bin for standard macOS framework installs89# Also log to ~/Library/Logs/ for use with the Console.app log viewer90if sys.platform[:6] == 'darwin' and sys.prefix[:16] == '/System/Library/':91bin_py = '/usr/local/bin'929394def distutils_scheme(95dist_name, user=False, home=None, root=None, isolated=False, prefix=None96):97# type:(str, bool, str, str, bool, str) -> Dict[str, str]98"""99Return a distutils install scheme100"""101from distutils.dist import Distribution102103dist_args = {'name': dist_name} # type: Dict[str, Union[str, List[str]]]104if isolated:105dist_args["script_args"] = ["--no-user-cfg"]106107d = Distribution(dist_args)108d.parse_config_files()109obj = None # type: Optional[DistutilsCommand]110obj = d.get_command_obj('install', create=True)111assert obj is not None112i = cast(distutils_install_command, obj)113# NOTE: setting user or home has the side-effect of creating the home dir114# or user base for installations during finalize_options()115# ideally, we'd prefer a scheme class that has no side-effects.116assert not (user and prefix), "user={} prefix={}".format(user, prefix)117assert not (home and prefix), "home={} prefix={}".format(home, prefix)118i.user = user or i.user119if user or home:120i.prefix = ""121i.prefix = prefix or i.prefix122i.home = home or i.home123i.root = root or i.root124i.finalize_options()125126scheme = {}127for key in SCHEME_KEYS:128scheme[key] = getattr(i, 'install_' + key)129130# install_lib specified in setup.cfg should install *everything*131# into there (i.e. it takes precedence over both purelib and132# platlib). Note, i.install_lib is *always* set after133# finalize_options(); we only want to override here if the user134# has explicitly requested it hence going back to the config135if 'install_lib' in d.get_option_dict('install'):136scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib))137138if running_under_virtualenv():139scheme['headers'] = os.path.join(140sys.prefix,141'include',142'site',143'python{}'.format(get_major_minor_version()),144dist_name,145)146147if root is not None:148path_no_drive = os.path.splitdrive(149os.path.abspath(scheme["headers"]))[1]150scheme["headers"] = os.path.join(151root,152path_no_drive[1:],153)154155return scheme156157158def get_scheme(159dist_name, # type: str160user=False, # type: bool161home=None, # type: Optional[str]162root=None, # type: Optional[str]163isolated=False, # type: bool164prefix=None, # type: Optional[str]165):166# type: (...) -> Scheme167"""168Get the "scheme" corresponding to the input parameters. The distutils169documentation provides the context for the available schemes:170https://docs.python.org/3/install/index.html#alternate-installation171172:param dist_name: the name of the package to retrieve the scheme for, used173in the headers scheme path174:param user: indicates to use the "user" scheme175:param home: indicates to use the "home" scheme and provides the base176directory for the same177:param root: root under which other directories are re-based178:param isolated: equivalent to --no-user-cfg, i.e. do not consider179~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for180scheme paths181:param prefix: indicates to use the "prefix" scheme and provides the182base directory for the same183"""184scheme = distutils_scheme(185dist_name, user, home, root, isolated, prefix186)187return Scheme(188platlib=scheme["platlib"],189purelib=scheme["purelib"],190headers=scheme["headers"],191scripts=scheme["scripts"],192data=scheme["data"],193)194195196