Using PyScript to Run Python in the Browser

By Raman Kumar

Updated on Dec 02, 2024

In this tutorial, we're using PyScript to run Python in the browser.

PyScript is a powerful framework that enables Python developers to write and execute Python code directly in the browser. By integrating seamlessly with HTML and JavaScript, PyScript opens a new realm of possibilities for creating web applications using Python.

This tutorial covers the installation, setup, and practical implementation of PyScript. We'll explore its features, write production-grade code, and discuss best practices for deploying PyScript-based applications.

What is PyScript?

PyScript is an open-source framework that allows Python scripts to be run in the browser using WebAssembly (via Pyodide). It provides Python developers with the ability to create interactive web applications without relying solely on JavaScript. PyScript supports Python libraries, integrates with HTML, and enables the use of Python’s rich ecosystem for web development.

Prerequisites

  • Basic understanding of Python and HTML.
  • Familiarity with web development concepts (optional but helpful).
  • A modern browser that supports WebAssembly (e.g., Chrome, Firefox).

Using PyScript to Run Python in the Browser

Step 1: Creating the Project Structure

Create a project directory with the following structure:

pyscript-tutorial/
├── index.html
└── styles.css

Step 2: Writing the HTML File

The core of PyScript lies in its integration with HTML. Let’s start by setting up index.html.

nano index.html

Add following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PyScript Tutorial</title>
    <link rel="stylesheet" href="styles.css">
    <!-- Include PyScript -->
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css">
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
    <header>
        <h1>Welcome to PyScript</h1>
        <p>Run Python in the Browser</p>
    </header>
    <main>
        <!-- PyScript Block -->
        <py-script>
            print("Hello, PyScript!")
        </py-script>
        
        <!-- Interactive Example -->
        <section>
            <h2>Interactive Python</h2>
            <py-repl></py-repl>
        </section>
        
        <!-- Fibonacci Calculator -->
        <section>
            <h2>Fibonacci Calculator</h2>
            <form id="fib-form">
                <label for="fib-input">Enter a number:</label>
                <input type="number" id="fib-input" min="1" placeholder="e.g., 10">
                <button type="button" id="fib-btn">Calculate</button>
            </form>
            <p id="fib-result"></p>
        </section>
    </main>
</body>
</html>

Step 3: Adding CSS for Styling

Style your application with styles.css:

nano styles.css

Add following code:

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f4f4f9;
    color: #333;
}

header {
    text-align: center;
    background-color: #008080;
    color: white;
    padding: 20px;
}

main {
    padding: 20px;
}

form {
    margin-bottom: 20px;
}

#fib-result {
    font-size: 1.2em;
    color: #008080;
    margin-top: 10px;
}

Writing Interactive Python Code

PyScript provides tags like <py-script> and <py-repl> for embedding Python code. Let’s implement a practical feature—a Fibonacci calculator.

Adding Python Logic in PyScript

Extend the PyScript block in your index.html:

<py-script>
from js import document

def calculate_fibonacci(n):
    if n <= 0:
        return "Please enter a positive integer."
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    fib_sequence = [0, 1]
    while len(fib_sequence) < n:
        fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
    return fib_sequence

# Handle button click
def on_click(event):
    input_field = document.querySelector("#fib-input")
    result_field = document.querySelector("#fib-result")
    try:
        n = int(input_field.value)
        result = calculate_fibonacci(n)
        result_field.textContent = f"Fibonacci Sequence: {result}"
    except ValueError:
        result_field.textContent = "Please enter a valid number."

# Bind the event listener
button = document.querySelector("#fib-btn")
button.addEventListener("click", on_click)
</py-script>

Explanation of the Code

  • Python Functions: calculate_fibonacci computes the Fibonacci sequence for a given number.
  • JavaScript Integration: Using js.document, we interact with HTML elements and handle user input/output.
  • Event Binding: The on_click function is tied to the button’s click event to trigger the calculation.

Running the Application

1. Open index.html in a browser.

2. Interact with the application:

  • Test the embedded Python script (print output in the console).
  • Use the <py-repl> to run arbitrary Python commands.
  • Input a number in the Fibonacci calculator and click Calculate.

Best Practices for PyScript

  • Optimize Performance: Limit complex calculations in the browser. Use server-side computation for heavy tasks.
  • Use Python Libraries: PyScript supports many Python libraries (e.g., NumPy, Pandas). Test compatibility before deployment.
  • Debugging: Use browser developer tools to debug PyScript and JavaScript interactions.
  • Browser Compatibility: Ensure your app works on modern browsers.

Advantages and Limitations of PyScript

Advantages

  • Enables Python use in web development.
  • Leverages Python's rich ecosystem.
  • Simplifies creating interactive educational tools and demos.

Limitations

  • Performance is constrained by WebAssembly.
  • Limited access to Python's native features requiring OS-level support.

Conclusion

In this tutorial, we'ved used PyScript to run Python in the browser. PyScript bridges the gap between Python and the web, empowering developers to build interactive browser-based applications. By following this tutorial, you’ve created a robust application and learned the essentials of integrating Python with HTML using PyScript. Experiment with PyScript to explore its potential in education, data visualization, and prototyping.

Checkout our instant dedicated servers and Instant KVM VPS plans.