From a721c29b8c75d7991a413d46703dbe8ae9383773 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miro=20Hron=C4=8Dok?= Date: Tue, 10 Mar 2020 22:16:28 +0100 Subject: [PATCH] bpo-38662: ensurepip invokes pip via runpy (GH-18901) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ensurepip module now invokes pip via the runpy module. Hence it is no longer tightly coupled with the internal API of the bundled pip version, allowing easier updates to a newer pip version both internally and for distributors. This way, any changes to the internal pip API won't mean ensurepip needs to be changed as well. Also, distributors can update their pip wheels independent on CPython release schedule. Co-Authored-By: Pradyun Gedam Co-Authored-By: Miro Hrončok (cherry picked from commit 88f82b2b9ea3514359cb6e3218121f75334063ac) Co-authored-by: Miro Hrončok --- Lib/ensurepip/__init__.py | 16 +++++++++++++--- .../2020-03-10-15-32-31.bpo-38662.o1DMXj.rst | 4 ++++ 2 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2020-03-10-15-32-31.bpo-38662.o1DMXj.rst diff --git a/Lib/ensurepip/__init__.py b/Lib/ensurepip/__init__.py index 7a0d3ee0db946f..948f34092435a5 100644 --- a/Lib/ensurepip/__init__.py +++ b/Lib/ensurepip/__init__.py @@ -2,6 +2,7 @@ import os.path import pkgutil import sys +import runpy import tempfile @@ -23,9 +24,18 @@ def _run_pip(args, additional_paths=None): if additional_paths is not None: sys.path = additional_paths + sys.path - # Install the bundled software - import pip._internal - return pip._internal.main(args) + # Invoke pip as if it's the main module, and catch the exit. + backup_argv = sys.argv[:] + sys.argv[1:] = args + try: + # run_module() alters sys.modules and sys.argv, but restores them at exit + runpy.run_module("pip", run_name="__main__", alter_sys=True) + except SystemExit as exc: + return exc.code + finally: + sys.argv[:] = backup_argv + + raise SystemError("pip did not exit, this should never happen") def version(): diff --git a/Misc/NEWS.d/next/Library/2020-03-10-15-32-31.bpo-38662.o1DMXj.rst b/Misc/NEWS.d/next/Library/2020-03-10-15-32-31.bpo-38662.o1DMXj.rst new file mode 100644 index 00000000000000..241b2a6272ad60 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-03-10-15-32-31.bpo-38662.o1DMXj.rst @@ -0,0 +1,4 @@ +The ``ensurepip`` module now invokes ``pip`` via the ``runpy`` module. +Hence it is no longer tightly coupled with the internal API of the bundled +``pip`` version, allowing easier updates to a newer ``pip`` version both +internally and for distributors.