__init__.py 6.3 KB

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