Auto-convert cell and output into formatted markdown string

When Jupyter cell code and its output are copy-pasted to other platforms (e.g. to GitHub or this Jupyter discourse), some manual formatting work is required.

This work can easily be automated, e.g. with this cell magic (implementation below):

The cell magic takes code and output and generates a formatted markdown string from it.
But there might be better options for this, like an extension that adds a copy button, similar to the sphinx copy button.

Furthermore, one could format the output depending on whether it is text or an error message.

Cell magic code:

from IPython.core.magic import Magics, cell_magic, magics_class
from IPython.utils.capture import capture_output
from IPython import get_ipython

@magics_class
class CaptureMagic(Magics):
    @cell_magic
    def to_md(self, line, cell):
        with capture_output(stdout=True, stderr=False, display=False) as result:
            self.shell.run_cell(cell)
            message = result.stdout

        print(message)
        print("#### Markdown #### \n")
        markdown_string = ""
        markdown_string += "```python\n"
        markdown_string += cell
        markdown_string += "```\n"

        if len(message) != 0:
            markdown_string += "```console\n"
            markdown_string += "# out:\n"
            markdown_string += message
            markdown_string += "```\n"
            
        print(markdown_string)

ipy = get_ipython()
ipy.register_magics(CaptureMagic)
2 Likes

Alternative Layout idea

I just had an idea for an alternative layout.
This is how a jupyter cell could also be rendered in discourse:

In
print("hi")
print(4+4)
Out
hi
8

How does it look like in raw text?

The above example was produced by this text-block

<table>
<tr>
<td>In</td>
<td>
	
```python
print("hi")
print(4+4)
```
</td>
</tr>
<tr>
<td>Out</td>
<td>

```console
hi
8
```
</td></table>

And what about images?

Furthermore, images could also be included into these markdown strings in base64:

<img src="data:image/png;base64,iVBORw0... and 15 000 more characters" />

These long strings are not at all convenient to work with, but technically it would be possible.
The rendered cell and output would look like this:

In
plt.plot(jupyter_logo)
Out

1 Like