0

I would like to programmatically run a jupyter notebook cell containing import statements and use the packages imported after opening the notebook and not just convert the output to a new ipython notebook.

Currently, I am using nbconvert to execute a pre-created Jupyter notebook. The steps taken to execute the notebook are as following -

jupyter nbconvert --execute --inplace test.ipynb

Code to create new notebook -

import nbformat as nbf
nb = nbf.v4.new_notebook()
nb['cells'] = [nbf.v4.new_markdown_cell(text),nbf.v4.new_code_cell(code,metadata={'editable':False,'deletable':False}) ]
nbf.write(nb, 'test.ipynb')

The code block in the notebook cell contains -

import pandas as pd
import numpy as np
import matplotlib as plt
%pylab inline
hist(normal(size=2000), bins=50)

The output cell displays the histogram as expected. However, I am unable to use the packages imported after opening the notebook. Is there a way to execute the notebook in command line and then use the imported packages after opening the notebook without having to manually run the cell again ?

  • what do you mean by `unable to use the packages imported after opening the notebook`? – muratgu Feb 19 '19 at 20:24
  • I can execute the notebook cell using nbconvert. When I open the executed notebook file , I can see the output in the output cell. However, if am trying to use the pandas package which I imported in the same pre-executed cell in a different code cell after opening the notebook, I am unable to do so. – user3151238 Feb 19 '19 at 20:26

1 Answers1

0

I was able to solve this problem by installing jupyter extension - [Jupyter notebook extension][1]https://github.com/ipython-contrib/jupyter_contrib_nbextensions.

After enabling the init_cell extension as specified in the document in the above link, I added the metadata tag "init_cell":True nbf.v4.new_code_cell(code,metadata={'editable':False,'deletable':False,'trusted':True,'init_cell':True}) in the notebook creation code for the cell I want to set as Initialized cell.

Also, I had to execute the line jupyter trust test.ipynb in the command-line just to make sure that notebook is set as trusted for cell block to run on notebook load.

This results in execution of the initialized code cell block after the notebook is loaded thus enabling me to use the imported packages and variables if any without having to manually run the cell.