Skip to content

Instantly share code, notes, and snippets.

@faizanbashir
Created April 1, 2023 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faizanbashir/2da33013c6ecc9220cf26076e42f3a75 to your computer and use it in GitHub Desktop.
Save faizanbashir/2da33013c6ecc9220cf26076e42f3a75 to your computer and use it in GitHub Desktop.
Running Python in the browser using WebAssembly and Pyodide
<!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