Files
openidea/src/features/python-console/index.ts
T
LU XIANGRUIandwildcatDownstairs c632dfa01c feat(python): add a Python Console tool window (#5164)
Adds a Python Console tool window: an interactive interpreter of the project's Python (the one Settings and the status bar show; in a workspace, the member the active file is in), started in the project root with the source roots on `PYTHONPATH`. It uses IPython when the interpreter has it and plain Python otherwise, in its own `__main__`. Enter runs the input, Shift+Enter adds a line, Up/Down recall earlier inputs, and while code runs a typed line answers its `input()`. A Variables pane lists the console's globals after each run. Execute Selection in Python Console (`python.console.executeSelection`, Alt+Shift+E, also in the editor context menu of Python files) sends the selection or the current line, starting the console if needed; a selection inside an indented block is dedented. The console is a small driver script run on the existing Run process host, so there are no backend changes.

Closes #5148

Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
2026-11-22 14:34:50 +08:00

58 lines
1.9 KiB
TypeScript

/** Python Console: an interactive interpreter of the project's Python, fed from the editor too. */
import { activeEditor } from "@/editor/api";
import { registerActions } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { lazyComponent } from "@/ui";
import { registerMenuGroup, registerToolWindow, toolWindowService } from "@/workbench/contributions";
import { selectionCode } from "./selection";
import { execute, installConsole } from "./store";
const ID = "pythonConsole";
export function activate(): () => void {
const disposers = [
installConsole(),
registerToolWindow({
id: ID,
title: "Python Console",
icon: "file-python",
anchor: "bottom",
// Listed under the stripe's "…" until first opened: most projects are not Python ones.
stripe: "onUse",
order: 27,
component: lazyComponent(() => import("./ConsoleView").then((m) => m.ConsoleView)),
}),
registerActions([
{
id: "python.console.show",
title: "Python Console",
category: "Tools",
when: "projectOpen",
run: () => toolWindowService().show(ID, true),
},
{
id: "python.console.executeSelection",
title: "Execute Selection in Python Console",
category: "Tools",
when: "editorLangId == python",
keyWhen: "editorTextFocus",
run: () => {
const state = activeEditor()?.view.state;
const code = state && selectionCode(state);
if (!code?.trim()) return;
toolWindowService().show(ID, false);
execute(code);
},
},
]),
registerMenuGroup({
id: "pythonConsole.editor",
menus: ["editor"],
order: 45,
items: () =>
getContext().editorLangId === "python" ? [{ kind: "action", action: "python.console.executeSelection" }] : [],
}),
];
return () => disposers.reverse().forEach((d) => d());
}