Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To display exceptions in Pyodide's runPythonAsync function as asyncio stacktraces, you can use the traceback module to print out the entire stack trace, including the outer-most asyncio exception.

Here's an example:

import traceback
import asyncio
from js import fetch, console, setTimeout
import pyodide

async def run_async_code(code: str) -> None:
    try:
        await pyodide.runPythonAsync(code)
    except Exception as e:
        tb = traceback.format_exception(type(e), e, e.__traceback__)
        console.log(''.join(tb))

code = """async def fetch_data():
  resp = await fetch('https://jsonplaceholder.typicode.com/todos/1')
  data = await resp.json()
  print(data['id'])

asyncio.run(fetch_data())"""

asyncio.ensure_future(run_async_code(code))
await asyncio.sleep(2)

In this example, we're using the traceback.format_exception function to convert the exception information into a readable format that includes the entire stack trace. We then use the console.log function to print the traceback to the console.

Note that as of Pyodide version 0.18.1, the runPythonAsync function only reports the inner-most exception by default, so this workaround is necessary to display full stack traces.