Debian Codegraph @

Lib/ensurepip/__init__.py

raw ◀ ▶
1 Debian patch touch this file
1 import os
2 import subprocess
3 import sys
4 import sysconfig
5 import tempfile
6 from contextlib import nullcontext
7 from importlib import resources
8 from pathlib import Path
9 from shutil import copy2
10
•11 def _ensurepip_is_disabled_in_debian_for_system():
12 # Detect if ensurepip is being executed inside of a python-virtualenv
13 # environment and return early if so.
14 if hasattr(sys, 'real_prefix'):
15 return
16
17 # Detect if ensurepip is being executed inside of a stdlib venv
18 # environment and return early if so.
19 if sys.prefix != getattr(sys, "base_prefix", sys.prefix):
20 return
21
22 # If we've gotten here, then we are running inside of the system Python
23 # and we don't want to use ensurepip to install into the system Python
24 # so instead we'll redirect the user to using dpkg and apt-get.
25 print('''\
26 ensurepip is disabled in Debian/Ubuntu for the system python.
27
28 Python modules for the system python are usually handled by dpkg and apt-get.
29
30 apt install python3-<module name>
31
32 Install the python3-pip package to use pip itself. Using pip together
33 with the system python might have unexpected results for any system installed
34 module, so use it on your own risk, or make sure to only use it in virtual
35 environments.
36 ''')
37 sys.exit(1)
38
39
40 __all__ = ["version", "bootstrap"]
41 _PIP_VERSION = "26.1.2"
42
43 # Directory of system wheel packages. Some Linux distribution packaging
44 # policies recommend against bundling dependencies. For example, Fedora
45 # installs wheel packages in the /usr/share/python-wheels/ directory and don't
46 # install the ensurepip._bundled package.
47 _pkg_dir = sysconfig.get_config_var('WHEEL_PKG_DIR')
48 if _pkg_dir:
49 _WHEEL_PKG_DIR = Path(_pkg_dir).resolve()
50 else:
51 _WHEEL_PKG_DIR = None
52
53
54 def _find_wheel_pkg_dir_pip():
55 if _WHEEL_PKG_DIR is None:
56 # NOTE: The compile-time `WHEEL_PKG_DIR` is unset so there is no place
57 # NOTE: for looking up the wheels.
58 return None
59
60 dist_matching_wheels = _WHEEL_PKG_DIR.glob('pip-*.whl')
61 try:
62 last_matching_dist_wheel = sorted(dist_matching_wheels)[-1]
63 except IndexError:
64 # NOTE: `WHEEL_PKG_DIR` does not contain any wheel files for `pip`.
65 return None
66
67 return nullcontext(last_matching_dist_wheel)
68
69
70 def _get_pip_whl_path_ctx():
71 # Prefer pip from the wheel package directory, if present.
72 if (alternative_pip_wheel_path := _find_wheel_pkg_dir_pip()) is not None:
73 return alternative_pip_wheel_path
74
75 return resources.as_file(
76 resources.files('ensurepip')
77 / '_bundled'
78 / f'pip-{_PIP_VERSION}-py3-none-any.whl'
79 )
80
81
82 def _get_pip_version():
83 with _get_pip_whl_path_ctx() as bundled_wheel_path:
84 wheel_name = bundled_wheel_path.name
85 return (
86 # Extract '21.2.4' from 'pip-21.2.4-py3-none-any.whl'
87 wheel_name.
88 removeprefix('pip-').
89 partition('-')[0]
90 )
91
92
93 def _run_pip(args, additional_paths=None):
94 # Run the bootstrapping in a subprocess to avoid leaking any state that happens
95 # after pip has executed. Particularly, this avoids the case when pip holds onto
96 # the files in *additional_paths*, preventing us to remove them at the end of the
97 # invocation.
98 code = f"""
99 import runpy
100 import sys
101 sys.path = {additional_paths or []} + sys.path
102 sys.argv[1:] = {args}
103 runpy.run_module("pip", run_name="__main__", alter_sys=True)
104 """
105
106 cmd = [
107 sys.executable,
108 '-W',
109 'ignore::DeprecationWarning',
110 '-c',
111 code,
112 ]
113 if sys.flags.isolated:
114 # run code in isolated mode if currently running isolated
115 cmd.insert(1, '-I')
116 return subprocess.run(cmd, check=True).returncode
117
118
119 def version():
120 """
121 Returns a string specifying the bundled version of pip.
122 """
123 return _get_pip_version()
124
125
126 def _disable_pip_configuration_settings():
127 # We deliberately ignore all pip environment variables
128 # when invoking pip
129 # See http://bugs.python.org/issue19734 for details
130 keys_to_remove = [k for k in os.environ if k.startswith("PIP_")]
131 for k in keys_to_remove:
132 del os.environ[k]
133 # We also ignore the settings in the default pip configuration file
134 # See http://bugs.python.org/issue20053 for details
135 os.environ['PIP_CONFIG_FILE'] = os.devnull
136
137
138 def bootstrap(*, root=None, upgrade=False, user=False,
139 altinstall=False, default_pip=False,
140 verbosity=0):
141 """
142 Bootstrap pip into the current Python installation (or the given root
143 directory).
144
145 Note that calling this function will alter both sys.path and os.environ.
146 """
147 # Discard the return value
148 _bootstrap(root=root, upgrade=upgrade, user=user,
149 altinstall=altinstall, default_pip=default_pip,
150 verbosity=verbosity)
151
152
153 def _bootstrap(*, root=None, upgrade=False, user=False,
154 altinstall=False, default_pip=False,
155 verbosity=0):
156 """
157 Bootstrap pip into the current Python installation (or the given root
158 directory). Returns pip command status code.
159
160 Note that calling this function will alter both sys.path and os.environ.
161 """
•162
163 # Ensure that we are only running this inside of a virtual environment
164 # of some kind.
165 _ensurepip_is_disabled_in_debian_for_system()
166
167 if altinstall and default_pip:
168 raise ValueError("Cannot use altinstall and default_pip together")
169
170 sys.audit("ensurepip.bootstrap", root)
171
172 _disable_pip_configuration_settings()
173
174 # By default, installing pip installs all of the
175 # following scripts (X.Y == running Python version):
176 #
177 # pip, pipX, pipX.Y
178 #
179 # pip 1.5+ allows ensurepip to request that some of those be left out
180 if altinstall:
181 # omit pip, pipX
182 os.environ["ENSUREPIP_OPTIONS"] = "altinstall"
183 elif not default_pip:
184 # omit pip
185 os.environ["ENSUREPIP_OPTIONS"] = "install"
186
187 with tempfile.TemporaryDirectory() as tmpdir:
188 # Put our bundled wheels into a temporary directory and construct the
189 # additional paths that need added to sys.path
190 tmpdir_path = Path(tmpdir)
191 with _get_pip_whl_path_ctx() as bundled_wheel_path:
192 tmp_wheel_path = tmpdir_path / bundled_wheel_path.name
193 copy2(bundled_wheel_path, tmp_wheel_path)
194
195 # Construct the arguments to be passed to the pip command
196 args = ["install", "--no-cache-dir", "--no-index", "--find-links", tmpdir]
197 if root:
198 args += ["--root", root]
199 if upgrade:
200 args += ["--upgrade"]
201 if user:
202 args += ["--user"]
203 if verbosity:
204 args += ["-" + "v" * verbosity]
205
206 return _run_pip([*args, "pip"], [os.fsdecode(tmp_wheel_path)])
207
208
209 def _uninstall_helper(*, verbosity=0):
210 """Helper to support a clean default uninstall process on Windows
211
212 Note that calling this function may alter os.environ.
213 """
214 # Nothing to do if pip was never installed, or has been removed
215 try:
216 import pip
217 except ImportError:
218 return
219
220 # If the installed pip version doesn't match the available one,
221 # leave it alone
222 available_version = version()
223 if pip.__version__ != available_version:
224 print(f"ensurepip will only uninstall a matching version "
225 f"({pip.__version__!r} installed, "
226 f"{available_version!r} available)",
227 file=sys.stderr)
228 return
229
230 _disable_pip_configuration_settings()
231
232 # Construct the arguments to be passed to the pip command
233 args = ["uninstall", "-y", "--disable-pip-version-check"]
234 if verbosity:
235 args += ["-" + "v" * verbosity]
236
237 return _run_pip([*args, "pip"])
238
239
240 def _main(argv=None):
241 import argparse
242 parser = argparse.ArgumentParser(color=True)
243 parser.add_argument(
244 "--version",
245 action="version",
246 version="pip {}".format(version()),
247 help="Show the version of pip that is bundled with this Python.",
248 )
249 parser.add_argument(
250 "-v", "--verbose",
251 action="count",
252 default=0,
253 dest="verbosity",
254 help=("Give more output. Option is additive, and can be used up to 3 "
255 "times."),
256 )
257 parser.add_argument(
258 "-U", "--upgrade",
259 action="store_true",
260 default=False,
261 help="Upgrade pip and dependencies, even if already installed.",
262 )
263 parser.add_argument(
264 "--user",
265 action="store_true",
266 default=False,
267 help="Install using the user scheme.",
268 )
269 parser.add_argument(
270 "--root",
271 default=None,
272 help="Install everything relative to this alternate root directory.",
273 )
274 parser.add_argument(
275 "--altinstall",
276 action="store_true",
277 default=False,
278 help=("Make an alternate install, installing only the X.Y versioned "
279 "scripts (Default: pipX, pipX.Y)."),
280 )
281 parser.add_argument(
282 "--default-pip",
283 action="store_true",
284 default=False,
285 help=("Make a default pip install, installing the unqualified pip "
286 "in addition to the versioned scripts."),
287 )
288
289 args = parser.parse_args(argv)
290
291 return _bootstrap(
292 root=args.root,
293 upgrade=args.upgrade,
294 user=args.user,
295 verbosity=args.verbosity,
296 altinstall=args.altinstall,
297 default_pip=args.default_pip,
298 )