8000 Fix #1841 - Provide a better error when input is used (#1857) · shivashankarv/pyscript@48e3383 · GitHub
[go: up one dir, main page]

Skip to content

Commit 48e3383

Browse files
Fix pyscript#1841 - Provide a better error when input is used (pyscript#1857)
1 parent e750fa7 commit 48e3383

File tree

3 files changed

+48
-1
lines changed

3 files changed

+48
-1
lines changed

pyscript.core/src/hooks.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,19 @@ export const createFunction = (self, name) => {
4545
const SetFunction = typedSet({ typeof: "function" });
4646
const SetString = typedSet({ typeof: "string" });
4747

48+
const inputFailure = `
49+
import builtins
50+
def input(prompt=""):
51+
raise Exception("\\n ".join([
52+
"input() doesn't work when PyScript runs in the main thread.",
53+
"Consider using the worker attribute: https://docs.pyscript.net/2023.11.1/user-guide/workers/"
54+
]))
55+
56+
builtins.input = input
57+
del builtins
58+
del input
59+
`;
60+
4861
export const hooks = {
4962
main: {
5063
/** @type {Set<function>} */
@@ -60,7 +73,7 @@ export const hooks = {
6073
/** @type {Set<function>} */
6174
onAfterRunAsync: new SetFunction(),
6275
/** @type {Set<string>} */
63-
codeBeforeRun: new SetString(),
76+
codeBeforeRun: new SetString([inputFailure]),
6477
/** @type {Set<string>} */
6578
codeBeforeRunAsync: new SetString(),
6679
/** @type {Set<string>} */

pyscript.core/test/input.html

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>PyScript Next</title>
7+
<script>
8+
addEventListener("py:ready", console.log);
9+
</script>
10+
<link rel="stylesheet" href="../dist/core.css">
11+
<script type="module" src="../dist/core.js"></script>
12+
</head>
13+
<body>
14+
<py-script>
15+
input("what's your name?")
16+
</py-script>
17+
<mpy-script>
18+
input("what's your name?")
19+
</mpy-script>
20+
</body>
21+
</html>

pyscript.core/tests/integration/test_01_basic.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,19 @@ def test_print(self):
9393
)
9494
assert self.console.log.lines[-1] == "hello pyscript"
9595

96+
@only_main
97+
def test_input_exception(self):
98+
self.pyscript_run(
99+
"""
100+
<script type="py">
101+
input("what's your name?")
102+
</script>
103+
"""
104+
)
105+
self.check_py_errors(
106+
"Exception: input() doesn't work when PyScript runs in the main thread."
107+
)
108+
96109
@skip_worker("NEXT: exceptions should be displayed in the DOM")
97110
def test_python_exception(self):
98111
self.pyscript_run(

0 commit comments

Comments
 (0)
0