### Full HTML Example for Loading Packages Source: https://pyodide.org/en/stable/_sources/usage/loading-packages.md A complete HTML example demonstrating how to load Pyodide, install a package via micropip, and run Python code. ```html ``` -------------------------------- ### Install and enable pre-commit linting Source: https://pyodide.org/en/stable/_sources/development/testing.md Install prek and configure it to run automatically on commit. ```bash pip install prek prek install ``` -------------------------------- ### Complete example: load Pyodide and run Python Source: https://pyodide.org/en/stable/_sources/usage/quickstart.md A complete example that loads Pyodide and runs Python code. The loadPyodide function is async and returns the Pyodide namespace. The example runs Python code to get the sys.version string. ```pyodide async function main() { let pyodide = await loadPyodide(); // Pyodide is now ready to use... console.log(pyodide.runPython(` import sys sys.version `)); }; main(); ``` -------------------------------- ### Install Python dependencies from requirements.txt Source: https://pyodide.org/en/stable/_sources/development/building-from-sources.md Installs the Python dependencies listed in the requirements.txt file at the root of the Pyodide folder. Run after installing the build prerequisites. ```bash pip install -r requirements.txt ``` -------------------------------- ### Pyodide app install command Source: https://pyodide.org/en/stable/usage/api/pyodide-cli.html Usage syntax for installing the cross-build environment. ```bash pyodide app install [OPTIONS] [VERSION] ``` -------------------------------- ### Install Pyodide and vite-plugin-static-copy Source: https://pyodide.org/en/stable/_sources/usage/working-with-bundlers.md Installs the Pyodide and vite-plugin-static-copy npm packages, which are required for the Vite bundling setup. ```bash $ npm install pyodide vite-plugin-static-copy ``` -------------------------------- ### Install a wheel from an arbitrary URL with Micropip Source: https://pyodide.org/en/stable/_sources/usage/loading-packages.md Use this snippet to install a pure Python wheel from any URL using Micropip. The URL must end in '.whl' and follow PEP 427 naming. Dependencies are installed by default; pass deps=False to disable. The server must set CORS headers for remote files. ```python import micropip micropip.install( 'https://example.com/files/snowballstemmer-2.0.0-py2.py3-none-any.whl' ) ``` -------------------------------- ### Build and preview production bundle Source: https://pyodide.org/en/stable/usage/working-with-bundlers.html Build the production bundle and preview it locally to verify the setup works in production. ```bash npx vite build npx vite preview ``` -------------------------------- ### Clone and build a subset of packages with pyodide build-recipes Source: https://pyodide.org/en/stable/_sources/development/building-from-sources.md Clones the pyodide-recipes repository and builds the specified packages with their dependencies. The package names must match the folder names exactly and are case-sensitive. Use the --recipe-dir flag and --install to install the built packages. ```bash git clone https://github.com/pyodide/pyodide-recipes # Build the packages you need pyodide build-recipes "numpy, scipy, toolz, attrs" --recipe-dir pyodide-recipes/packages --install ``` -------------------------------- ### Build and preview Vite production Source: https://pyodide.org/en/stable/_sources/usage/working-with-bundlers.md Builds the production bundle and previews it locally to verify the setup works in production. ```bash npx vite build npx vite preview ``` -------------------------------- ### pyodide.runPython() example with globals and locals Source: https://pyodide.org/en/stable/usage/api/js-api.html Example of runPython() with default globals, custom globals, and custom locals. Shows that the result of the last expression is returned. ```javascript async function main(){ const pyodide = await loadPyodide(); console.log(pyodide.runPython("1 + 2")); // 3 const globals = pyodide.toPy({ x: 3 }); console.log(pyodide.runPython("x + 1", { globals })); // 4 const locals = pyodide.toPy({ arr: [1, 2, 3] }); console.log(pyodide.runPython("sum(arr)", { locals })); // 6 } main(); ``` -------------------------------- ### Install packages with uv Source: https://pyodide.org/en/stable/_sources/usage/cli.md Command to install Pyodide packages using uv with the required index configuration. ```sh uv pip install --no-build --extra-index-url https://index.pyodide.org/314.0.0/ --index-strategy unsafe-best-match ``` -------------------------------- ### Install testing dependencies Source: https://pyodide.org/en/stable/_sources/development/testing.md Install the required pytest plugins for testing Pyodide and third-party applications. ```bash pip install pytest-pyodide pytest-httpserver ``` -------------------------------- ### Basic Python CLI usage Source: https://pyodide.org/en/stable/_sources/usage/cli.md Examples of standard Python CLI commands that work with the Pyodide CLI. ```sh python -c "some command" python file.py python -m some.module ``` -------------------------------- ### Raw handler example Source: https://pyodide.org/en/stable/usage/streams.html Shows how a raw handler receives output one character code at a time. ```python print("h") import sys print("p ", end="") print("l", end="") sys.stdout.flush() ``` -------------------------------- ### Enable pre-commit hooks Source: https://pyodide.org/en/stable/development/contributing.html Installs pre-commit hooks to run a set of linters for each commit. ```bash prek install ``` -------------------------------- ### Pyodide app install-emscripten command Source: https://pyodide.org/en/stable/usage/api/pyodide-cli.html Usage syntax for installing the Emscripten SDK into the cross-build environment. ```bash pyodide app install-emscripten [OPTIONS] ``` -------------------------------- ### Enable code style linting Source: https://pyodide.org/en/stable/_sources/development/contributing.md Command to install prek, which runs linters for each commit. ```bash prek install ``` -------------------------------- ### Pyodide app versions command Source: https://pyodide.org/en/stable/usage/api/pyodide-cli.html Usage syntax for listing all installed cross-build environment versions. ```bash pyodide app versions [OPTIONS] ``` -------------------------------- ### Using Console.push with ConsoleFuture Source: https://pyodide.org/en/stable/usage/api/python-api/console.html Shows how to create a Console instance, push a line of code, and inspect the syntax_check status. The future is then run with asyncio.run to execute the code and print the output. ```python >>> from pyodide.console import Console >>> console = Console() >>> future = console.push("print('Hello, World!')") >>> print(future.syntax_check) complete >>> import asyncio >>> result = asyncio.run(future) Hello, World! ``` -------------------------------- ### Load Pyodide and run Python code Source: https://pyodide.org/en/stable/usage/quickstart.html An async function that loads Pyodide and runs Python code to get the sys.version. This is the basic setup for using Pyodide. ```javascript async function main() { let pyodide = await loadPyodide(); // Pyodide is now ready to use... console.log(pyodide.runPython(` import sys sys.version `)); }; main(); ``` -------------------------------- ### Access object fields with as_py_json Source: https://pyodide.org/en/stable/usage/type-conversions.html Converts a JavaScript object to a Python dictionary using as_py_json() to access fields that are not valid Python identifiers, such as names starting with a dollar sign. The example creates an object with fields a, b, and $c and asserts the value of the $c key. ```python from pyodide.code import run_js obj = run_js( """ ({ a: 7, b: 9, $c: 11 }) """ ) obj_map = obj.as_py_json() assert obj_map["$c"] == 11 ``` -------------------------------- ### Use Pyodide in Node.js REPL Source: https://pyodide.org/en/stable/_sources/usage/index.md Starts the Node.js REPL with top-level await support and demonstrates importing Pyodide, initializing it, and running Python code interactively. ```bash $ node --experimental-repl-await Welcome to Node.js v18.5.0. Type ".help" for more information. > const { loadPyodide } = await import("pyodide"); undefined > let pyodide = await loadPyodide(); undefined > await pyodide.runPythonAsync("1+1"); 2 ``` -------------------------------- ### Install a package with Micropip in Pyodide Source: https://pyodide.org/en/stable/_sources/usage/loading-packages.md Use this snippet to install a pure Python wheel from PyPI using Micropip in a Pyodide environment. It loads the micropip package, imports it, installs 'snowballstemmer', and then runs Python code to use the installed package. Note that micropip.install is async and must be awaited. ```pyodide await pyodide.loadPackage("micropip"); const micropip = pyodide.pyimport("micropip"); await micropip.install('snowballstemmer'); pyodide.runPython(` import snowballstemmer stemmer = snowballstemmer.stemmer('english') print(stemmer.stemWords('go goes going gone'.split())) `); ``` -------------------------------- ### Using sockets directly in Python Source: https://pyodide.org/en/stable/_sources/usage/socket.md Example of creating a socket, connecting to a server, sending and receiving data, and closing the socket. Requires socket support enabled. ```python import socket # Create a socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to a server s.connect(('localhost', 8080)) # Send some data s.sendall(b'Hello, world') # Receive some data data = s.recv(1024) print('Received', repr(data)) # Close the socket s.close() ``` -------------------------------- ### Install Pyodide npm package Source: https://pyodide.org/en/stable/_sources/usage/index.md Installs the Pyodide npm package, which is required to use Pyodide in Node.js. ```bash $ npm install pyodide ``` -------------------------------- ### Launch Chrome with custom devtools frontend Source: https://pyodide.org/en/stable/_sources/development/debugging.md Command to start Chrome using the modified devtools frontend served locally. ```bash chrome --custom-devtools-frontend=http://localhost:/ ``` -------------------------------- ### Install Python requirements Source: https://pyodide.org/en/stable/development/contributing.html Installs the Python dependencies listed in requirements.txt. It is recommended to use a virtualenv or conda environment. ```bash pip install -r requirements.txt ``` -------------------------------- ### pyodide.pyimport() example with math.comb Source: https://pyodide.org/en/stable/usage/api/js-api.html Example of pyimport() with a dotted module name. Returns the result of calling the imported function. ```javascript pyodide.pyimport("math.comb")(4, 2) // returns 4 choose 2 = 6 ``` -------------------------------- ### Pyodide app use command Source: https://pyodide.org/en/stable/usage/api/pyodide-cli.html Usage syntax for selecting a specific cross-build environment version. ```bash pyodide app use [OPTIONS] VERSION ``` -------------------------------- ### Set ENABLE_PREBUILT_PACKAGES=1 to use pre-built packages Source: https://pyodide.org/en/stable/_sources/development/building-from-sources.md Runs a minimal make build that automatically downloads and installs pre-built packages from the pyodide-recipes repository. Set the ENABLE_PREBUILT_PACKAGES environment variable to 1 before executing make. ```bash ENABLE_PREBUILT_PACKAGES=1 make ``` -------------------------------- ### PyMutableSequence.fill(value, start, end) Source: https://pyodide.org/en/stable/usage/api/js-api.html Changes all elements in a PyMutableSequence to a static value, from a start index to an end index. ```APIDOC ## PyMutableSequence.fill(value, start, end) ### Description The `Array.fill()` method changes all elements in an array to a static value, from a start index to an end index. ### Arguments - **value** (`any`) - Required - Value to fill the array with. - **start** (`number`) - Optional - Zero-based index at which to start filling. Default 0. - **end** (`number`) - Optional - Zero-based index at which to end filling. Default `list.length`. ### Returns `any` ``` -------------------------------- ### PyodideConfig.packages Source: https://pyodide.org/en/stable/usage/api/js-api.html Configuration property specifying a list of packages to load as Pyodide is initializing. This is the same as loading the packages with `pyodide.loadPackage()` after Pyodide is loaded except using the `packages` option is more efficient because the packages are downloaded while Pyodide bootstraps itself. ```APIDOC ## PyodideConfig.packages ### Description A list of packages to load as Pyodide is initializing. This is the same as loading the packages with `pyodide.loadPackage()` after Pyodide is loaded except using the `packages` option is more efficient because the packages are downloaded while Pyodide bootstraps itself. ### Type `string`[] ``` -------------------------------- ### Install compatible Rust sysroot Source: https://pyodide.org/en/stable/_sources/development/abi/313.md Commands to install the nightly-2025-02-01 toolchain and download a compatible Emscripten sysroot for WebAssembly exception handling. ```bash rustup toolchain install nightly-2025-02-01 TOOLCHAIN_ROOT=$(rustup run nightly-2025-02-01 rustc --print sysroot) RUSTLIB=$TOOLCHAIN_ROOT/lib/rustlib wget https://github.com/pyodide/rust-emscripten-wasm-eh-sysroot/releases/download/emcc-4.0.9_nightly-2025-02-01/emcc-4.0.9_nightly-2025-02-01.tar.bz2 tar -xf emcc-4.0.9_nightly-2025-02-01.tar.bz2 --directory=$RUSTLIB ``` -------------------------------- ### pyodide app get usage Source: https://pyodide.org/en/stable/usage/api/pyodide-cli.html Shows the usage syntax for the 'pyodide app get' subcommand, which retrieves a config variable value. ```bash pyodide app get [OPTIONS] CONFIG_VAR ``` -------------------------------- ### Run project linting Source: https://pyodide.org/en/stable/_sources/development/testing.md Lint the codebase using the prek tool. ```bash prek -a ``` -------------------------------- ### Attempting to start a thread raises RuntimeError Source: https://pyodide.org/en/stable/_sources/usage/faq.md Shows that importing and using the general threading API works, but calling start() on a thread raises RuntimeError. The interactive session defines a target function and demonstrates that run() works but start() fails because Pyodide cannot create new threads. ```pycon >>> import threading >>> current = threading.current_thread() >>> current.name 'MainThread' >>> current.daemon False >>> current.is_alive() True >>> def target(nums): ... print(sum(nums)) ... >>> t = threading.Thread(target=target, args=([1, 2, 3], )) >>> t.run() 6 >>> t.start() Traceback (most recent call last): File "", line 1, in File "/lib/python312.zip/threading.py", line 994, in start _start_new_thread(self._bootstrap, ()) RuntimeError: can't start new thread ``` -------------------------------- ### Create Pyodide virtual environment Source: https://pyodide.org/en/stable/usage/api/pyodide-cli.html Initialize a virtual environment at the specified destination directory, supporting a subset of standard virtualenv arguments. ```bash pyodide main [OPTIONS] DEST ``` -------------------------------- ### Load packages from CDN with packageBaseUrl Source: https://pyodide.org/en/stable/_sources/usage/working-with-bundlers.md Loads Pyodide with a `packageBaseUrl` pointing to the CDN, so `.whl` packages are fetched from the CDN instead of being bundled locally. This is Option 1 for handling packages. ```js import { loadPyodide, version } from "pyodide"; const pyodide = await loadPyodide({ indexURL: `${import.meta.env.BASE_URL}assets/pyodide`, packageBaseUrl: `https://cdn.jsdelivr.net/pyodide/v${version}/full/`, }); ``` -------------------------------- ### pyodide.runPythonAsync() example with top-level await Source: https://pyodide.org/en/stable/usage/api/js-api.html Example of runPythonAsync() with top-level await. The promise resolves to the value of the last expression if it is an expression and the code does not end with a semicolon. ```javascript let result = await pyodide.runPythonAsync(` from js import fetch response = await fetch("./pyodide-lock.json") packages = await response.json() # If final statement is an expression, its value is returned to JavaScript len(packages.packages.object_keys()) `); console.log(result); // 79 ``` -------------------------------- ### Custom runPython wrapper Source: https://pyodide.org/en/stable/_sources/usage/faq.md Example of creating a custom Python entrypoint to modify execution behavior and return extra information alongside the result. ```javascript const my_eval_code = pyodide.runPython(` from pyodide.code import eval_code def my_eval_code(code, globals=None, locals=None): extra_info = None result = eval_code(code, globals, locals) return globals["extra_info"], result my_eval_code `) function myRunPython(code){ return my_eval_code(code, pyodide.globals); } ``` -------------------------------- ### as_py_json() example Source: https://pyodide.org/en/stable/usage/api/python-api/ffi.html This example shows how `as_py_json()` converts a JavaScript object into a Python-like structure, allowing access to nested properties using Python indexing and list comprehensions. ```python >>> from pyodide.code import run_js >>> o1 = run_js("({x : {y: 2}})") >>> o1.as_py_json()["x"]["y"] 2 >>> o2 = run_js("[{x: 2}, {x: 7}]") >>> [e["x"] for e in o2.as_py_json()] [2, 7] ``` -------------------------------- ### Serve inspector overlay with Python HTTP server Source: https://pyodide.org/en/stable/_sources/development/debugging.md Command to start a simple HTTP server in the inspector_overlay directory to serve the modified devtools resources. ```bash cd out/Default/resources/inspector_overlay/ python http.server ``` -------------------------------- ### find_imports example Source: https://pyodide.org/en/stable/usage/api/python-api/code.html Shows how to use pyodide.code.find_imports to extract module names from a Python source string. The example demonstrates that for 'import package.module', both 'package' and 'package.module' are included in the result. ```python >>> source = "import numpy as np; import scipy.stats" >>> find_imports(source) ['numpy', 'scipy', 'scipy.stats'] ``` -------------------------------- ### Build Python packages with pyodide main Source: https://pyodide.org/en/stable/usage/api/pyodide-cli.html Use the main command to build a Python package from a source location, which can be a folder, PyPI version, or URL. ```bash pyodide main [OPTIONS] [SOURCE_LOCATION] ```