Skip to content

pyodide/python/capture_system.py - Output Capture System

Location: src/pyodide/python/capture_system.py

This file is responsible for capturing all outputs generated by the user's Python code. This includes standard output (stdout), standard error (stderr), Matplotlib figures, and a custom structured data channel called the "missive" system.

Core Functions

reset_captures()

  • Description: This function is called before each code execution. It clears the stdout and stderr buffers, resets the missive state, and closes any open Matplotlib figures. It also redirects sys.stdout and sys.stderr to custom CaptureStream objects that write to in-memory buffers.

get_stdout() and get_stderr()

  • Description: These functions return the contents of the stdout and stderr buffers as strings.

get_missive()

  • Description: Returns the data sent via the missive function as a JSON string.

get_figures()

  • Description: This function finds any Matplotlib figures that have been created, saves each one to an in-memory buffer as a PNG image, and returns a list of base64-encoded strings representing the images.

missive(data)

  • Description: This function is made globally available to the user's code. It allows the user to send a Python dictionary back to the main JavaScript thread as structured data. It can only be called once per execution.
  • Parameters:
    • data (dict): A Python dictionary to be sent to JavaScript.
  • Throws: ValueError if called more than once.