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