The truth is rarely pure and never simple

Ipython Notebook: Code Output as Markdown

Sometimes, you want to present code output in a way that is more appealing to the eye than just unstructured output. In ipython, there are markdown cells available but you cannot execute any code there. So what if you want to show the markdown output generated by a code cell in ipython notebook?

It would look like this:
Screen Shot 2015-10-06 at 08.19.33

The only problem: the ipython magic “asmarkdown” (as shown in the screenshot) does not exist. Here is the code that you need for this to work — if you put it into your profile, you don’t have to copy it from notebook to notebook.

from __future__ import absolute_import
from IPython.core.getipython import get_ipython
from IPython.core.magic import (Magics, magics_class,  cell_magic)
import sys
from StringIO import StringIO
from markdown import markdown
from IPython.core.display import HTML

class MarkdownMagics(Magics):

    def asmarkdown(self, line, cell):
        buffer = StringIO()
        stdout = sys.stdout
        sys.stdout = buffer
            exec(cell, locals(),
            sys.stdout = stdout
        sys.stdout = stdout
        return HTML("


".format(markdown(buffer.getvalue(), extensions=['markdown.extensions.extra']))) return buffer.getvalue() + 'test' get_ipython().register_magics(MarkdownMagics)

After putting this in your notebook, you have two options if you use a code cell: if you prepend “%%asmarkup” in a single line before any python code, the output of the python code will be interpreted as markdown and shown accordingly. If you don’t prepend the magic, you will get the regular output.

Leave a comment

Your email address will not be published.

3 thoughts on “Ipython Notebook: Code Output as Markdown”