Debian Codegraph @

src/python_interpreter/mod.rs

raw
1 pub use self::config::InterpreterConfig;
2 use crate::auditwheel::PlatformTag;
3 use crate::{BridgeModel, BuildContext, Target};
4 use anyhow::{bail, ensure, format_err, Context, Result};
5 use pep440_rs::{Version, VersionSpecifiers};
6 use regex::Regex;
7 use serde::Deserialize;
8 use std::collections::HashSet;
9 use std::fmt;
10 use std::io::{self, Write};
11 use std::ops::Deref;
12 use std::path::{Path, PathBuf};
13 use std::process::{Command, Stdio};
14 use std::str::{self, FromStr};
15 use tracing::{debug, instrument};
16
17 mod config;
18
19 /// This snippets will give us information about the python interpreter's
20 /// version and abi as json through stdout
21 const GET_INTERPRETER_METADATA: &str = include_str!("get_interpreter_metadata.py");
22 pub const MINIMUM_PYTHON_MINOR: usize = 7;
23 pub const MINIMUM_PYPY_MINOR: usize = 8;
24 /// Be liberal here to include preview versions
25 pub const MAXIMUM_PYTHON_MINOR: usize = 13;
26 pub const MAXIMUM_PYPY_MINOR: usize = 11;
27
28 /// Identifies conditions where we do not want to build wheels
29 fn windows_interpreter_no_build(
30 major: usize,
31 minor: usize,
32 target_width: usize,
33 pointer_width: usize,
34 min_python_minor: usize,
35 requires_python: Option<&VersionSpecifiers>,
36 ) -> bool {
37 // Only python 3 with supported major versions
38 if major != 3 || minor < min_python_minor {
39 return true;
40 }
41
42 // From requires-python in pyproject.toml
43 if let Some(requires_python) = requires_python {
44 if !requires_python.contains(&Version::new([major as u64, minor as u64])) {
45 return true;
46 }
47 }
48
49 // There can be 32-bit installations on a 64-bit machine, but we can't link
50 // those for 64-bit targets
51 if pointer_width != target_width {
52 eprintln!(
53 "👽 {major}.{minor} is installed as {pointer_width}-bit, while the target is {target_width}-bit. Skipping."
54 );
55 return true;
56 }
57 false
58 }
59
60 /// On windows regular Python installs are supported along with environments
61 /// being managed by `conda`.
62 ///
63 /// We can't use the linux trick with trying different binary names since on
64 /// windows the binary is always called "python.exe". However, whether dealing
65 /// with regular Python installs or `conda` environments there are tools we can
66 /// use to query the information regarding installed interpreters.
67 ///
68 /// Regular Python installs downloaded from Python.org will include the python
69 /// launcher by default. We can use the launcher to find the information we need
70 /// for each installed interpreter using `py -0` which produces something like
71 /// the following output (the path can by determined using `sys.executable`):
72 ///
73 /// ```bash
74 /// Installed Pythons found by py Launcher for Windows
75 /// -3.7-64 *
76 /// -3.6-32
77 /// ```
78 ///
79 /// When using `conda` we can use the `conda info -e` command to retrieve information
80 /// regarding the installed interpreters being managed by `conda`. This is an example
81 /// of the output expected:
82 ///
83 /// ```bash
84 /// # conda environments:
85 /// #
86 /// base C:\Users\<user-name>\Anaconda3
87 /// foo1 * C:\Users\<user-name>\Anaconda3\envs\foo1
88 /// foo2 * C:\Users\<user-name>\Anaconda3\envs\foo2
89 /// ```
90 ///
91 /// The information required can either by obtained by parsing this output directly or
92 /// by invoking the interpreters to obtain the information.
93 ///
94 /// As well as the version numbers, etc. of the interpreters we also have to find the
95 /// pointer width to make sure that the pointer width (32-bit or 64-bit) matches across
96 /// platforms.
97 fn find_all_windows(
98 target: &Target,
99 bridge: &BridgeModel,
100 requires_python: Option<&VersionSpecifiers>,
101 ) -> Result<Vec<String>> {
102 let min_python_minor = bridge.minimal_python_minor_version();
103 let code = "import sys; print(sys.executable or '')";
104 let mut interpreter = vec![];
105 let mut versions_found = HashSet::new();
106
107 // If Python is installed from Python.org it should include the "python launcher"
108 // which is used to find the installed interpreters
109 let execution = Command::new("cmd")
110 .arg("/c")
111 .arg("py")
112 .arg("--list-paths")
113 .output();
114 if let Ok(output) = execution {
115 // x86_64: ' -3.10-64 * C:\Users\xxx\AppData\Local\Programs\Python\Python310\python.exe'
116 // x86_64: ' -3.11 * C:\Users\xxx\AppData\Local\Programs\Python\Python310\python.exe'
117 // arm64: ' -V:3.11-arm64 * C:\Users\xxx\AppData\Local\Programs\Python\Python311-arm64\python.exe
118 let expr = Regex::new(r" -(V:)?(\d).(\d+)-?(arm)?(\d*)\s*\*?\s*(.*)?").unwrap();
119 let stdout = str::from_utf8(&output.stdout).unwrap();
120 for line in stdout.lines() {
121 if let Some(capture) = expr.captures(line) {
122 let major = capture
123 .get(2)
124 .unwrap()
125 .as_str()
126 .parse::<usize>()
127 .context("Expected a digit for major version")?;
128 let minor = capture
129 .get(3)
130 .unwrap()
131 .as_str()
132 .parse::<usize>()
133 .context("Expected a digit for minor version")?;
134 if !versions_found.contains(&(major, minor)) {
135 let pointer_width = capture
136 .get(5)
137 .map(|m| m.as_str())
138 .filter(|m| !m.is_empty())
139 .unwrap_or("64")
140 .parse::<usize>()
141 .context("Expected a digit for pointer width")?;
142
143 if windows_interpreter_no_build(
144 major,
145 minor,
146 target.pointer_width(),
147 pointer_width,
148 min_python_minor,
149 requires_python,
150 ) {
151 continue;
152 }
153
154 let executable = capture.get(6).unwrap().as_str();
155 let output = Command::new(executable).args(["-c", code]).output();
156 let output = match output {
157 Ok(output) => output,
158 Err(err) => {
159 eprintln!(
160 "⚠️ Warning: failed to determine the path to python for `{executable}`: {err}"
161 );
162 continue;
163 }
164 };
165 let path = str::from_utf8(&output.stdout).unwrap().trim();
166 if !output.status.success() || path.trim().is_empty() {
167 eprintln!(
168 "⚠️ Warning: couldn't determine the path to python for `{executable}`"
169 );
170 continue;
171 }
172 interpreter.push(path.to_string());
173 versions_found.insert((major, minor));
174 }
175 }
176 }
177 }
178
179 // Conda environments are also supported on windows
180 let conda_info = Command::new("conda").arg("info").arg("-e").output();
181 if let Ok(output) = conda_info {
182 let lines = str::from_utf8(&output.stdout).unwrap().lines();
183 // The regex has three parts: The first matches the name and skips
184 // comments, the second skips the part in between and the third
185 // extracts the path
186 let re = Regex::new(r"^([^#].*?)[\s*]+([\w\\:.-]+)\s*$").unwrap();
187 let mut paths = vec![];
188 for i in lines {
189 if let Some(capture) = re.captures(i) {
190 if &capture[1] == "base" {
191 continue;
192 }
193 paths.push(String::from(&capture[2]));
194 }
195 }
196
197 for path in paths {
198 let executable_win = Path::new(&path).join("python.exe");
199 let executable = if executable_win.exists() {
200 executable_win
201 } else {
202 Path::new(&path).join("python")
203 };
204 if let Some(python_info) = windows_python_info(&executable)? {
205 if windows_interpreter_no_build(
206 python_info.major,
207 python_info.minor,
208 target.pointer_width(),
209 python_info.pointer_width.unwrap(),
210 min_python_minor,
211 requires_python,
212 ) {
213 continue;
214 }
215 interpreter.push(String::from(executable.to_str().unwrap()));
216 versions_found.insert((python_info.major, python_info.minor));
217 }
218 }
219 }
220
221 // Fallback to pythonX.Y for Microsoft Store versions
222 for minor in min_python_minor..=bridge.maximum_python_minor_version() {
223 if !versions_found.contains(&(3, minor)) {
224 let executable = format!("python3.{minor}.exe");
225 if let Some(python_info) = windows_python_info(Path::new(&executable))? {
226 if windows_interpreter_no_build(
227 python_info.major,
228 python_info.minor,
229 target.pointer_width(),
230 python_info.pointer_width.unwrap(),
231 min_python_minor,
232 requires_python,
233 ) {
234 continue;
235 }
236 interpreter.push(executable);
237 versions_found.insert((3, minor));
238 }
239 }
240 }
241
242 if interpreter.is_empty() {
243 bail!(
244 "Could not find any interpreters, are you sure you have python installed on your PATH?"
245 );
246 };
247 Ok(interpreter)
248 }
249
250 struct WindowsPythonInfo {
251 major: usize,
252 minor: usize,
253 pointer_width: Option<usize>,
254 }
255
256 fn windows_python_info(executable: &Path) -> Result<Option<WindowsPythonInfo>> {
257 let python_info = Command::new(executable)
258 .arg("-c")
259 .arg("import sys; print(sys.version)")
260 .output();
261
262 let python_info = match python_info {
263 Ok(python_info) => python_info,
264 Err(err) => {
265 if err.kind() == io::ErrorKind::NotFound {
266 // python executable not found
267 return Ok(None);
268 } else {
269 bail!(
270 "Error getting Python version info from {}",
271 executable.display()
272 );
273 }
274 }
275 };
276
277 let version_info = str::from_utf8(&python_info.stdout).unwrap();
278 let expr = Regex::new(r"(\d).(\d).(\d+)").unwrap();
279 if let Some(capture) = expr.captures(version_info) {
280 let major = capture.get(1).unwrap().as_str().parse::<usize>().unwrap();
281 let minor = capture.get(2).unwrap().as_str().parse::<usize>().unwrap();
282 let pointer_width = if version_info.contains("64 bit (AMD64)") {
283 64
284 } else {
285 32
286 };
287 Ok(Some(WindowsPythonInfo {
288 major,
289 minor,
290 pointer_width: Some(pointer_width),
291 }))
292 } else {
293 Ok(None)
294 }
295 }
296
297 #[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, clap::ValueEnum)]
298 #[serde(rename_all = "lowercase")]
299 #[clap(rename_all = "lower")]
300 pub enum InterpreterKind {
301 CPython,
302 PyPy,
303 GraalPy,
304 }
305
306 impl InterpreterKind {
307 /// Is this a CPython interpreter?
308 pub fn is_cpython(&self) -> bool {
309 matches!(self, InterpreterKind::CPython)
310 }
311
312 /// Is this a PyPy interpreter?
313 pub fn is_pypy(&self) -> bool {
314 matches!(self, InterpreterKind::PyPy)
315 }
316
317 /// Is this a GraalPy interpreter?
318 pub fn is_graalpy(&self) -> bool {
319 matches!(self, InterpreterKind::GraalPy)
320 }
321 }
322
323 impl fmt::Display for InterpreterKind {
324 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
325 match *self {
326 InterpreterKind::CPython => write!(f, "CPython"),
327 InterpreterKind::PyPy => write!(f, "PyPy"),
328 InterpreterKind::GraalPy => write!(f, "GraalVM"),
329 }
330 }
331 }
332
333 impl FromStr for InterpreterKind {
334 type Err = String;
335
336 fn from_str(s: &str) -> Result<Self, Self::Err> {
337 match s.to_ascii_lowercase().as_str() {
338 "cpython" => Ok(InterpreterKind::CPython),
339 "pypy" => Ok(InterpreterKind::PyPy),
340 "graalvm" | "graalpy" => Ok(InterpreterKind::GraalPy),
341 unknown => Err(format!("Unknown interpreter kind '{unknown}'")),
342 }
343 }
344 }
345
346 /// The output format of [GET_INTERPRETER_METADATA]
347 #[derive(Deserialize)]
348 struct InterpreterMetadataMessage {
349 implementation_name: String,
350 executable: Option<String>,
351 major: usize,
352 minor: usize,
353 abiflags: Option<String>,
354 interpreter: String,
355 ext_suffix: Option<String>,
356 // comes from `sysconfig.get_platform()`
357 platform: String,
358 // comes from `platform.system()`
359 system: String,
360 soabi: Option<String>,
361 gil_disabled: bool,
362 }
363
364 /// The location and version of an interpreter
365 #[derive(Debug, Clone, Eq, PartialEq)]
366 pub struct PythonInterpreter {
367 /// Python's sysconfig
368 /// Python's major version
369 pub config: InterpreterConfig,
370 /// Path to the python interpreter, e.g. /usr/bin/python3.6
371 ///
372 /// Just the name of the binary in PATH does also work, e.g. `python3.5`
373 pub executable: PathBuf,
374 /// Comes from `sysconfig.get_platform()`
375 ///
376 /// Note that this can be `None` when cross compiling
377 pub platform: Option<String>,
378 /// Is this interpreter runnable
379 ///
380 /// When cross compile the target interpreter isn't runnable,
381 /// and it's `executable` is empty
382 pub runnable: bool,
383 /// Comes from `sys.platform.name`
384 pub implementation_name: String,
385 /// Comes from sysconfig var `SOABI`
386 pub soabi: Option<String>,
387 }
388
389 impl Deref for PythonInterpreter {
390 type Target = InterpreterConfig;
391
392 fn deref(&self) -> &Self::Target {
393 &self.config
394 }
395 }
396
397 /// Returns the abiflags that are assembled through the message, with some
398 /// additional sanity checks.
399 ///
400 /// The rules are as follows:
401 /// - python 3 + Unix: Use ABIFLAGS
402 /// - python 3 + Windows: No ABIFLAGS, return an empty string
403 fn fun_with_abiflags(
404 message: &InterpreterMetadataMessage,
405 target: &Target,
406 bridge: &BridgeModel,
407 ) -> Result<String> {
408 if bridge != &BridgeModel::Cffi
409 && target.get_python_os() != message.system
410 && !target.cross_compiling()
411 {
412 bail!(
413 "platform.system() in python, {}, and the rust target, {:?}, don't match ಠ_ಠ",
414 message.system,
415 target,
416 )
417 }
418
419 if message.major != 3 || message.minor < 7 {
420 bail!(
421 "Only python >= 3.7 is supported, while you're using python {}.{}",
422 message.major,
423 message.minor
424 );
425 }
426
427 if message.interpreter == "pypy" || message.interpreter == "graalvm" {
428 // pypy and graalpy do not specify abi flags
429 Ok("".to_string())
430 } else if message.system == "windows" && message.minor < 14 {
431 if matches!(message.abiflags.as_deref(), Some("") | None) {
432 // windows has a few annoying cases, but its abiflags in sysconfig always empty
433 // python <= 3.7 has "m"
434 if message.minor <= 7 {
435 Ok("m".to_string())
436 } else if message.gil_disabled {
437 ensure!(
438 message.minor >= 13,
439 "gil_disabled is only available in python 3.13+ ಠ_ಠ"
440 );
441 Ok("t".to_string())
442 } else {
443 Ok("".to_string())
444 }
445 } else {
446 bail!("A python 3 interpreter on Windows does not define abiflags in its sysconfig before Python 3.14 ಠ_ಠ")
447 }
448 } else if let Some(ref abiflags) = message.abiflags {
449 if message.minor >= 8 {
450 // for 3.8, "builds with and without pymalloc are ABI compatible" and the flag dropped
451 Ok(abiflags.to_string())
452 } else if (abiflags != "m") && (abiflags != "dm") {
453 bail!("A python 3 interpreter on Linux or macOS must have 'm' or 'dm' as abiflags ಠ_ಠ")
454 } else {
455 Ok(abiflags.to_string())
456 }
457 } else {
458 bail!("A python 3 interpreter on Linux or macOS must define abiflags in its sysconfig ಠ_ಠ")
459 }
460 }
461
462 impl PythonInterpreter {
463 /// Does this interpreter have PEP 384 stable api aka. abi3 support?
464 pub fn has_stable_api(&self) -> bool {
465 if self.implementation_name.parse::<InterpreterKind>().is_err() {
466 false
467 } else {
468 match self.interpreter_kind {
469 // Free-threaded python does not have stable api support yet
470 InterpreterKind::CPython => !self.config.gil_disabled,
471 InterpreterKind::PyPy | InterpreterKind::GraalPy => false,
472 }
473 }
474 }
475
476 /// Returns the supported python environment in the PEP 425 format used for the wheel filename:
477 /// {python tag}-{abi tag}-{platform tag}
478 ///
479 /// Don't ask me why or how, this is just what setuptools uses so I'm also going to use
480 ///
481 /// If abi3 is true, cpython wheels use the generic abi3 with the given version as minimum
482 pub fn get_tag(&self, context: &BuildContext, platform_tags: &[PlatformTag]) -> Result<String> {
483 // Restrict `sysconfig.get_platform()` usage to Windows and non-portable Linux only for now
484 // so we don't need to deal with macOS deployment target
485 let target = &context.target;
486 let use_sysconfig_platform = target.is_windows()
487 || (target.is_linux() && platform_tags.iter().any(|tag| !tag.is_portable()))
488 || target.is_illumos();
489 let platform = if use_sysconfig_platform {
490 if let Some(platform) = self.platform.clone() {
491 platform
492 } else {
493 context.get_platform_tag(platform_tags)?
494 }
495 } else {
496 context.get_platform_tag(platform_tags)?
497 };
498 let tag = if self.implementation_name.parse::<InterpreterKind>().is_err() {
499 // Use generic tags when `sys.implementation.name` != `platform.python_implementation()`, for example Pyston
500 // See also https://github.com/pypa/packaging/blob/0031046f7fad649580bc3127d1cef9157da0dd79/packaging/tags.py#L234-L261
501 format!(
502 "{interpreter}{major}{minor}-{soabi}-{platform}",
503 interpreter = self.implementation_name,
504 major = self.major,
505 minor = self.minor,
506 soabi = self
507 .soabi
508 .as_deref()
509 .unwrap_or("none")
510 .replace(['-', '.'], "_"),
511 platform = platform
512 )
513 } else {
514 match self.interpreter_kind {
515 InterpreterKind::CPython => {
516 format!(
517 "cp{major}{minor}-cp{major}{minor}{abiflags}-{platform}",
518 major = self.major,
519 minor = self.minor,
520 abiflags = self.abiflags,
521 platform = platform
522 )
523 }
524 InterpreterKind::PyPy => {
525 // pypy uses its version as part of the ABI, e.g.
526 // pypy 3.7 7.3 => numpy-1.20.1-pp37-pypy37_pp73-manylinux2014_x86_64.whl
527 format!(
528 "pp{major}{minor}-{abi_tag}-{platform}",
529 major = self.major,
530 minor = self.minor,
531 abi_tag = calculate_abi_tag(&self.ext_suffix)
532 .expect("PyPy's syconfig didn't define a valid `EXT_SUFFIX` ಠ_ಠ"),
533 platform = platform,
534 )
535 }
536 InterpreterKind::GraalPy => {
537 // GraalPy like PyPy uses its version as part of the ABI
538 // graalpy 3.10 23.1 => numpy-1.23.5-graalpy310-graalpy231_310_native-manylinux2014_x86_64.whl
539 format!(
540 "graalpy{major}{minor}-{abi_tag}-{platform}",
541 major = self.major,
542 minor = self.minor,
543 abi_tag = calculate_abi_tag(&self.ext_suffix)
544 .expect("GraalPy's syconfig didn't define a valid `EXT_SUFFIX` ಠ_ಠ"),
545 platform = platform,
546 )
547 }
548 }
549 };
550 Ok(tag)
551 }
552
553 /// Adds the ext_suffix we read from python or know (.pyd/.abi3.so) and adds it to the base name
554 ///
555 /// For CPython, generate extensions as follows:
556 ///
557 /// For python 3, there is PEP 3149, but
558 /// that is only valid for 3.2 - 3.4. Since only 3.6+ is supported, the
559 /// templates are adapted from the (also
560 /// incorrect) release notes of CPython 3.5:
561 /// https://docs.python.org/3/whatsnew/3.5.html#build-and-c-api-changes
562 ///
563 /// Examples for 64-bit on CPython 3.6m:
564 /// Linux: foobar.cpython-36m-x86_64-linux-gnu.so
565 /// Windows: foobar.cp36-win_amd64.pyd
566 /// Mac: foobar.cpython-36m-darwin.so
567 /// FreeBSD: foobar.cpython-36m.so
568 ///
569 /// For pypy3, we read importlib.machinery.EXTENSION_SUFFIXES[0].
570 pub fn get_library_name(&self, base: &str) -> String {
571 format!(
572 "{base}{ext_suffix}",
573 base = base,
574 ext_suffix = self.ext_suffix
575 )
576 }
577
578 /// Is this a debug build of Python for Windows?
579 pub fn is_windows_debug(&self) -> bool {
580 self.ext_suffix.starts_with("_d.") && self.ext_suffix.ends_with(".pyd")
581 }
582
583 /// Checks whether the given command is a python interpreter and returns a
584 /// [PythonInterpreter] if that is the case
585 #[instrument(skip_all, fields(executable = %executable.as_ref().display()))]
586 pub fn check_executable(
587 executable: impl AsRef<Path>,
588 target: &Target,
589 bridge: &BridgeModel,
590 ) -> Result<Option<PythonInterpreter>> {
591 let output = Command::new(executable.as_ref())
592 .env("PYTHONNOUSERSITE", "1")
593 .args(["-c", GET_INTERPRETER_METADATA])
594 .output();
595
596 let err_msg = format!(
597 "Trying to get metadata from the python interpreter '{}' failed",
598 executable.as_ref().display()
599 );
600 let output = match output {
601 Ok(output) => {
602 if output.status.success() {
603 output
604 } else {
605 let stderr = String::from_utf8_lossy(&output.stderr);
606 if stderr.starts_with(&format!(
607 "pyenv: {}: command not found",
608 executable.as_ref().display()
609 )) {
610 eprintln!(
611 "⚠️ Warning: skipped unavailable python interpreter '{}' from pyenv",
612 executable.as_ref().display()
613 );
614 return Ok(None);
615 } else {
616 eprintln!("{stderr}");
617 bail!(err_msg);
618 }
619 }
620 }
621 Err(err) => {
622 if err.kind() == io::ErrorKind::NotFound {
623 if cfg!(windows) {
624 if let Some(python) = executable.as_ref().to_str() {
625 let ver = if python.starts_with("python") {
626 python.strip_prefix("python").unwrap_or(python)
627 } else {
628 python
629 };
630 // Try py -x.y on Windows
631 let mut metadata_py = tempfile::NamedTempFile::new()?;
632 write!(metadata_py, "{GET_INTERPRETER_METADATA}")?;
633 let mut cmd = Command::new("cmd");
634 cmd.arg("/c")
635 .arg("py")
636 .arg(format!("-{}-{}", ver, target.pointer_width()))
637 .arg(metadata_py.path())
638 .env("PYTHONNOUSERSITE", "1");
639 let output = cmd.output();
640 match output {
641 Ok(output) if output.status.success() => output,
642 _ => return Ok(None),
643 }
644 } else {
645 return Ok(None);
646 }
647 } else {
648 return Ok(None);
649 }
650 } else {
651 return Err(err).context(err_msg);
652 }
653 }
654 };
655 let message: InterpreterMetadataMessage = serde_json::from_slice(&output.stdout)
656 .context(err_msg)
657 .context(String::from_utf8_lossy(&output.stdout).trim().to_string())?;
658
659 if (message.major == 2 && message.minor != 7) || (message.major == 3 && message.minor < 5) {
660 debug!(
661 "Skipping outdated python interpreter '{}'",
662 executable.as_ref().display()
663 );
664 return Ok(None);
665 }
666
667 let interpreter = match message.interpreter.as_str() {
668 "cpython" => InterpreterKind::CPython,
669 "pypy" => InterpreterKind::PyPy,
670 "graalvm" | "graalpy" => InterpreterKind::GraalPy,
671 other => {
672 bail!("Unsupported interpreter {}", other);
673 }
674 };
675
676 let abiflags = fun_with_abiflags(&message, target, bridge).context(format_err!(
677 "Failed to get information from the python interpreter at {}",
678 executable.as_ref().display()
679 ))?;
680
681 let platform = if message.platform.starts_with("macosx") {
682 // We don't use platform from sysconfig on macOS
683 None
684 } else {
685 Some(message.platform.to_lowercase().replace(['-', '.'], "_"))
686 };
687
688 let executable = message
689 .executable
690 .map(PathBuf::from)
691 .unwrap_or_else(|| executable.as_ref().to_path_buf());
692 debug!(
693 "Found {} interpreter at {}",
694 interpreter,
695 executable.display()
696 );
697 Ok(Some(PythonInterpreter {
698 config: InterpreterConfig {
699 major: message.major,
700 minor: message.minor,
701 interpreter_kind: interpreter,
702 abiflags,
703 ext_suffix: message
704 .ext_suffix
705 .context("syconfig didn't define an `EXT_SUFFIX` ಠ_ಠ")?,
706 pointer_width: None,
707 gil_disabled: message.gil_disabled,
708 },
709 executable,
710 platform,
711 runnable: true,
712 implementation_name: message.implementation_name,
713 soabi: message.soabi,
714 }))
715 }
716
717 /// Construct a `PythonInterpreter` from a sysconfig and target
718 pub fn from_config(config: InterpreterConfig) -> Self {
719 let implementation_name = config.interpreter_kind.to_string().to_ascii_lowercase();
720 PythonInterpreter {
721 config,
722 executable: PathBuf::new(),
723 platform: None,
724 runnable: false,
725 implementation_name,
726 soabi: None,
727 }
728 }
729
730 /// Find all available python interpreters for a given target
731 pub fn find_by_target(
732 target: &Target,
733 requires_python: Option<&VersionSpecifiers>,
734 bridge: Option<&BridgeModel>,
735 ) -> Vec<PythonInterpreter> {
736 let min_python_minor = bridge
737 .map(|bridge| bridge.minimal_python_minor_version())
738 .unwrap_or(MINIMUM_PYTHON_MINOR);
739 let min_pypy_minor = bridge
740 .map(|bridge| bridge.minimal_pypy_minor_version())
741 .unwrap_or(MINIMUM_PYPY_MINOR);
742 let supports_free_threaded = bridge
743 .map(|bridge| bridge.supports_free_threaded())
744 .unwrap_or(false);
745 InterpreterConfig::lookup_target(target)
746 .into_iter()
747 .filter_map(|config| match requires_python {
748 Some(requires_python) => {
749 if requires_python
750 .contains(&Version::new([config.major as u64, config.minor as u64]))
751 {
752 Some(Self::from_config(config))
753 } else {
754 None
755 }
756 }
757 None => Some(Self::from_config(config)),
758 })
759 .filter_map(|config| match config.interpreter_kind {
760 InterpreterKind::CPython => {
761 if config.minor >= min_python_minor {
762 Some(config)
763 } else {
764 None
765 }
766 }
767 InterpreterKind::PyPy => {
768 if config.minor >= min_pypy_minor {
769 Some(config)
770 } else {
771 None
772 }
773 }
774 InterpreterKind::GraalPy => Some(config),
775 })
776 .filter_map(|config| {
777 if config.gil_disabled && !supports_free_threaded {
778 None
779 } else {
780 Some(config)
781 }
782 })
783 .collect()
784 }
785
786 /// Tries to find all installed python versions using the heuristic for the
787 /// given platform.
788 ///
789 /// We have two filters: The optional requires-python from the pyproject.toml and minimum python
790 /// minor either from the bindings (i.e. Cargo.toml `abi3-py{major}{minor}`) or the global
791 /// default minimum minor version
792 pub fn find_all(
793 target: &Target,
794 bridge: &BridgeModel,
795 requires_python: Option<&VersionSpecifiers>,
796 ) -> Result<Vec<PythonInterpreter>> {
797 let executables = if target.is_windows() {
798 // TOFIX: add PyPy support to Windows
799 find_all_windows(target, bridge, requires_python)?
800 } else {
801 let mut executables: Vec<String> = (bridge.minimal_python_minor_version()
802 ..=bridge.maximum_python_minor_version())
803 .filter(|minor| {
804 requires_python
805 .map(|requires_python| {
806 requires_python.contains(&Version::new([3, *minor as u64]))
807 })
808 .unwrap_or(true)
809 })
810 .map(|minor| format!("python3.{minor}"))
811 .collect();
812 // Also try to find PyPy for cffi and pyo3 bindings
813 if *bridge == BridgeModel::Cffi || bridge.is_pyo3() {
814 executables.extend(
815 (bridge.minimal_pypy_minor_version()..=bridge.maximum_pypy_minor_version())
816 .filter(|minor| {
817 requires_python
818 .map(|requires_python| {
819 requires_python.contains(&Version::new([3, *minor as u64]))
820 })
821 .unwrap_or(true)
822 })
823 .map(|minor| format!("pypy3.{minor}")),
824 );
825 }
826 executables
827 };
828 let mut available_versions = Vec::new();
829 for executable in executables {
830 if let Some(version) = PythonInterpreter::check_executable(executable, target, bridge)?
831 {
832 available_versions.push(version);
833 }
834 }
835
836 Ok(available_versions)
837 }
838
839 /// Checks that given list of executables are all valid python interpreters,
840 /// determines the abiflags and versions of those interpreters and
841 /// returns them as [PythonInterpreter]
842 pub fn check_executables(
843 executables: &[PathBuf],
844 target: &Target,
845 bridge: &BridgeModel,
846 ) -> Result<Vec<PythonInterpreter>> {
847 let mut available_versions = Vec::new();
848 for executable in executables {
849 if let Some(version) = PythonInterpreter::check_executable(executable, target, bridge)
850 .context(format!(
851 "{} is not a valid python interpreter",
852 executable.display()
853 ))? {
854 available_versions.push(version);
855 } else {
856 bail!(
857 "Python interpreter `{}` doesn't exist",
858 executable.display()
859 );
860 }
861 }
862
863 Ok(available_versions)
864 }
865
866 /// Run a python script using this Python interpreter.
867 pub fn run_script(&self, script: &str) -> Result<String> {
868 if !self.runnable {
869 bail!("This {} isn't runnable", self);
870 }
871 let out = Command::new(&self.executable)
872 .env("PYTHONIOENCODING", "utf-8")
873 .stdin(Stdio::piped())
874 .stdout(Stdio::piped())
875 .stderr(Stdio::inherit())
876 .spawn()
877 .and_then(|mut child| {
878 child
879 .stdin
880 .as_mut()
881 .expect("piped stdin")
882 .write_all(script.as_bytes())?;
883 child.wait_with_output()
884 });
885
886 match out {
887 Err(err) => {
888 if err.kind() == io::ErrorKind::NotFound {
889 bail!(
890 "Could not find any interpreter at {}, \
891 are you sure you have Python installed on your PATH?",
892 self.executable.display()
893 );
894 } else {
895 bail!(
896 "Failed to run the Python interpreter at {}: {}",
897 self.executable.display(),
898 err
899 );
900 }
901 }
902 Ok(ok) if !ok.status.success() => bail!("Python script failed"),
903 Ok(ok) => Ok(String::from_utf8(ok.stdout)?),
904 }
905 }
906
907 /// Whether this Python interpreter support portable manylinux/musllinux wheels
908 ///
909 /// Returns `true` if we can not decide
910 pub fn support_portable_wheels(&self) -> bool {
911 if !self.runnable {
912 return true;
913 }
914 let out = Command::new(&self.executable)
915 .args([
916 "-m",
917 "pip",
918 "debug",
919 "--verbose",
920 "--disable-pip-version-check",
921 ])
922 .output();
923
924 match out {
925 Err(_) => true,
926 Ok(ok) if !ok.status.success() => true,
927 Ok(ok) => {
928 if let Ok(stdout) = String::from_utf8(ok.stdout) {
929 stdout.contains("manylinux") || stdout.contains("musllinux")
930 } else {
931 true
932 }
933 }
934 }
935 }
936
937 /// An opaque string that uniquely identifies this Python interpreter.
938 /// Used to trigger rebuilds for `pyo3` when the Python interpreter changes.
939 pub fn environment_signature(&self) -> String {
940 let pointer_width = self.pointer_width.unwrap_or(64);
941 format!(
942 "{}-{}.{}-{}bit",
943 self.implementation_name, self.major, self.minor, pointer_width
944 )
945 }
946
947 /// Returns the site-packages directory inside a venv e.g.
948 /// {venv_base}/lib/python{x}.{y} on unix or {venv_base}/Lib on window
949 pub fn get_venv_site_package(&self, venv_base: impl AsRef<Path>, target: &Target) -> PathBuf {
950 if target.is_unix() {
951 match self.interpreter_kind {
952 InterpreterKind::CPython | InterpreterKind::GraalPy => {
953 let python_dir = format!("python{}.{}", self.major, self.minor);
954 venv_base
955 .as_ref()
956 .join("lib")
957 .join(python_dir)
958 .join("site-packages")
959 }
960 InterpreterKind::PyPy => venv_base.as_ref().join("site-packages"),
961 }
962 } else {
963 venv_base.as_ref().join("Lib").join("site-packages")
964 }
965 }
966 }
967
968 impl fmt::Display for PythonInterpreter {
969 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
970 if self.runnable {
971 write!(
972 f,
973 "{} {}.{}{} at {}",
974 self.config.interpreter_kind,
975 self.config.major,
976 self.config.minor,
977 self.config.abiflags,
978 self.executable.display()
979 )
980 } else {
981 write!(
982 f,
983 "{} {}.{}{}",
984 self.config.interpreter_kind,
985 self.config.major,
986 self.config.minor,
987 self.config.abiflags,
988 )
989 }
990 }
991 }
992
993 /// Calculate the ABI tag from EXT_SUFFIX
994 fn calculate_abi_tag(ext_suffix: &str) -> Option<String> {
995 let parts = ext_suffix.split('.').collect::<Vec<_>>();
996 if parts.len() < 3 {
997 // CPython3.7 and earlier uses ".pyd" on Windows.
998 return None;
999 }
1000 let soabi = parts[1];
1001 let mut soabi_split = soabi.split('-');
1002 let abi = if soabi.starts_with("cpython") {
1003 // non-windows
1004 format!("cp{}", soabi_split.nth(1).unwrap())
1005 } else if soabi.starts_with("cp") {
1006 // windows
1007 soabi_split.next().unwrap().to_string()
1008 } else if soabi.starts_with("pypy") {
1009 soabi_split.take(2).collect::<Vec<_>>().join("-")
1010 } else if soabi.starts_with("graalpy") {
1011 soabi_split.take(3).collect::<Vec<_>>().join("-")
1012 } else if !soabi.is_empty() {
1013 // pyston, ironpython, others?
1014 soabi_split.nth(1).unwrap().to_string()
1015 } else {
1016 return None;
1017 };
1018 let abi_tag = abi.replace(['.', '-', ' '], "_");
1019 Some(abi_tag)
1020 }
1021
1022 #[cfg(test)]
1023 mod tests {
1024 use crate::bridge::{PyO3, PyO3Crate};
1025 use expect_test::expect;
1026
1027 use super::*;
1028
1029 #[test]
1030 fn test_find_interpreter_by_target() {
1031 let target = Target::from_resolved_target_triple("x86_64-unknown-linux-gnu").unwrap();
1032 let pythons = PythonInterpreter::find_by_target(&target, None, None)
1033 .iter()
1034 .map(ToString::to_string)
1035 .collect::<Vec<_>>();
1036 let expected = expect![[r#"
1037 [
1038 "CPython 3.7m",
1039 "CPython 3.8",
1040 "CPython 3.9",
1041 "CPython 3.10",
1042 "CPython 3.11",
1043 "CPython 3.12",
1044 "CPython 3.13",
1045 "PyPy 3.8",
1046 "PyPy 3.9",
1047 "PyPy 3.10",
1048 "PyPy 3.11",
1049 ]
1050 "#]];
1051 expected.assert_debug_eq(&pythons);
1052
1053 // pyo3 0.23+ should find CPython 3.13t
1054 let pythons = PythonInterpreter::find_by_target(
1055 &target,
1056 None,
1057 Some(&BridgeModel::PyO3(PyO3 {
1058 crate_name: PyO3Crate::PyO3,
1059 version: semver::Version::new(0, 23, 0),
1060 abi3: None,
1061 metadata: None,
1062 })),
1063 )
1064 .iter()
1065 .map(ToString::to_string)
1066 .collect::<Vec<_>>();
1067 let expected = expect![[r#"
1068 [
1069 "CPython 3.7m",
1070 "CPython 3.8",
1071 "CPython 3.9",
1072 "CPython 3.10",
1073 "CPython 3.11",
1074 "CPython 3.12",
1075 "CPython 3.13",
1076 "CPython 3.13t",
1077 "PyPy 3.9",
1078 "PyPy 3.10",
1079 "PyPy 3.11",
1080 ]
1081 "#]];
1082 expected.assert_debug_eq(&pythons);
1083
1084 let pythons = PythonInterpreter::find_by_target(
1085 &target,
1086 Some(&VersionSpecifiers::from_str(">=3.8").unwrap()),
1087 None,
1088 )
1089 .iter()
1090 .map(ToString::to_string)
1091 .collect::<Vec<_>>();
1092 let expected = expect![[r#"
1093 [
1094 "CPython 3.8",
1095 "CPython 3.9",
1096 "CPython 3.10",
1097 "CPython 3.11",
1098 "CPython 3.12",
1099 "CPython 3.13",
1100 "PyPy 3.8",
1101 "PyPy 3.9",
1102 "PyPy 3.10",
1103 "PyPy 3.11",
1104 ]
1105 "#]];
1106 expected.assert_debug_eq(&pythons);
1107
1108 let pythons = PythonInterpreter::find_by_target(
1109 &target,
1110 Some(&VersionSpecifiers::from_str(">=3.10").unwrap()),
1111 None,
1112 )
1113 .iter()
1114 .map(ToString::to_string)
1115 .collect::<Vec<_>>();
1116 let expected = expect![[r#"
1117 [
1118 "CPython 3.10",
1119 "CPython 3.11",
1120 "CPython 3.12",
1121 "CPython 3.13",
1122 "PyPy 3.10",
1123 "PyPy 3.11",
1124 ]
1125 "#]];
1126 expected.assert_debug_eq(&pythons);
1127
1128 let pythons = PythonInterpreter::find_by_target(
1129 &target,
1130 Some(&VersionSpecifiers::from_str(">=3.8").unwrap()),
1131 Some(&BridgeModel::PyO3(PyO3 {
1132 crate_name: PyO3Crate::PyO3,
1133 version: semver::Version::new(0, 23, 0),
1134 abi3: None,
1135 metadata: None,
1136 })),
1137 )
1138 .iter()
1139 .map(ToString::to_string)
1140 .collect::<Vec<_>>();
1141 // should exclude PyPy < 3.9
1142 let expected = expect![[r#"
1143 [
1144 "CPython 3.8",
1145 "CPython 3.9",
1146 "CPython 3.10",
1147 "CPython 3.11",
1148 "CPython 3.12",
1149 "CPython 3.13",
1150 "CPython 3.13t",
1151 "PyPy 3.9",
1152 "PyPy 3.10",
1153 "PyPy 3.11",
1154 ]
1155 "#]];
1156 expected.assert_debug_eq(&pythons);
1157 }
1158
1159 #[test]
1160 fn test_calculate_abi_tag() {
1161 let cases = vec![
1162 (".cpython-37m-x86_64-linux-gnu.so", Some("cp37m")),
1163 (".cpython-310-x86_64-linux-gnu.so", Some("cp310")),
1164 (".cpython-310-darwin.so", Some("cp310")),
1165 (".cpython-313t-darwin.so", Some("cp313t")),
1166 (".cp310-win_amd64.pyd", Some("cp310")),
1167 (".cp39-mingw_x86_64.pyd", Some("cp39")),
1168 (".cpython-312-wasm32-wasi.so", Some("cp312")),
1169 (".cpython-38.so", Some("cp38")),
1170 (".pyd", None),
1171 (".so", None),
1172 (".pypy38-pp73-x86_64-linux-gnu.so", Some("pypy38_pp73")),
1173 (
1174 ".graalpy-38-native-x86_64-darwin.dylib",
1175 Some("graalpy_38_native"),
1176 ),
1177 (".pyston-23-x86_64-linux-gnu.so", Some("23")),
1178 ];
1179 for (ext_suffix, expected) in cases {
1180 assert_eq!(calculate_abi_tag(ext_suffix).as_deref(), expected);
1181 }
1182 }
1183 }