Search code examples
pythonjupyter-notebook

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?


Solution

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