Programmatically Create Jupyter Cells?

2,422 views
Skip to first unread message

Michael Zombok

unread,
Mar 3, 2016, 3:14:55 AM3/3/16
to Project Jupyter
Hi,

I have a function which produces markdown output. Is there a way in Jupyter to programmatically create a markdown cell with the output of this function/a previous code cell?

Thanks!

Best,
Michael

josiah....@gmail.com

unread,
Mar 3, 2016, 6:30:34 AM3/3/16
to Project Jupyter
Hi,

I've done this before by creating the cell using javascript.

Here is the function I used:

from IPython.display import display_javascript

def make_cell(s):

    display_javascript
("""var t_cell = IPython.notebook.get_selected_cell()
    t_cell.set_text('<!--\\n' + t_cell.get_text() + '\\n--> \\n{}');
    var t_index = IPython.notebook.get_cells().indexOf(t_cell);
    IPython.notebook.to_markdown(t_index);
    IPython.notebook.get_cell(t_index).render();"""
.format(s.replace('\n','\\n')), raw=True)

You could replace 

I'm sure there are better ways to do this, but that worked for me. 

josiah....@gmail.com

unread,
Mar 3, 2016, 6:32:57 AM3/3/16
to Project Jupyter
Sorry, I meant to say you could replace "Jupyter.notebook.get_selected_cell()" with "Jupyter.notebook.inset_cell_below()" to create a new cell, rather than replacing the existing one.

Best wishes,
Josiah

Jan Schulz

unread,
Mar 3, 2016, 7:49:41 AM3/3/16
to jup...@googlegroups.com
Hi,

`get_selected_cell` has the problem that it's different depending
whether you have pressed `shift+enter` or `strg+enter` (or even
clicked somewhere completely different while the kernel computed the
output?).

Unfortunately, I know of no way to get the "source" of the current
appended output. If anybody has a workaround for that, I would love to
hear it :-)

If you want to append python code, you can use
`get_ipython().set_next_input('print "test"')`, which knows about the
source cell: https://github.com/jupyter/notebook/blob/master/notebook/static/notebook/js/notebook.js#L197-L210

Jan
--
Jan Schulz
mail: ja...@gmx.net
web: http://www.katzien.de
> --
> You received this message because you are subscribed to the Google Groups
> "Project Jupyter" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to jupyter+u...@googlegroups.com.
> To post to this group, send email to jup...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/jupyter/d768111d-b8c3-4fe4-ab99-8176fb6ac9f5%40googlegroups.com.
>
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages