### Install project dependencies Source: https://docs.pyscript.net/2026.3.1/developers Sets up the environment and installs required software packages. ```bash make setup ``` -------------------------------- ### Event Handling Examples Source: https://docs.pyscript.net/2026.3.1/api/events Comprehensive examples covering DOM event binding, custom event listeners, and decorator usage. ```python from pyscript import when, display # Handle DOM events. @when("click", "#my-button") def handle_click(event): display("Button clicked!") # Handle DOM events with options. @when("click", "#my-button", once=True) def handle_click_once(event): display("Button clicked once!") # Handle custom events. my_event = Event() @when(my_event) def handle_custom(): # No event argument needed. display("Custom event triggered!") # Handle multiple custom events. another_event = Event() def another_handler(): display("Another custom event handler.") # Attach the same handler to multiple events but not as a decorator. when([my_event, another_event])(another_handler) # Trigger an Event instance from a DOM event via @when. @when("click", "#my-button") def handle_click(event): another_event.trigger("Button clicked!") # Stacked decorators also work. @when("mouseover", "#my-div") @when(my_event) def handle_both(event): display("Either mouseover or custom event triggered!") ``` -------------------------------- ### Perform network requests with fetch Source: https://docs.pyscript.net/2026.3.1/api/fetch Examples of simple GET requests, method chaining, and POST requests with JSON bodies. ```python # Simple GET request. response = await fetch("https://api.example.com/data") data = await response.json() # Method chaining. data = await fetch("https://api.example.com/data").json() # POST request with JSON. response = await fetch( "https://api.example.com/users", method="POST", headers={"Content-Type": "application/json"}, body=json.dumps({"name": "Alice"}) ) result = await response.json() # Check response status codes. response = await fetch("https://api.example.com/data") if response.ok: # Status in the range 200-299. data = await response.json() elif response.status == 404: print("Resource not found") else: print(f"Error: {response.status} {response.statusText}") ``` -------------------------------- ### Editor Setup Attribute Source: https://docs.pyscript.net/2026.3.1/user-guide/editor Use the 'setup' attribute for boilerplate code that runs automatically but isn't visible. Setup editors execute before any other editors in the same environment. ```html ``` -------------------------------- ### Basic Storage Usage Source: https://docs.pyscript.net/2026.3.1/api/storage Demonstrates opening a storage, setting and getting items, iterating, and ensuring writes complete immediately. ```python from pyscript import storage # Open a storage. prefs = await storage("preferences") # Use as a dictionary. prefs["color"] = "blue" prefs["count"] = 42 # Iterate like a dict. for key, value in prefs.items(): print(f"{key}: {value}") # Ensure writes complete immediately. await prefs.sync() ``` -------------------------------- ### Install Pyodide locally Source: https://docs.pyscript.net/2026.3.1/user-guide/offline Download the Pyodide package via npm and prepare the target directory. ```bash # Install Pyodide. npm i pyodide # Create target directory. mkdir -p public/pyodide ``` -------------------------------- ### Run PyScript examples with Python Source: https://docs.pyscript.net/2026.3.1/example-apps/overview Use a standard Python HTTP server to host and run self-contained PyScript applications. ```bash # Navigate to the example directory. cd example_apps/pirate-translator # Serve with any web server. python -m http.server 8000 # Visit http://localhost:8000 in your browser. ``` -------------------------------- ### Install MicroPython locally Source: https://docs.pyscript.net/2026.3.1/user-guide/offline Download the MicroPython WebAssembly package via npm and copy the necessary files to the public directory. ```bash # Install the MicroPython package. npm i @micropython/micropython-webassembly-pyscript # Create target directory. mkdir -p public/micropython # Copy interpreter files. cp node_modules/@micropython/micropython-webassembly-pyscript/micropython.* public/micropython/ ``` -------------------------------- ### Define a typical PyScript configuration Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration A complete example of a JSON configuration file defining packages, files, and JS modules. ```json { "packages": [ "numpy", "matplotlib" ], "files": { "https://example.com/data.csv": "./data.csv", "./utils.py": "./lib/utils.py" }, "js_modules": { "main": { "https://cdn.jsdelivr.net/npm/chart.js": "chartjs" } } } ``` -------------------------------- ### Precise Frame Timing with PyGame Source: https://docs.pyscript.net/2026.3.1/user-guide/pygame-ce This example demonstrates precise frame timing by synchronizing with the display refresh rate using `requestAnimationFrame` in the browser and `vsync=1` locally. It separates setup from the game loop and uses delta time for frame-rate independence. ```python import sys import pygame pygame.init() size = width, height = 320, 240 speed = pygame.Vector2(150, 150) black = 0, 0, 0 screen = pygame.display.set_mode(size, vsync=1) ball = pygame.image.load("intro_ball.gif") ballrect = ball.get_rect() clock = pygame.time.Clock() def run_one_frame(): """ Execute one frame of the game. """ for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # Delta time for frame-rate independence. dt = clock.tick(300) / 1000 ballrect.move_ip(speed * dt) # Bounce logic... if ballrect.left < 0 or ballrect.right > width: speed.x = -speed.x if ballrect.top < 0 or ballrect.bottom > height: speed.y = -speed.y screen.fill(black) screen.blit(ball, ballrect) pygame.display.flip() # Browser: use requestAnimationFrame. try: from pyscript import window, ffi def on_animation_frame(timestamp): """ Called by browser for each frame. """ run_one_frame() window.requestAnimationFrame(raf_proxy) raf_proxy = ffi.create_proxy(on_animation_frame) on_animation_frame(0) except ImportError: # Local: use while loop with vsync. while True: run_one_frame() ``` -------------------------------- ### Run PyScript examples with web-worker requirements Source: https://docs.pyscript.net/2026.3.1/example-apps/overview Use the mini-coi command to serve applications that require specific headers for web-worker functionality. ```bash # Navigate to the worker-related project. cd example_apps/prime-worker # Serve the app with the correct headers. npx mini-coi . # Visit http://localhost:8080/ in your browser. ``` -------------------------------- ### Start PyScript with a Script Tag Source: https://docs.pyscript.net/2026.3.1 Use this script tag in the `` of your HTML document to initialize PyScript and load your Python code. ```html ``` -------------------------------- ### Define packages in configuration Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration Specifies required Python packages to be installed from PyPI. ```toml packages = ["arrr", "numberwang" ] ``` ```json { "packages": ["arrr", "numberwang"] } ``` -------------------------------- ### Fetch files onto the filesystem with TOML Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration Use the 'files' option in TOML format to map URLs to destination filesystem paths. This configuration achieves the same result as the JSON example for fetching arbitrary content. ```toml [files] "https://example.com/data.csv" = "./data.csv" "./code.py" = "./subdir/code.py" ``` -------------------------------- ### Install Python Packages with `micropip` Source: https://docs.pyscript.net/2026.3.1/faq Install pure Python packages from PyPI using the `micropip` module within your PyScript application. Ensure the package is compatible with the browser environment. ```python import micropip await micropip.install("pillow") ``` -------------------------------- ### PyScript FS Module Overview Source: https://docs.pyscript.net/2026.3.1/api/fs Overview of the pyscript.fs module, its purpose, and usage examples for mounting, syncing, and unmounting local directories. ```APIDOC ## PyScript FS Module Overview This module provides an API for mounting directories from the user's local filesystem into the browser's virtual filesystem. This means Python code, running in the browser, can read and write files on the user's local machine. **Warning**: This API only works in Chromium-based browsers (Chrome, Edge, Vivaldi, Brave, etc.) that support the File System Access API. ### Core Functionality - **Mounting**: Allows Python code to access local directories. - **File Operations**: Read and write files within mounted directories. - **Synchronization**: Ensures changes are written to the local filesystem. - **Unmounting**: Cleans up mounted directory access. ### Code Examples ```python from pyscript import fs, document, when # Mount a local directory to the `/local` mount point. await fs.mount("/local") # Mount on a button click event. @when("click", "#mount-button") async def handler(event): await fs.mount("/another_dir") # Work with files in the mounted directory. with open("/local/example.txt", "w") as f: f.write("Hello from PyScript!") # Ensure changes are written to local filesystem. await fs.sync("/local") # Clean up when done. await fs.unmount("/local") ``` ``` -------------------------------- ### Reference PyScript Versions Source: https://docs.pyscript.net/2026.3.1/faq Examples of linking specific production versions versus the latest development version of PyScript. ```html ``` -------------------------------- ### Download PyScript core via npm Source: https://docs.pyscript.net/2026.3.1/user-guide/offline Use npm to install the PyScript core package and copy the distribution files into a local public directory. ```bash # Create your project directory. mkdir pyscript-offline cd pyscript-offline # Create a package.json file. echo '{}' > package.json # Install PyScript core. npm i @pyscript/core # Copy distribution files to your public directory. mkdir -p public cp -R node_modules/@pyscript/core/dist public/pyscript ``` -------------------------------- ### Implement a lifecycle logging plugin Source: https://docs.pyscript.net/2026.3.1/user-guide/plugins A complete plugin example that registers hooks for both main and worker threads to log lifecycle events. ```javascript // Import hooks from PyScript. import { hooks } from "https://pyscript.net/releases/2026.3.1/core.js"; // Register main thread hooks. hooks.main.onReady.add((wrap, element) => { console.log("main: interpreter ready"); if (location.search === '?debug') { console.debug("wrap:", wrap); console.debug("element:", element); } }); hooks.main.onBeforeRun.add(() => { console.log("main: about to run code"); }); hooks.main.codeBeforeRun.add('print("main: injected before")'); hooks.main.codeAfterRun.add('print("main: injected after")'); hooks.main.onAfterRun.add(() => { console.log("main: finished running code"); }); // Register worker hooks. hooks.worker.onReady.add((wrap, xworker) => { console.log("worker: interpreter ready"); if (location.search === '?debug') { console.debug("wrap:", wrap); console.debug("xworker:", xworker); } }); hooks.worker.onBeforeRun.add(() => { console.log("worker: about to run code"); }); hooks.worker.codeBeforeRun.add('print("worker: injected before")'); hooks.worker.codeAfterRun.add('print("worker: injected after")'); hooks.worker.onAfterRun.add(() => { console.log("worker: finished running code"); }); ``` -------------------------------- ### ElementCollection Usage Examples Source: https://docs.pyscript.net/2026.3.1/api/web Demonstrates common operations on an ElementCollection, including indexing, slicing, iteration, and bulk updates. ```python # Get a collection of elements. items = web.page.find(".item") # Access by index. first = items[0] last = items[-1] # Slice the collection. subset = items[1:3] # Look up a specific element by id (returns None if not found). specific = items["item-id"] # Iterate over elements. for item in items: item.innerHTML = "Updated" item.classes.add("processed") # Bulk update all contained elements. items.update_all(innerHTML="Hello", className="updated") # Find matches within the collection. buttons = items.find("button") # Get the count. count = len(items) ``` -------------------------------- ### Start an interactive REPL Source: https://docs.pyscript.net/2026.3.1/user-guide/terminal Utilize the Python code module to launch a full interactive REPL session within the terminal. ```python import code code.interact() ``` -------------------------------- ### Mount Local Directory with Different Modes and Options in PyScript Source: https://docs.pyscript.net/2026.3.1/api/fs Shows how to mount a local directory using `fs.mount` with various options. You can specify read-only access, provide a hint for the starting directory in the file picker, or use an ID for multiple mounts at the same path. ```python from pyscript import fs # Basic mount with default settings. await fs.mount("/local") # Mount with read-only access. await fs.mount("/readonly", mode="read") # Mount with a hint to start in Downloads folder. await fs.mount("/downloads", root="downloads") ``` -------------------------------- ### Mount Directory with Root Hint Source: https://docs.pyscript.net/2026.3.1/api/fs Mounts a local directory to a specified path in the virtual filesystem, providing a hint for the file picker's starting location. This can improve user experience by pre-selecting a common directory. ```python await fs.mount("/downloads", root="downloads") ``` -------------------------------- ### Use configured resources in Python Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration Access installed packages, read local files, and import JS modules within a PyScript application. ```python import numpy as np from pyscript import display # Use installed packages. data = np.array([1, 2, 3, 4, 5]) display(f"Mean: {data.mean()}") # Read configured files. with open("data.csv") as f: display(f"Data: {f.read()[:100]}") # Use JavaScript modules. from pyscript.js_modules import chartjs display("Chart.js loaded!") ``` -------------------------------- ### Using the template language in JSON Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration The 'files' option supports a mini-templating language using curly brackets for placeholders. This example defines placeholders for domain, path, and version to construct source and destination paths, reducing repetition when copying multiple files. ```json { "files": { "{DOMAIN}": "https://my-server.com", "{PATH}": "a/path", "{VERSION}": "1.2.3", "{FROM}": "{DOMAIN}/{PATH}/{VERSION}", "{TO}": "./my_module", "{FROM}/__init__.py": "{TO}/__init__.py", "{FROM}/foo.py": "{TO}/foo.py", "{FROM}/bar.py": "{TO}/bar.py", "{FROM}/baz.py": "{TO}/baz.py" } } ``` -------------------------------- ### Get element attributes Source: https://docs.pyscript.net/2026.3.1/api/web Retrieves attributes from the DOM element, or returns an Event instance if the attribute name starts with 'on_'. ```python def __getattr__(self, name): """ Get an attribute from the element. Attributes starting with `on_` return `Event` instances. Other attributes are retrieved from the underlying DOM element. """ if name.startswith("on_"): return self.get_event(name) dom_name = self._normalize_attribute_name(name) return getattr(self._dom_element, dom_name) ``` -------------------------------- ### Initialize and use a WebSocket connection Source: https://docs.pyscript.net/2026.3.1/api/websocket Demonstrates setting up a WebSocket connection with event handlers for open, message, and close events. ```python from pyscript import WebSocket def on_open(event): print("Connected!") ws.send("Hello server") def on_message(event): print(f"Received: {event.data}") def on_close(event): print("Connection closed") ws = WebSocket(url="ws://localhost:8080/") ws.onopen = on_open ws.onmessage = on_message ws.onclose = on_close ``` -------------------------------- ### Start Worker from Main Thread Source: https://docs.pyscript.net/2026.3.1/example-apps/prime-worker/info Get a reference to a worker defined in HTML from the main thread. The worker name corresponds to the script tag's type attribute. ```python # Main thread gets reference to worker defined in HTML. from pyscript import workers worker = await workers.py # Name from script tag's type. ``` -------------------------------- ### Retrieve and list media devices Source: https://docs.pyscript.net/2026.3.1/api/media Demonstrates importing list_devices, awaiting the result, and iterating through the returned device objects. ```python from pyscript.media import list_devices # Get all devices. devices = await list_devices() # Print device information. for device in devices: print(f"{device.kind}: {device.label} (ID: {device.id})") # Filter for specific device types. cameras = [d for d in devices if d.kind == "videoinput"] microphones = [d for d in devices if d.kind == "audioinput"] speakers = [d for d in devices if d.kind == "audiooutput"] ``` -------------------------------- ### Serve application locally Source: https://docs.pyscript.net/2026.3.1/user-guide/offline Use a simple Python HTTP server to host the local public directory. ```bash python3 -m http.server -d public/ ``` -------------------------------- ### GET /get_stream Source: https://docs.pyscript.net/2026.3.1/api/media Get a media stream from a specific device. This method is called on a Device instance. ```APIDOC ## GET /get_stream ### Description Get a media stream from this specific device. This will trigger a permission dialog if the user hasn't already granted permission for this device type. ### Method GET ### Endpoint /get_stream ### Parameters This method does not take any explicit parameters, but it uses the device's properties (`kind` and `id`) to request a stream. ### Request Example ```python # Assuming 'my_camera' is a Device object stream = await my_camera.get_stream() ``` ### Response #### Success Response (200) - **stream** (MediaStream) - The requested media stream object. ``` -------------------------------- ### Device Initialization and Access Source: https://docs.pyscript.net/2026.3.1/api/media How to initialize a Device object and access its properties, including support for JavaScript interop. ```APIDOC ### `__init__(device)` Create a Device wrapper around a MediaDeviceInfo `device`. Source code in `pyscript/media.py` ```python def __init__(self, device): """ Create a Device wrapper around a MediaDeviceInfo `device`. """ self._device_info = device ``` ### `__getitem__(key)` Support bracket notation for JavaScript interop. Allows accessing properties via `device["id"]` syntax. Necessary when Device instances are proxied to JavaScript. Source code in `pyscript/media.py` ```python def __getitem__(self, key): """ Support bracket notation for JavaScript interop. Allows accessing properties via `device["id"]` syntax. Necessary when Device instances are proxied to JavaScript. """ return getattr(self, key) ``` ``` -------------------------------- ### Storage.__init__ Source: https://docs.pyscript.net/2026.3.1/api/storage Initializes a Storage instance, wrapping an IndexedDB store. ```APIDOC ## Storage.__init__(store) ### Description Create a Storage instance wrapping an IndexedDB `store` (a JS proxy). ### Parameters #### Path Parameters - **store** (object) - Required - A JavaScript proxy object representing the IndexedDB store. ``` -------------------------------- ### Initialize WebSocket with URL and Protocols Source: https://docs.pyscript.net/2026.3.1/api/websocket Create a WebSocket instance specifying the connection URL and an array of supported protocols. This constructor is used when initiating a new WebSocket connection. ```python if protocols: js_websocket = js.WebSocket.new(url, protocols) else: js_websocket = js.WebSocket.new(url) # Set binary type to arraybuffer for easier Python handling. js_websocket.binaryType = "arraybuffer" # Store the underlying WebSocket. # Use object.__setattr__ to bypass our custom __setattr__. object.__setattr__(self, "_js_websocket", js_websocket) # Attach any event handlers passed as keyword arguments. for handler_name, handler in handlers.items(): setattr(self, handler_name, handler) ``` -------------------------------- ### PyScript Fetch: Simple GET Request Source: https://docs.pyscript.net/2026.3.1/api/fetch Performs a simple GET request to a specified URL and retrieves JSON data from the response. This is a basic usage pattern for fetching data. ```python # Simple GET request. response = await fetch("https://api.example.com/data") data = await response.json() ``` -------------------------------- ### Page Title Property Source: https://docs.pyscript.net/2026.3.1/api/web Allows getting and setting the page's title. ```APIDOC ## Page Title ### Description Get or set the page `title`. ### Property - **title** (string) - The title of the web page. ### Example Usage ```python # Get the current title current_title = web.page.title # Set a new title web.page.title = "My New Page Title" ``` ``` -------------------------------- ### Get Stream from Specific Device Source: https://docs.pyscript.net/2026.3.1/api/media Retrieves a media stream from a specific media device. ```APIDOC ## POST /api/devices/{deviceId}/stream ### Description Gets a media stream from a specific device. This will trigger a permission dialog if the user hasn't already granted permission for this device type. ### Method POST ### Endpoint /api/devices/{deviceId}/stream ### Parameters #### Path Parameters - **deviceId** (string) - Required - The unique identifier of the device. ### Request Example ```json { "deviceId": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ### Response #### Success Response (200) - **MediaStream** (object) - A MediaStream object from the specified device. #### Response Example ```json { "stream": "[MediaStream Object]" } ``` ``` -------------------------------- ### Accessing and Filtering Media Devices Source: https://docs.pyscript.net/2026.3.1/api/media Demonstrates how to list all available media devices and filter them to identify specific hardware like cameras. ```python if cameras: stream = await cameras[0].get_stream() ``` ```python from pyscript.media import list_devices # Get all available devices. devices = await list_devices() # Find video input devices (cameras). cameras = [d for d in devices if d.kind == "videoinput"] # Get a stream from a specific camera. if cameras: stream = await cameras[0].get_stream() ``` -------------------------------- ### JSON Packages List Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration Use this format to specify Python packages to be installed when using JSON configuration. ```json { "packages": ["arrr", "numberwang", "snowballstemmer>=2.2.0" ] } ``` -------------------------------- ### TOML Packages List Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration Use this format to specify Python packages to be installed when using TOML configuration. ```toml packages = ["arrr", "numberwang", "snowballstemmer>=2.2.0" ] ``` -------------------------------- ### List Available Media Devices in Python Source: https://docs.pyscript.net/2026.3.1/user-guide/media Discover all media devices available on the user's system. Device labels might be empty until user permission is granted. ```python from pyscript.media import list_devices # Get all available media devices. devices = await list_devices() for device in devices: print(f"{device.kind}: {device.label}") ``` -------------------------------- ### Worker Deadlock Example Source: https://docs.pyscript.net/2026.3.1/faq Demonstrates a circular dependency where the worker and main thread wait for each other, causing a deadlock. ```python from pyscript import sync sync.worker_task = lambda: print('🔥 this is fine 🔥') # Deadlock occurs here. 💀🔒 sync.main_task() ``` ```html ``` -------------------------------- ### Initialize Classes Source: https://docs.pyscript.net/2026.3.1/api/web Constructor for the Classes class. ```python def __init__(self, element): """ Initialise the CSS Classes set for the given element. """ self._class_list = element._dom_element.classList super().__init__(self._class_list) ``` -------------------------------- ### Getting a Stream from a Specific Device Source: https://docs.pyscript.net/2026.3.1/api/media Retrieve a media stream from a specific hardware device identified by listing available devices. ```python from pyscript.media import list_devices # List all devices. devices = await list_devices() # Find a specific camera. my_camera = None for device in devices: if device.kind == "videoinput" and "USB" in device.label: my_camera = device break # Get a stream from that specific camera. if my_camera: stream = await my_camera.get_stream() ``` -------------------------------- ### Mount and Manage Local Filesystem Source: https://docs.pyscript.net/2026.3.1/user-guide/filesystem Basic workflow for mounting a directory, performing file operations, syncing changes, and unmounting. ```python # virtual filesystem to which the user-selected directory will be # mounted. await fs.mount("/local") # Do file related operations here. with open("/local/data.txt", "w") as f: f.write("Hello from PyScript!") # Ensure changes are persisted to the local filesystem's folder. await fs.sync("/local") # If needed, sync and unmount to free RAM. await fs.unmount("/local") ``` -------------------------------- ### Requesting Media Streams with Constraints Source: https://docs.pyscript.net/2026.3.1/api/media Shows how to request access to media devices using simple boolean flags or complex constraint dictionaries, and how to attach the resulting stream to a DOM element. ```python from pyscript import document from pyscript.media import Device # Get default video stream. stream = await Device.request_stream() # Get stream with specific constraints. stream = await Device.request_stream( video={"width": 1920, "height": 1080} ) # Get audio and video. stream = await Device.request_stream(audio=True, video=True) # Use the stream. video_el = document.getElementById("camera") video_el.srcObject = stream ``` -------------------------------- ### Build PyScript core from source Source: https://docs.pyscript.net/2026.3.1/user-guide/offline Clone the repository and build the distribution files manually for development or customization purposes. ```bash # Clone the repository. git clone https://github.com/pyscript/pyscript.git cd pyscript # Follow build instructions from the developer guide. # Once built, copy the dist folder. cp -R dist ../pyscript-offline/public/pyscript ``` -------------------------------- ### PyScript Filesystem Access Pattern Source: https://docs.pyscript.net/2026.3.1/example-apps/note-taker/info Demonstrates the core pattern for interacting with the local filesystem: mounting a directory, writing files, and syncing changes to persist them. Ensure the browser supports the File System Access API. ```python # Mount (user selects folder). await fs.mount("/notes") # Write files. with open("/notes/my-note.txt", "w") as f: f.write(note_text) # Sync to persist changes. await fs.sync("/notes") ``` -------------------------------- ### PyScript Media Module Overview Source: https://docs.pyscript.net/2026.3.1/api/media This snippet demonstrates the basic usage of the pyscript.media module, including requesting a video stream and listing available devices. ```APIDOC ## PyScript Media Module ### Description This module provides classes and functions for interacting with media devices and streams in the browser, enabling you to work with cameras, microphones, and other media input/output devices directly from Python. Use this module for: * Accessing webcams for video capture. * Recording audio from microphones. * Enumerating available media devices. * Applying constraints to media streams (resolution, frame rate, etc.). ### Requesting a Video Stream and Listing Devices ```python from pyscript import document from pyscript.media import Device, list_devices # Get a video stream from the default camera. stream = await Device.request_stream(video=True) # Display in a video element. video = document.getElementById("my-video") video.srcObject = stream # Or list all available devices. devices = await list_devices() for device in devices: print(f"{device.kind}: {device.label}") ``` ### Important Note Using media devices requires user permission. Browsers will show a permission dialog when accessing devices for the first time. ``` -------------------------------- ### Python NameError Example Source: https://docs.pyscript.net/2026.3.1/faq This traceback shows a NameError, indicating that a variable or function was used before it was defined. Check your variable names and definitions. ```python Traceback (most recent call last): File "/lib/python311.zip/_pyodide/_base.py", line 501, in eval_code .run(globals, locals) ^^^^^^^^^^^^^^^^^^^^ File "/lib/python311.zip/_pyodide/_base.py", line 339, in run coroutine = eval(self.code, globals, locals) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "", line 1, in NameError: name 'failure' is not defined ``` ```python Traceback (most recent call last): File "", line 1, in NameError: name 'failure' isn't defined ``` -------------------------------- ### Mount, Write, Sync, and Unmount Local Directory in PyScript Source: https://docs.pyscript.net/2026.3.1/api/fs Demonstrates mounting a local directory, writing to a file, synchronizing changes, and unmounting. Ensure the mount operation is triggered by a user event like a button click to avoid issues with browser permission prompts. ```python from pyscript import fs, document, when # Mount a local directory to the `/local` mount point in the browser's # virtual filesystem (may prompt user for permission). await fs.mount("/local") # Alternatively, mount on a button click event. This is important because # if the call to `fs.mount` happens after a click or other transient event, # the confirmation dialog will not be shown. @when("click", "#mount-button") async def handler(event): await fs.mount("/another_dir") # Work with files in the mounted directory as usual. with open("/local/example.txt", "w") as f: f.write("Hello from PyScript!") # Ensure changes are written to local filesystem. await fs.sync("/local") # Clean up when done. await fs.unmount("/local") ``` -------------------------------- ### Initialize persistent storage Source: https://docs.pyscript.net/2026.3.1/api/storage Opens or creates a persistent storage instance by name. Returns a dictionary-like object. ```python from pyscript import storage # Basic usage. user_data = await storage("user-profile") user_data["name"] = "Alice" user_data["age"] = 30 # Multiple independent storages. settings = await storage("app-settings") cache = await storage("api-cache") ``` -------------------------------- ### Retrieve event instances with get_event Source: https://docs.pyscript.net/2026.3.1/api/web Fetches or creates an Event instance for a given event name, ensuring the name starts with 'on_'. ```python def get_event(self, name): """ Get an `Event` instance for the specified event name. Event names must start with `on_` (e.g. `on_click`). Creates and caches `Event` instances that are triggered when the DOM event fires. """ if not name.startswith("on_"): raise ValueError("Event names must start with 'on_'.") event_name = name[3:] # Remove 'on_' prefix. if not hasattr(self._dom_element, event_name): raise ValueError(f"Element has no '{event_name}' event.") if name in self._on_events: return self._on_events[name] # Create Event instance and wire it to the DOM event. ev = Event() self._on_events[name] = ev self._dom_element.addEventListener(event_name, create_proxy(ev.trigger)) return ev ``` -------------------------------- ### Container Element Initialization Source: https://docs.pyscript.net/2026.3.1/api/web Documentation for the __init__ method of the container element class. ```APIDOC ## __init__(*args, children=None, dom_element=None, style=None, classes=None, **kwargs) ### Description Create a container element with optional children. Children can be passed as positional arguments or via the children keyword argument. String children are inserted as unescaped HTML. ### Parameters - **args** (list) - Optional - Positional children elements. - **children** (list) - Optional - List of children elements. - **dom_element** (object) - Optional - The underlying DOM element. - **style** (dict) - Optional - CSS styles to apply. - **classes** (list) - Optional - CSS classes to apply. - **kwargs** (dict) - Optional - Additional attributes passed to the base Element initializer. ``` -------------------------------- ### __getattr__ Source: https://docs.pyscript.net/2026.3.1/api/web Retrieves an attribute from the element. Attributes starting with 'on_' return Event instances, while others are fetched from the underlying DOM element. ```APIDOC ## __getattr__(name) ### Description Get an attribute from the element. Attributes starting with `on_` return `Event` instances. Other attributes are retrieved from the underlying DOM element. ### Method Instance Method ### Parameters #### Path Parameters - **name** (str) - Required - The name of the attribute to retrieve. ### Request Example ```json { "name": "id" } ``` ```json { "name": "on_click" } ``` ### Response #### Success Response (200) - **any** (any) - The value of the attribute. ### Response Example ```json { "attribute_value": "my-element-id" } ``` ```json { "event_handler": "" } ``` ``` -------------------------------- ### Implement list_devices function Source: https://docs.pyscript.net/2026.3.1/api/media The internal implementation of list_devices using window.navigator.mediaDevices.enumerateDevices. ```python async def list_devices(): """ Returns a list of all media devices currently available to the browser, such as microphones, cameras, and speakers. ```python from pyscript.media import list_devices # Get all devices. devices = await list_devices() # Print device information. for device in devices: print(f"{device.kind}: {device.label} (ID: {device.id})") # Filter for specific device types. cameras = [d for d in devices if d.kind == "videoinput"] microphones = [d for d in devices if d.kind == "audioinput"] speakers = [d for d in devices if d.kind == "audiooutput"] ``` The returned list will omit devices that are blocked by the document [Permission Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Permissions_Policy) (microphone, camera, speaker-selection) or for which the user has not granted explicit permission. For security and privacy, device labels may be empty strings until permission is granted. See [this document](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices) for more information about this web standard. """ device_infos = await window.navigator.mediaDevices.enumerateDevices() return [Device(device_info) for device_info in device_infos] ``` -------------------------------- ### Write Files to Virtual Filesystem Source: https://docs.pyscript.net/2026.3.1/faq Demonstrates how to create and write content to files within PyScript's in-memory virtual filesystem. These files can then be made available for download. ```python with open("output.txt", "w") as f: f.write("Hello, world!") ``` -------------------------------- ### Custom Storage with Logging Source: https://docs.pyscript.net/2026.3.1/api/storage Shows how to subclass `Storage` to add custom behavior, such as logging set operations to the console. ```python from pyscript import storage, Storage, window class LoggingStorage(Storage): def __setitem__(self, key, value): window.console.log(f"Setting {key} = {value}") super().__setitem__(key, value) my_store = await storage("app-data", storage_class=LoggingStorage) my_store["test"] = 123 # Logs to console. ``` -------------------------------- ### Request Specific Media Stream Types in Python Source: https://docs.pyscript.net/2026.3.1/user-guide/media Specify whether to request audio, video, or both. By default, `request_stream` attempts to get video. ```python # Video only (default). video_stream = await Device.request_stream(video=True) # Audio only. audio_stream = await Device.request_stream(audio=True, video=False) # Both audio and video. av_stream = await Device.request_stream(audio=True, video=True) ``` -------------------------------- ### Configure PyScript Editor with Packages Source: https://docs.pyscript.net/2026.3.1/user-guide/editor Use the 'config' attribute in a script tag to specify packages for the editor. This example includes the 'numpy' package. ```html ``` -------------------------------- ### Configure experimental_create_proxy Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration Enable automatic proxy handling for Pyodide using TOML or JSON configuration. ```toml experimental_create_proxy = "auto" ``` ```json { "experimental_create_proxy": "auto" } ``` -------------------------------- ### Create a Pyodide Worker with Packages Source: https://docs.pyscript.net/2026.3.1/api/workers Create a Pyodide worker and specify additional Python packages to be installed in the worker's environment. The config can be a dictionary or a JSON string. ```python # Create with standard PyScript configuration. worker = await create_named_worker( src="./processor.py", name="data-processor", config={"packages": ["numpy", "pandas"]} ) ``` -------------------------------- ### Initialize PyScript in HTML Head Source: https://docs.pyscript.net/2026.3.1/beginning-pyscript Include the required PyScript CSS and module script tags within the document head. ```html 🦜 Polyglot - Piratical PyScript ``` -------------------------------- ### Get HTML Tag Name from Class Source: https://docs.pyscript.net/2026.3.1/api/web The `get_tag_name` class method determines the HTML tag name for an element class by removing any trailing underscore from the class name. ```python @classmethod def get_tag_name(cls): """ Get the HTML tag name for this class. Classes ending with underscore (e.g. `input_`) have it removed to get the actual HTML tag name. """ return cls.__name__.replace("_", "") ``` -------------------------------- ### Get Current Output Target Source: https://docs.pyscript.net/2026.3.1/api/context Retrieve the current output target within the main thread context. This function accesses the globally defined target for PyScript outputs. ```python def current_target(): """ Get the current output target in main thread context. """ return _pyscript.target ``` -------------------------------- ### Initialize and Use PyScript Storage Source: https://docs.pyscript.net/2026.3.1/api/storage Open persistent storage instances and perform dictionary-like operations. Storage names are automatically namespaced with @pyscript/. ```python from pyscript import storage # Basic usage. user_data = await storage("user-profile") user_data["name"] = "Alice" user_data["age"] = 30 # Multiple independent storages. settings = await storage("app-settings") cache = await storage("api-cache") # With custom Storage class. class ValidatingStorage(Storage): def __setitem__(self, key, value): if not isinstance(key, str): raise TypeError("Keys must be strings") super().__setitem__(key, value) validated = await storage("validated-data", ValidatingStorage) ``` -------------------------------- ### Basic Python Editor Usage Source: https://docs.pyscript.net/2026.3.1/user-guide/editor Create a visual code editor with syntax highlighting and a run button. The interpreter loads only when the user clicks run. ```html ``` -------------------------------- ### Use JavaScript Module in Python Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration Import and utilize a loaded JavaScript module within your Python code. This example shows how to access the 'leaflet' module, which was previously configured. ```python from pyscript.js_modules import leaflet as L map = L.map("map") # etc.... ``` -------------------------------- ### Write to Mounted File Source: https://docs.pyscript.net/2026.3.1/api/fs Writes data to a file within a mounted directory. This example demonstrates creating or overwriting a file named 'data.txt' in the '/local' mount point. ```python with open("/local/data.txt", "w") as f: f.write("Important data") ``` -------------------------------- ### Initialize Device Wrapper Source: https://docs.pyscript.net/2026.3.1/api/media Creates a Device wrapper object around a MediaDeviceInfo object. This is a constructor for the Device class. ```python def __init__(self, device): """ Create a Device wrapper around a MediaDeviceInfo `device`. """ self._device_info = device ``` -------------------------------- ### Style Class Source: https://docs.pyscript.net/2026.3.1/api/web The Style class behaves like a Python dict, with changes automatically reflected in the element's style attribute. It allows setting, getting, and deleting CSS properties. ```APIDOC ## Style Class ### Description Behaves like a Python `dict` with changes automatically reflected in the element's `style` attribute. ### Usage ```python # Set and get styles using CSS property names (hyphenated). element.style["color"] = "red" element.style["background-color"] = "#f0f0f0" element.style["font-size"] = "16px" # Get a style value. color = element.style["color"] # Remove a style. del element.style["margin"] # Check if a style is set. if "color" in element.style: print(f"Color is {element.style['color']}") ``` ### Methods #### `__init__(element)` Initialise the Style dict for the given element. #### `__setitem__(key, value)` Set a style property. #### `__delitem__(key)` Remove a style property. ``` -------------------------------- ### Override Editor Execution Behavior Source: https://docs.pyscript.net/2026.3.1/user-guide/editor Customize the editor's execution by overriding the 'handleEvent' method. This example logs the code instead of running it and prevents default execution by returning False. ```python from pyscript import document def handle_event(event): # Log the code instead of running it. print(event.code) # Return False to prevent default execution. return False editor = document.getElementById("custom") editor.handleEvent = handle_event ``` -------------------------------- ### Configure experimental_remote_packages Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration Enable remote package loading and define the remote configuration structure. ```toml experimental_remote_packages = true packages = ['numpy', 'https://remote.host.com/my_package/v1/config.toml'] ``` ```toml name = "my_package" # a remote config can include packages, even remote ones packages = ['matplotlib'] # files are resolved relatively to this config URL [files] "./__init__.py" = "" "./sub/module.py" = "" "./main.py" = "" ``` -------------------------------- ### Apply and Modify CSS Styles with PyScript Source: https://docs.pyscript.net/2026.3.1/api/web Demonstrates how to manage inline CSS styles for an Element using a dictionary-like interface. Shows setting, getting, and removing styles by their CSS property names. ```python # Set styles using CSS property names (hyphenated). element.style["color"] = "red" element.style["background-color"] = "#f0f0f0" element.style["font-size"] = "16px" # Get styles. color = element.style["color"] # Remove styles. del element.style["margin"] ``` -------------------------------- ### Activate a Python virtual environment Source: https://docs.pyscript.net/2026.3.1/developers Run this command to enter the sandbox environment for development activities. ```bash source my_pyscript_dev_venv/bin/activate ``` -------------------------------- ### Get Media Stream from Specific Device Source: https://docs.pyscript.net/2026.3.1/api/media Lists all available media devices and then retrieves a stream from a specific camera identified by its label. This will trigger a permission dialog if the user hasn't already granted permission. ```python from pyscript.media import list_devices # List all devices. devices = await list_devices() # Find a specific camera. my_camera = None for device in devices: if device.kind == "videoinput" and "USB" in device.label: my_camera = device break # Get a stream from that specific camera. if my_camera: stream = await my_camera.get_stream() ``` -------------------------------- ### Using the template language in TOML Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration This TOML configuration demonstrates the 'files' option's templating language, using placeholders like {DOMAIN}, {PATH}, and {VERSION} to define reusable source and destination paths for multiple file copies. ```toml [files] "{DOMAIN}" = "https://my-server.com" "{PATH}" = "a/path" "{VERSION}" = "1.2.3" "{FROM}" = "{DOMAIN}/{PATH}/{VERSION}" "{TO}" = "./my_module" "{FROM}/__init__.py" = "{TO}/__init__.py" "{FROM}/foo.py" = "{TO}/foo.py" "{FROM}/bar.py" = "{TO}/bar.py" "{FROM}/baz.py" = "{TO}/baz.py" ``` -------------------------------- ### Basic Usage of display() Source: https://docs.pyscript.net/2026.3.1/user-guide/display Demonstrates the fundamental usage of the display() function for rendering simple text and multiple values. ```APIDOC ## Basic usage of display() ### Description Displays simple Python objects like text to the web page. ### Method `display()` ### Parameters None for basic usage. ### Request Example ```python from pyscript import display display("Hello, World!") display("Multiple", "values", "at", "once") ``` ### Response Content is rendered directly in the browser. ``` -------------------------------- ### Create a Python virtual environment Source: https://docs.pyscript.net/2026.3.1/developers Use this command to initialize a new isolated Python environment in the current directory. ```bash python3 -m venv my_pyscript_dev_venv ``` -------------------------------- ### Define JavaScript Main Thread Modules in JSON Source: https://docs.pyscript.net/2026.3.1/user-guide/configuration This JSON configuration achieves the same as the TOML example, loading JavaScript modules and their CSS dependencies into the main thread. CSS files must match the JavaScript module names. ```json { "js_modules": { "main": { "https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet-src.esm.js": "leaflet", "https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.css": "leaflet" } } } ``` -------------------------------- ### __init__ Source: https://docs.pyscript.net/2026.3.1/api/web Initializes an Element instance, either by creating a new DOM element or wrapping an existing one. Supports setting classes, styles, and HTML attributes/event handlers. ```APIDOC ## __init__(dom_element=None, classes=None, style=None, **kwargs) ### Description Create or wrap a DOM element. If `dom_element` is `None`, this creates a new element. Otherwise wraps the provided DOM element. The `**kwargs` can include HTML attributes and event handlers (names starting with `on_`). ### Method Constructor ### Parameters #### Path Parameters - **dom_element** (DOMElement, optional) - The DOM element to wrap. If None, a new element is created. - **classes** (str, optional) - CSS classes to apply to the element. - **style** (str, optional) - CSS styles to apply to the element. - **kwargs** (dict, optional) - Additional HTML attributes and event handlers (e.g., `on_click`). ### Request Example ```json { "classes": "my-class", "style": "color: red;", "id": "my-element", "on_click": "myFunction()" } ``` ### Response #### Success Response (200) - **Element** (Element) - The initialized Element object. ### Response Example ```json { "element": "
" } ``` ```