__init__.py 6.3 KB

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