TL, DR
PyScript is a new and cool piece of technology that let you use Python in the browser. In this tutorial we will embed a PyScript REPL in a webpage. More tutorials on PyScript to come!
Embed a PyScript REPL in a webpage
Python is famous for running everywhere. Jupyter Notebooks enabled professionals and hobbyists to test and develop Python code in their browser. However, Jupyter still requires a server running a Python engine as backend.
Enter PyScript. This new piece of technology supported by the Anaconda team embeds Python straight into your browser without any server needed.
PyScript is based on Pyodide, which is a port of CPyhton to WebAssembly/Emscripten. This let us use the browser engine to run Python code.
There are a few caveats, since the browser is mostly suitable for running async code. So you’d better master async/await concepts to make the most out of it.
Keep in mind that PyScript is experimental and in Alpha status, so many things may break over time.
Creating your REPL
With only a few lines of code we can create a webpage with a PyScript REPL embedded and ready to use. Let’s see the overall picture:
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
- matplotlib
- imageio
- pandas
- numpy
</py-env>
<style>
ul {
list-style-type: circle;
list-style-position: outside;
margin: 20px;
padding: 5px;
}
h1 {
text-align: center;
font-family: Arial, Helvetica, sans-serif;
font-size: 40px;
}
</style>
</head>
<div>
<h1>PyScript REPL</h1>
<p>This webpage implements a REPL with PyScript.</p>
<p>The following packages have been loaded into the environment:</p>
<ul>
<li>matplotlib</li>
<li>imageio</li>
<li>pandas</li>
<li>numpy</li>
</ul>
<p>Output is displayed below the REPL box.</p>
</div>
<py-repl></py-repl>
</html>
There are a few steps that require some further explanation. Those lines in the head section source the PyScript code (yes, it’s a JavaScript file) and its style sheet.
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
This passage, still in the head section of our webpage, instead lists which packages we want to make available for PyScript:
<py-env>
- matplotlib
- imageio
- pandas
- numpy
</py-env>
Finally, those tags place the REPL code into the webpage:
<py-repl></py-repl>
That’s it, now you can render the page in your browser and experiment! I will publish further tutorials on PyScript, you can find them at this link (also reported below).
Related links
- More posts about PyScript link
- PyScript homepage link
- Pyodide homepage link
- Blog posts from John Hanley about PyScript link
- GitHub repo with PyScript examples link
Do you like our content? Check more of our posts in our blog!