Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save Jupyter Notebook to HTML by code?

I have a Jupyter Notebook program, which do analysis for me. After it's been run, I want to save it as HTML so I can view it later. (And then I can change the input data file to do analysis for other data.)

Typically, I do this by hand. This would look like

enter image description here

But this feels very tedious for me. So I'm wondering if there is any code can do this for me? Maybe something like

%save_html
# or with a file_name
%save_html file_name

Note: I have figured out a workaround for this. But I didn't find too much info by search, so I post it here and it may help someone else having the same problem. I'll post my solution as an answer.

like image 349
cqcn1991 Avatar asked Jun 06 '16 12:06

cqcn1991


2 Answers

just execute this snippet

!!jupyter nbconvert *.ipynb
like image 78
lamoboos223 Avatar answered Sep 19 '22 17:09

lamoboos223


I'll give an answer myself.

from IPython.display import Javascript
from nbconvert import HTMLExporter

def save_notebook():
    display(
        Javascript("IPython.notebook.save_notebook()"),
        include=['application/javascript']
    )

def output_HTML(read_file, output_file):
    import codecs
    import nbformat
    exporter = HTMLExporter()
    # read_file is '.ipynb', output_file is '.html'
    output_notebook = nbformat.read(read_file, as_version=4)
    output, resources = exporter.from_notebook_node(output_notebook)
    codecs.open(output_file, 'w', encoding='utf-8').write(output)

In the last cell of the notebook, something like

import time

save_notebook()
time.sleep(3)
current_file = 'GMM.ipynb'
output_file = 'output_file.html'
output_HTML(current_file, output_file)
like image 27
cqcn1991 Avatar answered Sep 19 '22 17:09

cqcn1991