Running Code
Once you have PyScript running on your page, you can start writing Python code inside a <script>
tag with the attribute type="py"
, which will then be executed when the page loads.
Info
Note that Python's print
function outputs to the browser's dev console. To output content to the screen, use PyScript's display function
A complete example of an HTML page which loads PyScript and runs some Python code (including some additional recommended HTML bits) might look like:
Once you have PyScript running on your page, you can start writing Python code inside a <script>
tag with the attribute type="mpy"
, which will then be executed when the page loads.
Info
Note that Python's print
function outputs to the browser's dev console. To output content to the screen, use PyScript's display function
A complete example of an HTML page which loads PyScript and runs some Python code (including some additional recommended HTML bits) might look like:
Once you have the Pyodide script included on your page, you can use the global loadPyodide() function in JavaScript to load the Pyodide runtime. Once loaded, the runtime can be used to execute Python code. Note that loadPyodide
is an async function, and so must be awaited within another async function in order to retrieve a reference to the runtime once it loads.
Once loaded, call the runPython()
method of the resulting runtime to execute Python code:
async function main() {
let pyodide = await loadPyodide();
// Pyodide is now ready to use...
console.log(pyodide.runPython(`
import sys
print(sys.version)
`));
};
main();
Info
Note that Python's print
function outputs to the browser's dev console.
A complete example of an HTML page with PyScript (including some additional recommended HTML bits) might look like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello, world!</title>
<script src="https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js"></script>
</head>
<body>
<script>
async function main() {
let pyodide = await loadPyodide();
// Pyodide is now ready to use...
console.log(pyodide.runPython(`
import sys
print(sys.version)
`));
};
main();
</script>
</body>
</html>