How to programmatically generate markdown output in Jupyter notebooks?
PythonIpythonJupyterJupyter NotebookPython Problem Overview
I want to write a report for classes in Jupyter notebook. I'd like to count some stuff, generate some results and include them in markdown. Can I set the output of the cell to be interpreted as markdown?
I'd like such command: print '$\phi$'
to generate phi symbol, just like in markdown.
In other words, I'd like to have a template made in markdown and insert the values generated by the program written in the notebook. Recalculating the notebook should generate new results and new markdown with those new values inserted. Is that possible with this software, or do I need to replace the values by myself?
Python Solutions
Solution 1 - Python
The functions you want are in the IPython.display module.
from IPython.display import display, Markdown, Latex
display(Markdown('*some markdown* $\phi$'))
# If you particularly want to display maths, this is more direct:
display(Latex('\phi'))
Solution 2 - Python
You are basically asking for two different things:
-
Markdown cells outputting code results. > I'd like to count some stuff, generate some results and include them in markdown. [...] I'd like to have a template in markdown and insert values generated by the program in the notebook
-
Code cells outputting markdown
> I'd like such command:
print '$\phi$'
to generate phi symbol, just like in markdown.
Since 2. is already covered by another answer (basically: use Latex()
or Markdown()
imported from IPython.display
), I will focus on the first one:
1. Markdown Template with inserted variables
With the Jupyter extension Python Markdown it actually is possible to do exactly what you describe.
Installation instructions can be found on the github page of nbextensions. Make sure you'll enable the python markdown extension using a jupyter command or the extension configurator.
With the extension, variables are accessed via {{var-name}}
. An example for such a markdown template could look like this:
> Python Code in Markdown Cells > > The variable a is {{a}} > > You can also embed LateX: {{b}} in here! > > Even images can be embedded: {{i}}
Naturally all variables or images a
, b
, i
should be set in previous code. And of course you may also make use of Markdown-Latex-style expressions (like $\phi$
) without the print command. This image is from the wiki of the extension, demonstrating the capability.
Further info on this functionality being integrated into ipython/jupyter is discussed in the issue trackers for ipython and jupyter.