Raman Bonde
Raman Bonde

Reputation: 1

setup to get the python output displayed line by line during execution

I am working on building a web application that runs Python code in the browser using Web Workers and Pyodide. My goal is to display the output line by line in the browser/application as the code is executed. However, with my current implementation, I only receive the output after the entire execution is complete

importScripts("https://cdn.jsdelivr.net/pyodide/v0.26.1/full/pyodide.js");

async function loadPyodideAndPackages() {
  self.pyodide = await loadPyodide({
    indexURL: "https://cdn.jsdelivr.net/pyodide/v0.26.1/full/",
  });
  await self.pyodide.loadPackage(["numpy", "pytz"]);
  // Send message to main thread that Pyodide is ready
  self.postMessage({ status: "READY" });
}

let pyodideReadyPromise = loadPyodideAndPackages();

self.onmessage = async (event) => {
  await pyodideReadyPromise;

  let stdout = [];
  let stderr = [];

  self.pyodide.setStdout({
    batched: (str) => {
      stdout.push(str);
      // Send each line (or part of line) to main thread
      self.postMessage({ line: str });
    },
  });

  self.pyodide.setStderr({
    batched: (str) => {
      stderr.push(str);
      // Send error lines
      self.postMessage({ error: str });
    },
  });

  try {
    await self.pyodide.runPythonAsync(event.data);
    self.postMessage({ status: "done" });
  } catch (error) {
    self.postMessage({ error: error.message });
  }
};

Upvotes: 0

Views: 28

Answers (0)

Related Questions