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