1

I'm trying to write python code in my jupyter notebook, that will export the whole current notebook to html/pdf.

I know I can do something like that:

import subprocess
subprocess.call("jupyter nbconvert notebook.ipynb")

But that requires the file name, which is not known inside the notebook.

I saw many "hacks" to get the notebook file name, like this one: How do I get the current IPython Notebook name but I prefer to find a better solution.

Is there a smart way to export the current running notebook to a html/pdf file?

Thanks.

Itay Gabbay
  • 113
  • 1
  • 9
  • Why don't you just use the main menu `File > Download as... > HTML`? – Nils Werner Aug 13 '18 at 11:22
  • I need to write a python package that will export the notebook automatically and save it in a specific location – Itay Gabbay Aug 13 '18 at 11:26
  • Yeah, but *why* do you need to write a package that does it inside the notebook? I would recommend a workflow that stays outside of the notebook, and compiles everything from there. – Nils Werner Aug 13 '18 at 11:27
  • In the end-state, I want this workflow to track finished runs of notebooks, export the whole notebook (including the outputs) to a html/pdf file, and save it in a remote directory, in order to keep track of running experiments.If I write a workflow that runs outside of the notebook, will it be possible to determine which notebook has finished it's run? – Itay Gabbay Aug 13 '18 at 11:37
  • @ItayGabbay did you find a way to do it? :) – mbh86 Mar 29 '19 at 08:49
  • 1
    @mbh86 Unfortunately, No :( – Itay Gabbay Apr 02 '19 at 13:46
  • @ItayGabbay By chance, I found a solution. I was looking for script to execute many notebooks in a row, with different parameters, and so I found a way to pass parameters from outside the notebooks, which also fits your need imho. Check the answer below. – mbh86 Jun 07 '19 at 13:49

1 Answers1

0

You can use the library papermill, that will execute the notebook with ingested parameters (basically your notebook name that you define outside your notebook)

Python program

pm.execute_notebook(
   'notebooks/notebookA.ipynb', # notebook to execute
   'notebooks/temp.ipynb', # temporary notebook that will contains the outputs and will be used to save HTML
   report_mode=True, # To hide ingested parameters cells, but not working for me
   parameters=dict(filename_ipynb='notebooks/temp.ipynb', 
                   filename_html='output/notebookA.html')
)

/notebooks/notebookA.ipynb

(To insert as the last cell of your notebook)

import os
os.system('jupyter nbconvert --output ../' + filename_html + ' --to html ' + filename_ipynb)

Just a thing: it is adding a cell to set the parameters ingested. It should be able to hide it with report_mode=False but somehow it doesn't work, even though it should: https://github.com/nteract/papermill/issues/253

mbh86
  • 6,078
  • 3
  • 18
  • 31