The method you described would be possible via a custom plugin, combining both a markdown-it style plugin and possibly a nice object storage for the HTMLs. However I’d be cautious about the security of it, letting user inputted code run anywhere on the server. Discourse already does a lot of work just to sanitize a post for HTML and JS to be safely parsed in the backend.
You might have better luck instead trying to embed a Python interpreter in the browser and let it run the code on client, skipping the whole HTML creation. JupyterLite would let you run JupyterLab on the browser with UI. From the documentation, it looks like you can have it auto run code on creation of the iframe. You can feed in the code with a custom HighlightJS plugin that will create an actionable button on any Python code block, or have it run automatically.
So something like:
- User sees a post with a Python code block.
- User hovers over the code block, where a button appears to let them run the code in browser.
- User clicks on the button, which creates an iframe to JupyterLite below the code, importing the code from the code block.
Since this would just be a HighlightJS plugin that just creates an iframe to JupyterLite, you can create it all within a Theme Component, no server code needed.
One thing to note: JupyterLite is described as not being feature complete to JupyterLab, and I’m not sure how it goes about handling package imports, so you might have to host it yourself. JupyterLite uses Pyodide, which supports any wheel on PyPI, so it should be good