Run ipynb from python file keeping imports and variables

Another suggestion, maybe more helpful for those finding this later, is that nbformat makes accessing & extracting of the code cells of the notebooks json a bit more straighforward.
Because it is part of the Jupyter machinery, it’s already present wherever you are using notebooks.
There’s several stubs of code examples in this forum if you search ‘nbformat’, or you can look at this post and the links below it. This code illustrates the ease with which you can use it to subset notebooks.