10000 PyTerminal Plugin by WebReflection · Pull Request #1801 · pyscript/pyscript · GitHub
[go: up one dir, main page]

Skip to content

PyTerminal Plugin #1801

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions pyscript.core/src/plugins/py-terminal.js
Original file line number Diff line number Di 10000 ff line change
@@ -0,0 +1,114 @@
// PyScript py-terminal plugin
import { hooks } from "../core.js";

const XTERM = "5.3.0";
const XTERM_READLINE = "1.1.1";

const { assign } = Object;

// Avoid conflicts with py-terminal re-definition
if (!customElements.get("py-terminal")) {
document.head.append(
assign(document.createElement("link"), {
rel: "stylesheet",
href: `https://cdn.jsdelivr.net/npm/xterm@${XTERM}/css/xterm.min.css`,
}),
);

const [{ Terminal }, { Readline }] = await Promise.all([
import(
/* webpackIgnore: true */ `https://cdn.jsdelivr.net/npm/xterm@${XTERM}/+esm`
),
import(
/* webpackIgnore: true */ `https://cdn.jsdelivr.net/npm/xterm-readline@${XTERM_READLINE}/+esm`
),
]);

customElements.define(
"py-terminal",
class extends HTMLElement {
#terminal;
#readline;
init(options) {
this.#readline = new Readline();
this.#terminal = new Terminal({
theme: {
background: "#191A19",
foreground: "#F5F2E7",
},
...options,
});
this.#terminal.loadAddon(this.#readline);
this.#terminal.open(this);
this.#terminal.focus();
}
readline(prompt) {
return this.#readline.read(prompt);
}
write(line) {
this.#readline.write(line);
}
},
);

const codeBefore = `
from pyscript import pyterminal as _pyterminal
_pyterminal.init()
`;

const codeAfter = `
from pyscript import pyterminal as _pyterminal

# avoid bootstrapping interact() if no terminal exists
if _pyterminal.PY_TERMINAL:
import code as _code
_code.interact()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a shame not to support top level await...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hoodmane not intentional ... and I am not sure what you are referring to. Mind to expand a bit? We do support top level await if the tag has an async attribute though, but I am trying to figure out what would be the benefit here ... or maybe you are referring to some missing field when interact(...) is called that would allow top level await within the repl?

Thanks in advance for any sort of clarification, please remember I know nothing about Python 😅

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, this has been discussed during yesterday community call, I am waiting for @hoodmane link/hint on how to workaround and enable the top level await if possible, thanks!

`;

const main = ({ io }) => {
const pt = document.querySelector("py-terminal");
if (pt) {
cleanUp(true);
pt.init({
disableStdin: true,
cursorBlink: false,
cursorStyle: "underline",
});
io.stdout = (value) => {
pt.write(`${value}\n`);
};
io.stderr = (error) => {
pt.write(`${error.message || error}\n`);
};
}
};

const thread = (_, xworker) => {
const pt = document.querySelector("py-terminal");
if (pt) {
cleanUp(false);
pt.init({
disableStdin: false,
cursorBlink: true,
cursorStyle: "block",
});
xworker.sync.pyterminal_readline = pt.readline.bind(pt);
xworker.sync.pyterminal_write = pt.write.bind(pt);
}
};

// we currently support only one <py-terminal>
const cleanUp = (fromMain) => {
hooks.onInterpreterReady.delete(main);
hooks.onWorkerReady.delete(thread);
if (fromMain) {
hooks.codeBeforeRunWorker.delete(codeBefore);
hooks.codeAfterRunWorker.delete(codeBefore);
}
};

hooks.onInterpreterReady.add(main);
hooks.onWorkerReady.add(thread);
hooks.codeBeforeRunWorker.add(codeBefore);
hooks.codeAfterRunWorker.add(codeAfter);
}
26 changes: 26 additions & 0 deletions pyscript.core/src/stdlib/pyscript/pyterminal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import builtins
import sys

import js
from pyscript import RUNNING_IN_WORKER, document, sync


class _PyTerminal:
def write(self, line):
sync.pyterminal_write(line)

def input(self, prompt):
return sync.pyterminal_readline(prompt)


PY_TERMINAL = None


def init():
global PY_TERMINAL
# we currently support only one terminal
# and it's interactive only within a worker tag
if not PY_TERMINAL and RUNNING_IN_WORKER and document.querySelector("py-terminal"):
PY_TERMINAL = _PyTerminal()
sys.stdout = sys.stderr = PY_TERMINAL
builtins.input = PY_TERMINAL.input
24 changes: 24 additions & 0 deletions pyscript.core/test/py-terminal.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PyTerminal</title>
<link rel="stylesheet" href="../dist/core.css">
<script type="module" src="../dist/core.js"></script>
<style>.xterm { padding: .5rem; }</style>
</head>
<body>
<script type="py" worker>
import sys
from pyscript import display
display("Hello", "PyScript Next - PyTerminal", append=False)
print("this should go to the terminal")
print("another line")

# this works as expected
print("this goes to stderr", file=sys.stderr)
</script>
<py-terminal></py-terminal>
</body>
</html>
7 changes: 4 additions & 3 deletions pyscript.core/types/plugins.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
declare namespace _default {
function error(): Promise<typeof import("./plugins/error.js")>;
}
declare const _default: {
error: () => Promise<typeof import("./plugins/error.js")>;
"py-terminal": () => Promise<typeof import("./plugins/py-terminal.js")>;
};
export default _default;
1 change: 1 addition & 0 deletions pyscript.core/types/plugins/py-terminal.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {};
1 change: 1 addition & 0 deletions pyscript.core/types/stdlib/pyscript.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ declare namespace _default {
"display.py": string;
"event_handling.py": string;
"magic_js.py": string;
"pyterminal.py": string;
"util.py": string;
};
let pyweb: {
Expand Down
0