use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};
use super::remote_attach::{PyVersion, is_python_process};
const VERSION_FLAG: &str = "--version";
const CMD_SUMMARY_MAX: usize = 160;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PyTarget {
pub pid: u32,
pub version: PyVersion,
pub exe: PathBuf,
pub label: String,
}
pub fn attachable_python_targets() -> Vec<PyTarget> {
let mut sys = System::new();
sys.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::nothing()
.without_tasks()
.with_exe(UpdateKind::OnlyIfNotSet)
.with_cmd(UpdateKind::OnlyIfNotSet),
);
let self_pid = std::process::id();
let rows: Vec<(u32, PyVersion, PathBuf, String)> = sys
.processes()
.iter()
.filter_map(|(pid, proc_)| {
let pid = pid.as_u32();
if pid == self_pid {
return None;
}
let name = proc_.name().to_string_lossy();
let exe = proc_.exe();
if !is_python_process(&name, exe) {
return None;
}
let exe = exe?;
if is_pdb_attach_client(proc_.cmd()) {
return None;
}
let version = interpreter_version(exe)?;
if !version.supports_remote_attach() {
return None;
}
Some((pid, version, exe.to_path_buf(), summarize_cmd(proc_.cmd())))
})
.collect();
labelled_targets(rows)
}
fn labelled_targets(mut rows: Vec<(u32, PyVersion, PathBuf, String)>) -> Vec<PyTarget> {
rows.sort_by_key(|(pid, ..)| *pid);
let pid_width = rows
.iter()
.map(|(pid, ..)| pid.to_string().len())
.max()
.unwrap_or(0);
rows.into_iter()
.map(|(pid, version, exe, summary)| PyTarget {
pid,
version,
exe,
label: target_label(pid, pid_width, version, &summary),
})
.collect()
}
fn interpreter_version(exe: &Path) -> Option<PyVersion> {
let out = Command::new(exe).arg(VERSION_FLAG).output().ok()?;
PyVersion::parse(&String::from_utf8_lossy(&out.stdout))
.or_else(|| PyVersion::parse(&String::from_utf8_lossy(&out.stderr)))
}
fn summarize_cmd(cmd: &[OsString]) -> String {
let joined = cmd
.iter()
.enumerate()
.map(|(i, s)| match Path::new(s).file_name() {
Some(name) if i == 0 => name.to_string_lossy(),
_ => s.to_string_lossy(),
})
.collect::<Vec<_>>()
.join(" ");
elide_middle(&joined, CMD_SUMMARY_MAX)
}
pub fn elide_middle(s: &str, max: usize) -> String {
let chars: Vec<char> = s.chars().collect();
if chars.len() <= max {
return s.to_string();
}
let keep = max.saturating_sub(1);
let head = keep / 3;
let tail = keep - head;
let mut out: String = chars[..head].iter().collect();
out.push('…');
out.extend(&chars[chars.len() - tail..]);
out
}
fn is_pdb_attach_client(cmd: &[OsString]) -> bool {
let args: Vec<_> = cmd.iter().skip(1).map(|a| a.to_string_lossy()).collect();
let Some(module_at) = pdb_arguments_at(&args) else {
return false;
};
let mut rest = args[module_at..].iter();
while let Some(a) = rest.next() {
match a.as_ref() {
"-p" | "--pid" => return true,
a if a.starts_with("--pid=") => return true,
"-c" | "--command" => {
rest.next();
}
a if a.starts_with('-') => {}
_ => return false,
}
}
false
}
fn pdb_arguments_at(args: &[std::borrow::Cow<'_, str>]) -> Option<usize> {
let mut next = 0;
while let Some(arg) = args.get(next) {
next += 1;
if let Some(long) = arg.strip_prefix("--") {
match long {
"" => return None,
"check-hash-based-pycs" => next += 1,
_ => {}
}
continue;
}
let group = arg.strip_prefix('-').filter(|g| !g.is_empty())?;
for (at, flag) in group.char_indices() {
let value = &group[at + flag.len_utf8()..];
match flag {
'c' => return None,
'm' => {
let module = if value.is_empty() {
next += 1;
args.get(next - 1)?.as_ref()
} else {
value
};
return (module == "pdb").then_some(next);
}
'W' | 'X' => {
if value.is_empty() {
next += 1;
}
break;
}
_ => {}
}
}
}
None
}
fn target_label(pid: u32, pid_width: usize, version: PyVersion, cmd_summary: &str) -> String {
format!(
"PID {pid:<pid_width$} · Python {}.{}.{} · {cmd_summary}",
version.major, version.minor, version.patch
)
}
#[cfg(test)]
mod tests {
use super::*;
fn v(major: u32, minor: u32, patch: u32) -> PyVersion {
PyVersion {
major,
minor,
patch,
}
}
#[test]
fn label_includes_pid_version_and_command() {
let label = target_label(4321, 4, v(3, 14, 2), "app.py --serve");
assert!(label.contains("PID 4321"));
assert!(label.contains("3.14.2"));
assert!(label.contains("app.py --serve"));
}
#[test]
fn summarize_joins_argv_with_spaces() {
let cmd = vec![
OsString::from("python3.14"),
OsString::from("app.py"),
OsString::from("--port=8000"),
];
assert_eq!(summarize_cmd(&cmd), "python3.14 app.py --port=8000");
}
#[test]
fn summarize_names_the_interpreter_by_file_name_and_keeps_the_arguments() {
let cmd = argv(&[
"/root/.local/share/uv/python/cpython-3.14.0-linux-x86_64-gnu/bin/python3.14",
"-m",
"http.server",
"8766",
]);
assert_eq!(summarize_cmd(&cmd), "python3.14 -m http.server 8766");
}
#[test]
fn summarize_cuts_an_overlong_argv_in_the_middle_and_keeps_its_end() {
let long = "x".repeat(300);
let cmd = argv(&["python3", "worker.py", &long, "--queue", "emails"]);
let out = summarize_cmd(&cmd);
assert_eq!(out.chars().count(), CMD_SUMMARY_MAX);
assert!(out.starts_with("python3 worker.py x"), "{out}");
assert!(out.ends_with("x --queue emails"), "{out}");
assert_eq!(out.matches('…').count(), 1, "{out}");
}
#[test]
fn summarize_leaves_a_short_command_whole() {
let cmd = argv(&["python3", "manage.py", "runserver"]);
assert_eq!(summarize_cmd(&cmd), "python3 manage.py runserver");
assert_eq!(summarize_cmd(&argv(&["python3.14"])), "python3.14");
}
#[test]
fn summarize_empty_argv_is_empty() {
assert_eq!(summarize_cmd(&[]), "");
}
fn argv(args: &[&str]) -> Vec<OsString> {
args.iter().map(OsString::from).collect()
}
#[test]
fn a_pdb_attach_client_is_not_offered_as_a_target() {
for client in [
&["/usr/bin/python3.14", "-m", "pdb", "-p", "4321"][..],
&["python3", "-mpdb", "--pid=4321"],
&["python3", "-m", "pdb", "-c", "continue", "--pid", "9"],
] {
assert!(is_pdb_attach_client(&argv(client)), "{client:?}");
}
for target in [
&["python3", "-m", "pdb", "app.py", "-p", "80"][..],
&["python3", "serve.py", "-p", "8000"],
&["python3", "-m", "http.server", "-p"],
&["python3"],
] {
assert!(!is_pdb_attach_client(&argv(target)), "{target:?}");
}
}
#[test]
fn a_programs_own_dash_m_pdb_arguments_are_not_an_attach_client() {
let hidden = [
&["python3", "tool.py", "-m", "pdb", "-p", "80"][..],
&["python3", "-c", "code", "-m", "pdb", "-p", "5"],
&["python3", "-X", "dev", "tool.py", "-m", "pdb", "-p", "1"],
&["python3", "-", "-m", "pdb", "-p", "1"],
&["python3", "--", "tool.py", "-m", "pdb", "-p", "1"],
]
.into_iter()
.filter(|target| is_pdb_attach_client(&argv(target)))
.collect::<Vec<_>>();
assert!(hidden.is_empty(), "taken for pdb clients: {hidden:?}");
}
#[test]
fn interpreter_options_before_dash_m_pdb_are_read_through() {
for client in [
&["python3", "-m", "pdb", "-p", "123"][..],
&["python3", "-X", "dev", "-m", "pdb", "-p", "123"],
&[
"python3", "-Xdev", "-W", "ignore", "-u", "-m", "pdb", "--pid", "1",
],
&[
"python3",
"--check-hash-based-pycs",
"never",
"-m",
"pdb",
"-p",
"1",
],
] {
assert!(is_pdb_attach_client(&argv(client)), "{client:?}");
}
for target in [
&["python3", "-W", "ignore", "tool.py"][..],
&["python3", "-W", "ignore", "tool.py", "-p", "1"],
] {
assert!(!is_pdb_attach_client(&argv(target)), "{target:?}");
}
}
#[test]
fn combined_short_options_are_read_as_cpython_reads_them() {
for client in [
&["python3", "-IB", "-um", "pdb", "-p", "1"][..],
&["python3", "-uX", "dev", "-mpdb", "-p", "1"],
] {
assert!(is_pdb_attach_client(&argv(client)), "{client:?}");
}
let code_then_args = ["python3", "-uc", "import pdb", "-m", "pdb", "-p", "1"];
assert!(!is_pdb_attach_client(&argv(&code_then_args)));
}
#[test]
fn a_module_only_named_like_pdb_is_still_a_target() {
for target in [
&["python3", "-m", "pdbpp", "-p", "1"][..],
&["python3", "-mpdbx", "--pid=1"],
&["python3", "-m", "pdb"],
&["python3", "-m", "pdb", "-c", "continue"],
] {
assert!(!is_pdb_attach_client(&argv(target)), "{target:?}");
}
}
#[test]
fn a_threaded_target_is_listed_once() {
let Some(python) = python_314() else {
eprintln!("skipping: no CPython 3.14+ found");
return;
};
let marker = format!("threaded{}", std::process::id());
let script = format!(
"{marker} = 1\n\
import threading, time\n\
for _ in range(3): threading.Thread(target=time.sleep, args=(30,), daemon=True).start()\n\
time.sleep(30)\n"
);
let target = Reap(
Command::new(&python)
.args(["-c", &script])
.spawn()
.expect("spawn the target"),
);
let pid = target.0.id();
let listed = || -> Vec<u32> {
attachable_python_targets()
.into_iter()
.filter(|t| t.label.contains(&marker))
.map(|t| t.pid)
.collect()
};
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the threaded python to be listed",
|| !listed().is_empty(),
);
std::thread::sleep(std::time::Duration::from_millis(300));
assert_eq!(listed(), vec![pid]);
}
fn python_314() -> Option<PathBuf> {
let mut candidates: Vec<PathBuf> = ["python3.14", "python3.15", "python3"]
.into_iter()
.map(PathBuf::from)
.collect();
if let Some(home) = std::env::var_os("HOME") {
candidates.push(PathBuf::from(home).join(".croft/debug-venv/bin/python"));
}
if let Ok(out) = Command::new("uv").args(["python", "find", "3.14"]).output() {
let found = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !found.is_empty() {
candidates.push(PathBuf::from(found));
}
}
candidates
.into_iter()
.find(|p| interpreter_version(p).is_some_and(|v| v.supports_remote_attach()))
}
struct Reap(std::process::Child);
impl Drop for Reap {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
#[test]
fn a_listed_target_shows_its_command_line() {
let Some(python) = python_314() else {
eprintln!("skipping: no CPython 3.14+ found");
return;
};
let target = Reap(
Command::new(&python)
.args(["-c", "import time; time.sleep(30)"])
.spawn()
.expect("spawn the target"),
);
let pid = target.0.id();
let mut label = None;
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the sleeping python to be listed",
|| {
label = attachable_python_targets()
.into_iter()
.find(|t| t.pid == pid)
.map(|t| t.label);
label.is_some()
},
);
let label = label.unwrap();
assert!(
label.contains("-c import time"),
"the row names the command line: {label}"
);
}
fn version_column(label: &str) -> usize {
label[..label.find("Python").expect("a version")]
.chars()
.count()
}
#[test]
fn the_pid_column_is_padded_to_the_widest_pid() {
let exe = PathBuf::from("/usr/bin/python3.14");
let rows = labelled_targets(vec![
(
51234,
v(3, 14, 2),
exe.clone(),
String::from("python3.14 worker.py"),
),
(
812,
v(3, 14, 2),
exe.clone(),
String::from("python3.14 a.py"),
),
(
4321,
v(3, 14, 2),
exe.clone(),
String::from("python3.14 -m app"),
),
]);
assert_eq!(
rows.iter().map(|t| t.pid).collect::<Vec<_>>(),
vec![812, 4321, 51234]
);
let columns: Vec<usize> = rows.iter().map(|t| version_column(&t.label)).collect();
assert!(columns.iter().all(|c| *c == columns[0]), "{rows:#?}");
assert!(
rows[0].label.starts_with("PID 812 ·"),
"{}",
rows[0].label
);
assert!(
rows[2].label.ends_with("· python3.14 worker.py"),
"{}",
rows[2].label
);
}
#[test]
fn same_width_pids_are_not_padded() {
let exe = PathBuf::from("/usr/bin/python3.14");
let one = labelled_targets(vec![(
4321,
v(3, 14, 2),
exe.clone(),
String::from("app.py --serve"),
)]);
assert_eq!(
one[0].label,
"PID 4321 · Python 3.14.2 · app.py --serve"
);
let same = labelled_targets(vec![
(4321, v(3, 14, 2), exe.clone(), String::from("a.py")),
(1234, v(3, 14, 2), exe.clone(), String::from("b.py")),
]);
assert!(
same.iter()
.all(|t| t.label.starts_with("PID ") && !t.label.contains(" ·"))
);
assert!(labelled_targets(Vec::new()).is_empty());
}
}