Ask Your Question
1

How can exceptions in Pyodide's runPythonAsync be displayed as asyncio stacktraces instead of inner ones?

asked 2022-08-29 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-02-23 06:00:00 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-29 11:00:00 +0000

Seen: 9 times

Last updated: Feb 23 '22