示例#1
0
    def load_module_by_path(self):
        # parse the notebook json
        with io.open(self.nb_path, 'r', encoding='utf-8') as f:
            notebook = reader.read(f)
        # convert to current notebook version
        notebook = convert_notebook(notebook)

        # create the module and generate a hash from the name
        fullname = hashlib.sha1().hexdigest()
        mod = types.ModuleType(fullname)
        mod.__file__ = self.nb_path
        mod.__package__ = None
        mod.__loader__ = self
        sys.modules[fullname] = mod

        # extra work to ensure that magics that would affect the user_ns
        # actually affect the notebook module's ns
        save_user_ns = self.shell.user_ns
        self.shell.user_ns = mod.__dict__

        try:
            self.eval_notebook(notebook, mod)
        finally:
            self.shell.user_ns = save_user_ns
        return mod
示例#2
0
    def load_module(self, fullname):
        '''
        Creates a module containing the exposed API content of a notebook
        by evaluating those notebook cells.
        '''
        # parse the notebook json
        with io.open(self.nb_path, 'r', encoding='utf-8') as f:
            notebook = reader.read(f)
        # convert to current notebook version
        notebook = convert_notebook(notebook)

        # create the module
        mod = types.ModuleType(fullname)
        mod.__file__ = self.nb_path
        mod.__package__ = '.'.join(fullname.split('.')[:-1])
        mod.__loader__ = self
        sys.modules[fullname] = mod

        # extra work to ensure that magics that would affect the user_ns
        # actually affect the notebook module's ns
        save_user_ns = self.shell.user_ns
        self.shell.user_ns = mod.__dict__

        try:
            self.eval_notebook(notebook, mod)
        finally:
            self.shell.user_ns = save_user_ns
        return mod
示例#3
0
def Viewer(nburl=None, showcode=False, render='html'):

    from IPython.nbformat import reader as nbformat
    from IPython.nbconvert import exporters

    # Get url or file path
    if nburl:

        if nburl.startswith("http"):
            import requests
            response = requests.get(nburl)
            notebook = nbformat.reads_json(response.content)

        else:
            notebook = nbformat.read(fp=file(nburl))

    else:
        notebook = ''

# Get rendering template
    if showcode:

        if render == 'html':
            template = 'full'

    else:

        if render == 'html':
            template = 'full2'

    import IPython.nbconvert
    from IPython.config import Config
    from IPython.nbconvert import HTMLExporter

    ## I use `basic` here to have less boilerplate and headers in the HTML.
    ## we'll see later how to pass config to exporters.
    exportHtml = HTMLExporter(
        config=Config({'HTMLExporter': {
            'template_file': template
        }}))

    (body, resources) = exportHtml.from_filename(nburl)

    return body