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(), self.shell.user_ns)
            sys.stdout = stdout
        sys.stdout = stdout
        return HTML("<p>{}</p>".format(markdown(buffer.getvalue(), extensions=['markdown.extensions.extra'])))
        return buffer.getvalue() + 'test'


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.

You may also like...

2 Responses

  1. ibar says:

    If I used this code, I can not access variables in other cells of the notebook. Is there a bug?

  2. Guido says:

    Thanks for trying it. If I understand your problem correctly, then variables created in the cell with the %%asmarkdown magic command are not accessible in later cells. This indeed was caused by a bug in the above code (now corrected) that did not pass on the current ipython notebook namespace to the exec command. Please update your code accordingly (copy and paste from above is sufficient).

Leave a Reply

Your email address will not be published.