Created
April 1, 2023 16:28
-
-
Save faizanbashir/2da33013c6ecc9220cf26076e42f3a75 to your computer and use it in GitHub Desktop.
Running Python in the browser using WebAssembly and Pyodide
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Running Python in the browser using WebAssembly and Pyodide</title> | |
<script type="text/javascript" src="https://cdn.jsdelivr.net/pyodide/v0.23.0/full/pyodide.js"></script> | |
</head> | |
<body> | |
<h1>Calculate the square of a number using Python in WebAssembly</h1> | |
<input type="number" id="number" placeholder="Enter a number"> | |
<button id="calculate">Calculate</button> | |
<p id="result"></p> | |
<script> | |
async function main() { | |
let pyodide = await loadPyodide(); | |
console.log('Pyodide is ready to use!'); | |
// Load and run the Python code | |
pyodide.globals.set("square", x => x*x) | |
return pyodide | |
} | |
pyodide = main(); | |
const calculateButton = document.getElementById('calculate'); | |
const numberInput = document.getElementById('number'); | |
const resultElement = document.getElementById('result'); | |
calculateButton.addEventListener('click', () => { | |
const number = parseInt(numberInput.value); | |
const result = pyodide.runPython('square('+number+')'); | |
resultElement.textContent = `The square of ${number} is ${result}.`; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment