__init__.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import os
  2. import os.path
  3. import sys
  4. import runpy
  5. import tempfile
  6. import subprocess
  7. from importlib import resources
  8. from . import _bundled
  9. __all__ = ["version", "bootstrap"]
  10. _SETUPTOOLS_VERSION = "58.1.0"
  11. _PIP_VERSION = "22.0.4"
  12. _PROJECTS = [
  13. ("setuptools", _SETUPTOOLS_VERSION, "py3"),
  14. ("pip", _PIP_VERSION, "py3"),
  15. ]
  16. def _run_pip(args, additional_paths=None):
  17. # Run the bootstraping in a subprocess to avoid leaking any state that happens
  18. # after pip has executed. Particulary, this avoids the case when pip holds onto
  19. # the files in *additional_paths*, preventing us to remove them at the end of the
  20. # invocation.
  21. code = f"""
  22. import runpy
  23. import sys
  24. sys.path = {additional_paths or []} + sys.path
  25. sys.argv[1:] = {args}
  26. runpy.run_module("pip", run_name="__main__", alter_sys=True)
  27. """
  28. return subprocess.run([sys.executable, "-c", code], check=True).returncode
  29. def version():
  30. """
  31. Returns a string specifying the bundled version of pip.
  32. """
  33. return _PIP_VERSION
  34. def _disable_pip_configuration_settings():
  35. # We deliberately ignore all pip environment variables
  36. # when invoking pip
  37. # See http://bugs.python.org/issue19734 for details
  38. keys_to_remove = [k for k in os.environ if k.startswith("PIP_")]
  39. for k in keys_to_remove:
  40. del os.environ[k]
  41. # We also ignore the settings in the default pip configuration file
  42. # See http://bugs.python.org/issue20053 for details
  43. os.environ['PIP_CONFIG_FILE'] = os.devnull
  44. def bootstrap(*, root=None, upgrade=False, user=False,
  45. altinstall=False, default_pip=False,
  46. verbosity=0):
  47. """
  48. Bootstrap pip into the current Python installation (or the given root
  49. directory).
  50. Note that calling this function will alter both sys.path and os.environ.
  51. """
  52. # Discard the return value
  53. _bootstrap(root=root, upgrade=upgrade, user=user,
  54. altinstall=altinstall, default_pip=default_pip,
  55. verbosity=verbosity)
  56. def _bootstrap(*, root=None, upgrade=False, user=False,
  57. altinstall=False, default_pip=False,
  58. verbosity=0):
  59. """
  60. Bootstrap pip into the current Python installation (or the given root
  61. directory). Returns pip command status code.
  62. Note that calling this function will alter both sys.path and os.environ.
  63. """
  64. if altinstall and default_pip:
  65. raise ValueError("Cannot use altinstall and default_pip together")
  66. sys.audit("ensurepip.bootstrap", root)
  67. _disable_pip_configuration_settings()
  68. # By default, installing pip and setuptools installs all of the
  69. # following scripts (X.Y == running Python version):
  70. #
  71. # pip, pipX, pipX.Y, easy_install, easy_install-X.Y
  72. #
  73. # pip 1.5+ allows ensurepip to request that some of those be left out
  74. if altinstall:
  75. # omit pip, pipX and easy_install
  76. os.environ["ENSUREPIP_OPTIONS"] = "altinstall"
  77. elif not default_pip:
  78. # omit pip and easy_install
  79. os.environ["ENSUREPIP_OPTIONS"] = "install"
  80. with tempfile.TemporaryDirectory() as tmpdir:
  81. # Put our bundled wheels into a temporary directory and construct the
  82. # additional paths that need added to sys.path
  83. additional_paths = []
  84. for project, version, py_tag in _PROJECTS:
  85. wheel_name = "{}-{}-{}-none-any.whl".format(project, version, py_tag)
  86. whl = resources.read_binary(
  87. _bundled,
  88. wheel_name,
  89. )
  90. with open(os.path.join(tmpdir, wheel_name), "wb") as fp:
  91. fp.write(whl)
  92. additional_paths.append(os.path.join(tmpdir, wheel_name))
  93. # Construct the arguments to be passed to the pip command
  94. args = ["install", "--no-cache-dir", "--no-index", "--find-links", tmpdir]
  95. if root:
  96. args += ["--root", root]
  97. if upgrade:
  98. args += ["--upgrade"]
  99. if user:
  100. args += ["--user"]
  101. if verbosity:
  102. args += ["-" + "v" * verbosity]
  103. return _run_pip(args + [p[0] for p in _PROJECTS], additional_paths)
  104. def _uninstall_helper(*, verbosity=0):
  105. """Helper to support a clean default uninstall process on Windows
  106. Note that calling this function may alter os.environ.
  107. """
  108. # Nothing to do if pip was never installed, or has been removed
  109. try:
  110. import pip
  111. except ImportError:
  112. return
  113. # If the pip version doesn't match the bundled one, leave it alone
  114. if pip.__version__ != _PIP_VERSION:
  115. msg = ("ensurepip will only uninstall a matching version "
  116. "({!r} installed, {!r} bundled)")
  117. print(msg.format(pip.__version__, _PIP_VERSION), file=sys.stderr)
  118. return
  119. _disable_pip_configuration_settings()
  120. # Construct the arguments to be passed to the pip command
  121. args = ["uninstall", "-y", "--disable-pip-version-check"]
  122. if verbosity:
  123. args += ["-" + "v" * verbosity]
  124. return _run_pip(args + [p[0] for p in reversed(_PROJECTS)])
  125. def _main(argv=None):
  126. import argparse
  127. parser = argparse.ArgumentParser(prog="python -m ensurepip")
  128. parser.add_argument(
  129. "--version",
  130. action="version",
  131. version="pip {}".format(version()),
  132. help="Show the version of pip that is bundled with this Python.",
  133. )
  134. parser.add_argument(
  135. "-v", "--verbose",
  136. action="count",
  137. default=0,
  138. dest="verbosity",
  139. help=("Give more output. Option is additive, and can be used up to 3 "
  140. "times."),
  141. )
  142. parser.add_argument(
  143. "-U", "--upgrade",
  144. action="store_true",
  145. default=False,
  146. help="Upgrade pip and dependencies, even if already installed.",
  147. )
  148. parser.add_argument(
  149. "--user",
  150. action="store_true",
  151. default=False,
  152. help="Install using the user scheme.",
  153. )
  154. parser.add_argument(
  155. "--root",
  156. default=None,
  157. help="Install everything relative to this alternate root directory.",
  158. )
  159. parser.add_argument(
  160. "--altinstall",
  161. action="store_true",
  162. default=False,
  163. help=("Make an alternate install, installing only the X.Y versioned "
  164. "scripts (Default: pipX, pipX.Y, easy_install-X.Y)."),
  165. )
  166. parser.add_argument(
  167. "--default-pip",
  168. action="store_true",
  169. default=False,
  170. help=("Make a default pip install, installing the unqualified pip "
  171. "and easy_install in addition to the versioned scripts."),
  172. )
  173. args = parser.parse_args(argv)
  174. return _bootstrap(
  175. root=args.root,
  176. upgrade=args.upgrade,
  177. user=args.user,
  178. verbosity=args.verbosity,
  179. altinstall=args.altinstall,
  180. default_pip=args.default_pip,
  181. )