/** * Settings › Python › Dependencies (PyCharm's "Python Interpreter" page): the * project interpreter and its packages (pip / uv pip). The interpreter feeds * run configurations, basedpyright / pyright (`python.pythonPath`) and the * terminal's virtualenv activation. A Docker or Compose run target can be the * interpreter (`target:`): its libraries are a read-only snapshot of the image. */ import { isCancelled } from "@/platform/ipc"; import { useCallback, useEffect, useMemo, useState, type KeyboardEvent, type MouseEvent } from "react"; import clsx from "clsx"; import { Button, IconButton, Input, Spinner, showContextMenu, T } from "@/ui"; import { useProject } from "@/platform/project"; import { Section, Toggle } from "../components/Form"; import { containerPython, effectivePython, interpreterTarget, listPackages, pip, refreshContainerPython, targetChoices, type ContainerPython, type PythonPackage, } from "./api"; import { validateRunTargets, type RunTargetValid } from "@/platform/remoteSettings"; import { AddInterpreterDialog } from "./AddInterpreterDialog"; import { useSetting } from "../components/context"; import { SdkField, tildify } from "./components"; import { interpreterIcon, sameInterpreterPath, usePythonInterpreters } from "./interpreters"; import styles from "./Sdk.module.css"; import { tx } from "@/platform/i18n"; type Op = "install" | "upgrade" | "uninstall"; interface Job { op: Op; target: string; cancel: () => void; } export function filterPackages(packages: readonly PythonPackage[], query: string): PythonPackage[] { const q = query.trim().toLowerCase(); return q ? packages.filter((p) => p.name.toLowerCase().includes(q)) : [...packages]; } function usePackages(python: string | null) { const [tick, setTick] = useState(0); const [result, setResult] = useState<{ key: string; python: string; packages: PythonPackage[] | null; error: string | null; } | null>(null); useEffect(() => { if (!python) return; let live = true; const key = `${python}#${tick}`; listPackages(python) .then((packages) => live && setResult({ key, python, packages, error: null })) .catch( (e: unknown) => live && setResult({ key, python, packages: null, error: String((e as Error)?.message ?? e) }), ); return () => { live = false; }; }, [python, tick]); const reload = useCallback(() => setTick((t) => t + 1), []); // While reloading the same interpreter, keep showing its previous list. const same = !!python && result?.python === python; return { packages: same ? result.packages : null, error: same ? result.error : null, loading: !!python && result?.key !== `${python}#${tick}`, reload, }; } /** The snapshot of a run target interpreter; polled while one is being taken. */ function useContainerPython(target: string | null) { const [state, setState] = useState<{ target: string; info: ContainerPython | null; error: string | null } | null>( null, ); const [tick, setTick] = useState(0); const [refreshing, setRefreshing] = useState(false); useEffect(() => { if (!target) return; let live = true; let timer: ReturnType | undefined; const load = () => containerPython() .then((info) => { if (!live) return; setState({ target, info, error: null }); if (info?.updating) timer = setTimeout(load, 2000); }) .catch((e: unknown) => live && setState({ target, info: null, error: String((e as Error)?.message ?? e) })); void load(); return () => { live = false; clearTimeout(timer); }; }, [target, tick]); const refresh = useCallback(() => { if (!target) return; setRefreshing(true); refreshContainerPython() .then((info) => setState({ target, info, error: null })) .catch((e: unknown) => setState((s) => ({ target, info: s?.info ?? null, error: String((e as Error)?.message ?? e) })), ) .finally(() => { setRefreshing(false); setTick((t) => t + 1); }); }, [target]); const same = !!target && state?.target === target; return { info: same ? state.info : null, error: same ? state.error : null, busy: refreshing || (same && !!state.info?.updating), loading: !!target && !same, refresh, }; } export function PythonInterpreterPage() { const [interpreter, setInterpreter] = useSetting("languages.python.interpreter"); const [activate, setActivate] = useSetting("languages.python.activateVirtualenv"); const root = useProject((s) => s.project?.root ?? null); const [auto, setAuto] = useState(null); // Bumped when an environment is created: it may reuse the configured path, whose state changed. const [created, setCreated] = useState(0); // Detected interpreters plus the ones added to (or hidden from) the IDE-wide list. const { detected, rows, hidden } = usePythonInterpreters({ withProjects: false }); const extras = useMemo( () => rows .filter((row) => !row.invalid && !detected.some((sdk) => sameInterpreterPath(sdk.path, row.path, null))) .map((row) => ({ value: row.path, label: row.name, detail: tildify(row.path), icon: interpreterIcon(row.source), })), [rows, detected], ); const [rawTargets] = useSetting("runTargets"); const targets = useMemo(() => targetChoices(validateRunTargets(rawTargets)), [rawTargets]); const target = interpreterTarget(interpreter); const container = useContainerPython(target); useEffect(() => { let live = true; effectivePython() .then((p) => live && setAuto(p)) .catch(() => live && setAuto(null)); return () => { live = false; }; }, [root, created]); // The interpreter runs resolve to: the configured one while it exists, else the fallback. const [resolved, setResolved] = useState<{ interpreter: string; path: string | null } | null>(null); useEffect(() => { if (!interpreter) return; let live = true; effectivePython() .then((path) => live && setResolved({ interpreter, path })) .catch(() => live && setResolved(null)); return () => { live = false; }; }, [root, interpreter, created]); // A configured interpreter whose executable is gone (PyCharm's "Invalid"): runs fall back. const invalid = !target && !!interpreter && resolved?.interpreter === interpreter && !sameInterpreter(resolved.path, interpreter, root); // Without a configured interpreter the project's virtualenv is used (like run configurations). const python = target ? null : interpreter || auto; const local = usePackages(python); const { packages, error, loading, reload } = target ? { packages: container.info?.version ? container.info.packages : null, error: container.error, loading: container.loading || container.busy, reload: container.refresh, } : local; const [selected, setSelected] = useState(null); const [query, setQuery] = useState(""); const [installing, setInstalling] = useState(false); const [requirement, setRequirement] = useState(""); const [job, setJob] = useState(null); const [log, setLog] = useState([]); const [jobError, setJobError] = useState(null); const [adding, setAdding] = useState(false); const shown = useMemo(() => filterPackages(packages ?? [], query), [packages, query]); const run = (op: Op, target: string) => { if (!python || job) return; setLog([]); setJobError(null); const s = pip(python, target, op, (line) => setLog((l) => [...l.slice(-400), line])); setJob({ op, target, cancel: s.cancel }); s.promise .then(() => { if (op === "install") { setRequirement(""); setInstalling(false); } if (op === "uninstall") setSelected(null); reload(); }) .catch((e: unknown) => setJobError(isCancelled(e) ? null : String((e as Error)?.message ?? e))) .finally(() => setJob(null)); }; const menu = (e: MouseEvent, pkg: PythonPackage) => { e.preventDefault(); setSelected(pkg.name); showContextMenu(e, [ { label: "Upgrade", icon: "arrow-up", disabled: !!job, run: () => run("upgrade", pkg.name) }, { label: "Uninstall", icon: "minus", disabled: !!job, run: () => run("uninstall", pkg.name) }, ]); }; const onRowKey = (e: KeyboardEvent, i: number) => { const next = e.key === "ArrowDown" ? i + 1 : e.key === "ArrowUp" ? i - 1 : -1; if (next >= 0 && next < shown.length) { e.preventDefault(); setSelected(shown[next]!.name); (e.currentTarget.parentElement?.children[next] as HTMLElement | undefined)?.focus(); } else if ((e.key === "Delete" || e.key === "Backspace") && selected) { e.preventDefault(); run("uninstall", selected); } }; const autoDetail = auto ? tildify(auto) : "No virtualenv in the project"; const current = detected?.find((s) => s.path === python); const containerDetail = !target ? null : container.info?.version ? `${container.info.name || target} — Python ${container.info.version}${container.info.image ? ` · ${container.info.image.replace(/^sha256:/, "").slice(0, 12)}` : ""}` : container.busy ? tx("Copying the libraries from the container…") : container.info && !container.info.name ? tx("No run target has this id: choose another interpreter.") : tx("The container's libraries have not been copied yet."); return (
Python Interpreter "} emptyDetail={autoDetail} browseTitle="Select Python Interpreter" aria-label="Python interpreter" invalid={invalid} extra={[...extras, ...targets]} exclude={hidden} optionIcon={(sdk) => interpreterIcon(sdk.source)} />
{containerDetail && (
{containerDetail}
)} {python && (
{current && !invalid ? `${current.name} — ` : ""} {tildify(python)}
)} {invalid && (
The configured Python interpreter no longer exists. Choose another interpreter or add a new one.
)}
setInstalling((v) => !v)} /> selected && run("uninstall", selected)} /> selected && run("upgrade", selected)} /> {(loading || job) && } setQuery(e.target.value)} />
{installing && (
{ e.preventDefault(); if (requirement.trim()) run("install", requirement.trim()); }} > setRequirement(e.target.value)} onKeyDown={(e) => { if (e.key === "Escape") { e.stopPropagation(); setInstalling(false); } }} />
)}
{shown.map((p, i) => ( setSelected(p.name)} onContextMenu={(e) => (target ? undefined : menu(e, p))} onKeyDown={(e) => onRowKey(e, i)} > ))}
Package Version
{p.name} {p.version}
{!python && !target && (
No interpreter selected. Choose one above or add a new one.
)} {(python || target) && error && !invalid && (
{error}
)} {(python || target) && !error && packages && shown.length === 0 && (
{query ? tx("No packages match") : tx("No packages installed")}
)} {(python || target) && !error && !packages && loading && (
Loading packages…
)}
{target && (
Packages come from the container image and are read-only here. To change them, edit the image or its requirements and rebuild it, then copy the libraries again.
)} {job && (
{job.op === "install" ? tx("Installing") : job.op === "upgrade" ? tx("Upgrading") : tx("Uninstalling")}{" "} {job.target}…
)} {jobError && (
{jobError}
)} {log.length > 0 && (
          {log.join("\n")}
        
)}
{adding && root && ( setAdding(false)} onAdded={(path) => { setInterpreter(path); setCreated((n) => n + 1); reload(); setAdding(false); }} /> )}
); } /** Whether `resolved` (an absolute path from the backend) is the configured `interpreter` setting. */ function sameInterpreter(resolved: string | null, interpreter: string, root: string | null): boolean { if (!resolved) return false; if (tildify(resolved) === tildify(interpreter)) return true; return !!root && resolved === `${root.replace(/[\\/]+$/, "")}/${interpreter}`; }