Skip to main content

byob_exec/
python.rs

1//! Which Python runs model code, and the managed environment for data-analysis packages.
2//!
3//! Order: `$BYOB_PYTHON`, then the managed venv `<data>/python/venv` (created by
4//! [`install_python_packages`](crate::InstallPythonPackages) with `uv`), then `python3` /
5//! `python` on `PATH`.
6
7use std::ffi::OsStr;
8use std::path::{Path, PathBuf};
9
10pub use byob_sandbox::which;
11
12/// Overrides the interpreter.
13pub const PYTHON_ENV: &str = "BYOB_PYTHON";
14
15/// The managed environment's folder under the byob data folder.
16pub fn managed_root(data_dir: &Path) -> PathBuf {
17    data_dir.join("python")
18}
19
20pub fn managed_venv(data_dir: &Path) -> PathBuf {
21    managed_root(data_dir).join("venv")
22}
23
24pub fn venv_python(venv: &Path) -> PathBuf {
25    if cfg!(windows) { venv.join("Scripts").join("python.exe") } else { venv.join("bin").join("python") }
26}
27
28/// A resolved interpreter.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Python {
31    pub path: PathBuf,
32    /// It's byob's managed venv.
33    pub managed: bool,
34}
35
36impl Python {
37    /// Find an interpreter (see the module docs).
38    pub fn resolve(data_dir: Option<&Path>) -> Option<Self> {
39        Self::resolve_in(data_dir, &[])
40    }
41
42    /// Like [`Python::resolve`], but a `python3` in the workspace environment's `PATH`
43    /// entries (installed packages, a `.venv`, the dev shell) comes right after `$BYOB_PYTHON`.
44    pub fn resolve_in(data_dir: Option<&Path>, env_path: &[PathBuf]) -> Option<Self> {
45        if let Some(p) = std::env::var_os(PYTHON_ENV).filter(|p| !p.is_empty()) {
46            return which(&p).map(|path| Self { path, managed: false });
47        }
48        for dir in env_path {
49            for name in ["python3", "python"] {
50                let p = dir.join(if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() });
51                if which(p.as_os_str()).is_some() {
52                    return Some(Self { path: p, managed: false });
53                }
54            }
55        }
56        if let Some(d) = data_dir {
57            let p = venv_python(&managed_venv(d));
58            if p.exists() {
59                return Some(Self { path: p, managed: true });
60            }
61        }
62        system_python().map(|path| Self { path, managed: false })
63    }
64
65    /// Folders the sandbox must let this interpreter read (see
66    /// [`byob_sandbox::interpreter_read_paths`]).
67    pub fn read_paths(&self) -> Vec<PathBuf> {
68        byob_sandbox::interpreter_read_paths(self.path.as_os_str())
69    }
70}
71
72/// `python3` (or `python`) on `PATH`, ignoring `$BYOB_PYTHON` and the managed venv. On
73/// Windows, the Microsoft Store's `python.exe` aliases don't count (without Python installed
74/// they open the Store), and the `py` launcher is asked where its Python 3 is.
75pub fn system_python() -> Option<PathBuf> {
76    let found = ["python3", "python"].into_iter().filter_map(|n| which(OsStr::new(n))).find(|p| !is_store_alias(p));
77    if found.is_some() || !cfg!(windows) {
78        return found;
79    }
80    let launcher = which(OsStr::new("py"))?;
81    let out = std::process::Command::new(launcher)
82        .args(["-3", "-c", "import sys; print(sys.executable)"])
83        .stdin(std::process::Stdio::null())
84        .stderr(std::process::Stdio::null())
85        .output()
86        .ok()
87        .filter(|o| o.status.success())?;
88    let path = PathBuf::from(String::from_utf8(out.stdout).ok()?.trim());
89    (path.is_absolute() && path.is_file() && !is_store_alias(&path)).then_some(path)
90}
91
92/// A Windows App Execution Alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\python.exe`).
93fn is_store_alias(p: &Path) -> bool {
94    p.components().any(|c| c.as_os_str().eq_ignore_ascii_case("WindowsApps"))
95}
96
97/// A package requirement the model may ask for: a name with optional extras and version
98/// constraints (`pandas`, `scikit-learn>=1.4`, `xarray[io]`). No URLs, paths or options.
99pub fn valid_requirement(s: &str) -> bool {
100    let Some(first) = s.chars().next() else { return false };
101    s.len() <= 100 && first.is_ascii_alphanumeric() && s.chars().all(|c| c.is_ascii_alphanumeric() || "._-[],<>=!~".contains(c))
102}
103
104#[cfg(test)]
105mod tests {
106    /// The Windows runners have Python installed: it's found by name (`python.exe`), not
107    /// through a Store alias.
108    #[cfg(windows)]
109    #[test]
110    fn windows_finds_an_installed_python() {
111        let p = system_python().expect("a Python on PATH or through py");
112        assert!(!is_store_alias(&p) && p.is_file(), "{}", p.display());
113    }
114
115    #[test]
116    fn store_aliases_are_not_python() {
117        assert!(is_store_alias(Path::new("/Users/me/AppData/Local/Microsoft/WindowsApps/python.exe")));
118        assert!(is_store_alias(Path::new("/x/windowsapps/python3.exe")));
119        assert!(!is_store_alias(Path::new("/usr/bin/python3")));
120    }
121
122    use super::*;
123
124    #[test]
125    fn requirements() {
126        for ok in ["pandas", "scikit-learn>=1.4", "xarray[io]", "numpy==2.1.0", "a.b_c"] {
127            assert!(valid_requirement(ok), "{ok}");
128        }
129        for bad in ["", "-r", "--index-url=x", "../x", "git+https://x", "a b", "pkg@ https://x", "/abs", "x;rm", &"a".repeat(101)] {
130            assert!(!valid_requirement(bad), "{bad}");
131        }
132    }
133
134    #[cfg(unix)]
135    #[test]
136    fn venv_read_paths() {
137        use std::os::unix::fs::PermissionsExt;
138        let d = tempfile::tempdir().unwrap();
139        let venv = d.path().join("venv");
140        std::fs::create_dir_all(venv.join("bin")).unwrap();
141        std::fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\n").unwrap();
142        std::fs::write(venv.join("bin/python"), "").unwrap();
143        std::fs::set_permissions(venv.join("bin/python"), std::fs::Permissions::from_mode(0o755)).unwrap();
144        let p = Python { path: venv.join("bin/python"), managed: true };
145        assert!(p.read_paths().contains(&venv.canonicalize().unwrap()));
146        // a stray binary in a plain folder grants nothing
147        std::fs::create_dir_all(d.path().join("bin")).unwrap();
148        std::fs::write(d.path().join("bin/python3"), "").unwrap();
149        std::fs::set_permissions(d.path().join("bin/python3"), std::fs::Permissions::from_mode(0o755)).unwrap();
150        let p = Python { path: d.path().join("bin/python3"), managed: false };
151        assert!(p.read_paths().is_empty());
152    }
153}