7

I want to programmatically create several cells in a Jupyter notebook.

With this function I can create one cell

def create_new_cell(contents):
    from IPython.core.getipython import get_ipython
    shell = get_ipython()
    shell.set_next_input(contents, replace=False)

But if I try to call it several times, for instance, from a for loop, like so

for x in ['a', 'b', 'c']:
    create_new_cell(x)

It will only create one cell with the last item in the list. I've tried to find if there's a "flush" function or something similar but did not succeed.

Does anyone know how to properly write several cells programmatically?

braunmagrin
  • 828
  • 6
  • 17

2 Answers2

20

I dug a bit more in the code of the shell.payload_manager and found out that in the current implementation of the set_next_input it does not pass the single argument to the shell.payload_manager.write_payload function. That prevents the notebook from creating several cells, since they all have the same source (the set_next_input function, in this case).

That being said, the following function works. It's basically the code from write_payload function setting the single parameter to False.

def create_new_cell(contents):
    from IPython.core.getipython import get_ipython
    shell = get_ipython()

    payload = dict(
        source='set_next_input',
        text=contents,
        replace=False,
    )
    shell.payload_manager.write_payload(payload, single=False)

Hope this helps someone out there ;)

braunmagrin
  • 828
  • 6
  • 17
1
from IPython.display import display, Javascript
def add_cell(text,  type='code', direct='above'):
    text = text.replace('\n','\\n').replace("\"", "\\\"").replace("'", "\\'")

    display(Javascript('''
    var cell = IPython.notebook.insert_cell_{}("{}")
    cell.set_text("{}")
    '''.format(direct, type, text)));

for i in range(3):
    add_cell(f'# heading{i}', 'markdown')
    add_cell(f'code {i}')

codes above will add cells as follows:enter image description here

xingpei Pang
  • 1,185
  • 11
  • 15