9

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?

2 Answers 2

24

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 ;)

Sign up to request clarification or add additional context in comments.

7 Comments

Please provide an example of putting some code into the new cell programmatically
@WestCoastProjects You can use the function like so: create_new_cell('print(123)'). Is that what you were asking for? The contents argument can be any Python code as a string.
@braunmagrin - is there anyway to execute it?
Absolutely brilliant! Very, very creative, thank you.
Works beautifully! i.imgur.com/83Ofq7w.gif (feel free to add it to the answer so others can 'see')
|
2
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

2 Comments

I get the error Javascript Error: IPython is not defined
I get empty output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.