braunmagrin
braunmagrin

Reputation: 886

How to programmatically create several new cells in a Jupyter notebook

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?

Upvotes: 9

Views: 4650

Answers (2)

braunmagrin
braunmagrin

Reputation: 886

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)

How to use it:
Suppose you want to create a new cell with print(123) as the content. You just have to define the function above and then call the function like so:

content = 'print(123)'
create_new_cell(content)

Hope this helps someone out there ;)

Upvotes: 23

xingpei Pang
xingpei Pang

Reputation: 1285

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

Upvotes: 2

Related Questions