Example #1
0
def get_exporter(name):
    """Given an exporter name or import path, return a class ready to be instantiated
    
    Raises ValueError if exporter is not found
    """
    
    if name == 'ipynb':
        name = 'notebook'

    try:
        return entrypoints.get_single('nbconvert.exporters', name).load()
    except entrypoints.NoSuchEntryPoint:
        try:
            return entrypoints.get_single('nbconvert.exporters', name.lower()).load()
        except entrypoints.NoSuchEntryPoint:
            pass
        
    if '.' in name:
        try:
            return import_item(name)
        except ImportError:
            log = get_logger()
            log.error("Error importing %s" % name, exc_info=True)

    raise ValueError('Unknown exporter "%s", did you mean one of: %s?'
                     % (name, ', '.join(get_export_names())))
Example #2
0
def _get_nbextension_metadata(module):
    """Get the list of nbextension paths associated with a Python module.

    Returns a tuple of (the module,             [{
        'section': 'notebook',
        'src': 'mockextension',
        'dest': '_mockdestination',
        'require': '_mockdestination/index'
    }])

    Parameters
    ----------

    module : str
        Importable Python module exposing the
        magic-named `_jupyter_nbextension_paths` function
    """
    m = import_item(module)
    if not hasattr(m, "_jupyter_nbextension_paths"):
        raise KeyError(
            "The Python module {} is not a valid nbextension, "
            "it is missing the `_jupyter_nbextension_paths()` method.".format(module)
        )
    nbexts = m._jupyter_nbextension_paths()
    return m, nbexts
def _get_nbextension_metadata(module):
    """Get the list of nbextension paths associated with a Python module."""
    m = import_item(module)
    if not hasattr(m, '_jupyter_nbextension_paths'):
        raise KeyError(
            'The Python module {} is not a valid nbextension'.format(module))
    nbexts = m._jupyter_nbextension_paths()
    return m, nbexts
Example #4
0
 def handle_comm_opened(comm, msg):
     """Static method, called when a widget is constructed."""
     class_name = str(msg['content']['data']['widget_class'])
     if class_name in Widget.widget_types:
         widget_class = Widget.widget_types[class_name]
     else:
         widget_class = import_item(class_name)
     widget = widget_class(comm=comm)
Example #5
0
def get_labextension_config_python(module):
    """Get the labextension configuration data associated  with a Python module. 

    Parameters
    -----------
    module : str
    Importable Python module exposing the
    magic-named `_jupyter_labextension_config` function
    """
    m = import_item(module)
    if not hasattr(m, '_jupyter_labextension_config'):
        return {}
    return m._jupyter_labextension_config()
Example #6
0
    def register_preprocessor(self, preprocessor, enabled=False):
        """
        Register a preprocessor.
        Preprocessors are classes that act upon the notebook before it is
        passed into the Jinja templating engine.  preprocessors are also
        capable of passing additional information to the Jinja
        templating engine.

        Parameters
        ----------
        preprocessor : :class:`~nbconvert.preprocessors.Preprocessor`
            A dotted module name, a type, or an instance
        enabled : bool
            Mark the preprocessor as enabled

        """
        if preprocessor is None:
            raise TypeError('preprocessor must not be None')
        isclass = isinstance(preprocessor, type)
        constructed = not isclass

        # Handle preprocessor's registration based on it's type
        if constructed and isinstance(preprocessor, py3compat.string_types):
            # Preprocessor is a string, import the namespace and recursively call
            # this register_preprocessor method
            preprocessor_cls = import_item(preprocessor)
            return self.register_preprocessor(preprocessor_cls, enabled)

        if constructed and hasattr(preprocessor, '__call__'):
            # Preprocessor is a function, no need to construct it.
            # Register and return the preprocessor.
            if enabled:
                preprocessor.enabled = True
            self._preprocessors.append(preprocessor)
            return preprocessor

        elif isclass and issubclass(preprocessor, HasTraits):
            # Preprocessor is configurable.  Make sure to pass in new default for
            # the enabled flag if one was specified.
            self.register_preprocessor(preprocessor(parent=self), enabled)

        elif isclass:
            # Preprocessor is not configurable, construct it
            self.register_preprocessor(preprocessor(), enabled)

        else:
            # Preprocessor is an instance of something without a __call__
            # attribute.
            raise TypeError('preprocessor must be callable or an importable constructor, got %r' % preprocessor)
    def _register_filter(self, environ, name, jinja_filter):
        """
        Register a filter.
        A filter is a function that accepts and acts on one string.
        The filters are accessible within the Jinja templating engine.

        Parameters
        ----------
        name : str
            name to give the filter in the Jinja engine
        filter : filter
        """
        if jinja_filter is None:
            raise TypeError('filter')
        isclass = isinstance(jinja_filter, type)
        constructed = not isclass

        #Handle filter's registration based on it's type
        if constructed and isinstance(jinja_filter, py3compat.string_types):
            #filter is a string, import the namespace and recursively call
            #this register_filter method
            filter_cls = import_item(jinja_filter)
            return self._register_filter(environ, name, filter_cls)

        if constructed and hasattr(jinja_filter, '__call__'):
            #filter is a function, no need to construct it.
            environ.filters[name] = jinja_filter
            return jinja_filter

        elif isclass and issubclass(jinja_filter, HasTraits):
            #filter is configurable.  Make sure to pass in new default for
            #the enabled flag if one was specified.
            filter_instance = jinja_filter(parent=self)
            self._register_filter(environ, name, filter_instance)

        elif isclass:
            #filter is not configurable, construct it
            filter_instance = jinja_filter()
            self._register_filter(environ, name, filter_instance)

        else:
            #filter is an instance of something without a __call__
            #attribute.
            raise TypeError('filter')
Example #8
0
def _get_labextension_metadata(module):
    """Get the list of labextension paths associated with a Python module.

    Returns a tuple of (the module,             [{
        'name': 'mockextension',
        'src': 'static',
    }])

    Parameters
    ----------

    module : str
        Importable Python module exposing the
        magic-named `_jupyter_labextension_paths` function
    """
    m = import_item(module)
    if not hasattr(m, '_jupyter_labextension_paths'):
        raise KeyError('The Python module {} is not a valid labextension'.format(module))
    labexts = m._jupyter_labextension_paths()
    return m, labexts
Example #9
0
 def from_notebook_node(self, nb, resources=None, **kw):
     langinfo = nb.metadata.get('language_info', {})
     
     # delegate to custom exporter, if specified
     exporter_name = langinfo.get('nbconvert_exporter')
     if exporter_name and exporter_name != 'script':
         self.log.debug("Loading script exporter: %s", exporter_name)
         from .export import exporter_map
         if exporter_name not in self._exporters:
             if exporter_name in exporter_map:
                 Exporter = exporter_map[exporter_name]
             else:
                 self.log.debug("Importing custom Exporter: %s", exporter_name)
                 Exporter = import_item(exporter_name)
             self._exporters[exporter_name] = Exporter(parent=self)
         exporter = self._exporters[exporter_name]
         return exporter.from_notebook_node(nb, resources, **kw)
     
     self.file_extension = langinfo.get('file_extension', '.txt')
     self.output_mimetype = langinfo.get('mimetype', 'text/plain')
     return super(ScriptExporter, self).from_notebook_node(nb, resources, **kw)
def _get_bundler_metadata(module):
    """Gets the list of bundlers associated with a Python package.
    
    Returns a tuple of (the module, [{
        'name': 'unique name of the bundler',
        'label': 'file menu item label for the bundler',
        'module_name': 'dotted package/module name containing the bundler',
        'group': 'download or deploy parent menu item'
    }])
    
    Parameters
    ----------

    module : str
        Importable Python module exposing the
        magic-named `_jupyter_bundler_paths` function    
    """
    m = import_item(module)
    if not hasattr(m, '_jupyter_bundler_paths'):
        raise KeyError('The Python module {} does not contain a valid bundler'.format(module))
    bundlers = m._jupyter_bundler_paths()
    return m, bundlers
Example #11
0
def _get_server_extension_metadata(module):
    """Load server extension metadata from a module.

    Returns a tuple of (
        the package as loaded
        a list of server extension specs: [
            {
                "module": "mockextension"
            }
        ]
    )

    Parameters
    ----------

    module : str
        Importable Python module exposing the
        magic-named `_jupyter_server_extension_paths` function
    """
    m = import_item(module)
    if not hasattr(m, '_jupyter_server_extension_paths'):
        raise KeyError(u'The Python module {} does not include any valid server extensions'.format(module))
    return m, m._jupyter_server_extension_paths()
 def _reset_registry_on_reset(self, change: dict) -> None:
     self.registry = import_item(change['new'])()
Example #13
0
 def _writer_class_changed(self, change):
     new = change['new']
     if new.lower() in self.writer_aliases:
         new = self.writer_aliases[new.lower()]
     self.writer_factory = import_item(new)
Example #14
0
 def test_import_unicode(self):
     self.assertIs(os, import_item('os'))
     self.assertIs(os.path, import_item('os.path'))
     self.assertIs(os.path.join, import_item('os.path.join'))
 def _postprocessor_class_changed(self, change):
     new = change['new']
     if new.lower() in self.postprocessor_aliases:
         new = self.postprocessor_aliases[new.lower()]
     if new:
         self.postprocessor_factory = import_item(new)
 def _writer_class_changed(self, change):
     new = change['new']
     if new.lower() in self.writer_aliases:
         new = self.writer_aliases[new.lower()]
     self.writer_factory = import_item(new)
Example #17
0
    def autoawait(self, parameter_s):
        """
        Allow to change the status of the autoawait option.

        This allow you to set a specific asynchronous code runner.

        If no value is passed, print the currently used asynchronous integration
        and whether it is activated.

        It can take a number of value evaluated in the following order:

        - False/false/off deactivate autoawait integration
        - True/true/on activate autoawait integration using configured default
          loop
        - asyncio/curio/trio activate autoawait integration and use integration
          with said library.

        - `sync` turn on the pseudo-sync integration (mostly used for
          `IPython.embed()` which does not run IPython with a real eventloop and
          deactivate running asynchronous code. Turning on Asynchronous code with
          the pseudo sync loop is undefined behavior and may lead IPython to crash.

        If the passed parameter does not match any of the above and is a python
        identifier, get said object from user namespace and set it as the
        runner, and activate autoawait. 

        If the object is a fully qualified object name, attempt to import it and
        set it as the runner, and activate autoawait.
        
        
        The exact behavior of autoawait is experimental and subject to change
        across version of IPython and Python.
        """

        param = parameter_s.strip()
        d = {True: "on", False: "off"}

        if not param:
            print(
                "IPython autoawait is `{}`, and set to use `{}`".format(
                    d[self.shell.autoawait], self.shell.loop_runner
                )
            )
            return None

        if param.lower() in ("false", "off"):
            self.shell.autoawait = False
            return None
        if param.lower() in ("true", "on"):
            self.shell.autoawait = True
            return None

        if param in self.shell.loop_runner_map:
            self.shell.loop_runner, self.shell.autoawait = self.shell.loop_runner_map[
                param
            ]
            return None

        if param in self.shell.user_ns:
            self.shell.loop_runner = self.shell.user_ns[param]
            self.shell.autoawait = True
            return None

        runner = import_item(param)

        self.shell.loop_runner = runner
        self.shell.autoawait = True
Example #18
0
 def handle_comm_opened(comm, msg):
     """Static method, called when a widget is constructed."""
     widget_class = import_item(str(msg['content']['data']['widget_class']))
     widget = widget_class(comm=comm)
 def _auto_registry(self) -> All:
     return import_item(self.registry_type)()
Example #20
0
 def _postprocessor_class_changed(self, change):
     new = change['new']
     if new.lower() in self.postprocessor_aliases:
         new = self.postprocessor_aliases[new.lower()]
     if new:
         self.postprocessor_factory = import_item(new)
    def autoawait(self, parameter_s):
        """
        Allow to change the status of the autoawait option.

        This allow you to set a specific asynchronous code runner.

        If no value is passed, print the currently used asynchronous integration
        and whether it is activated.

        It can take a number of value evaluated in the following order:

        - False/false/off deactivate autoawait integration
        - True/true/on activate autoawait integration using configured default
          loop
        - asyncio/curio/trio activate autoawait integration and use integration
          with said library.

        - `sync` turn on the pseudo-sync integration (mostly used for
          `IPython.embed()` which does not run IPython with a real eventloop and
          deactivate running asynchronous code. Turning on Asynchronous code with
          the pseudo sync loop is undefined behavior and may lead IPython to crash.

        If the passed parameter does not match any of the above and is a python
        identifier, get said object from user namespace and set it as the
        runner, and activate autoawait. 

        If the object is a fully qualified object name, attempt to import it and
        set it as the runner, and activate autoawait.
        
        
        The exact behavior of autoawait is experimental and subject to change
        across version of IPython and Python.
        """

        param = parameter_s.strip()
        d = {True: "on", False: "off"}

        if not param:
            print("IPython autoawait is `{}`, and set to use `{}`".format(
                d[self.shell.autoawait],
                self.shell.loop_runner
            ))
            return None

        if param.lower() in ('false', 'off'):
            self.shell.autoawait = False
            return None
        if param.lower() in ('true', 'on'):
            self.shell.autoawait = True
            return None

        if param in self.shell.loop_runner_map:
            self.shell.loop_runner, self.shell.autoawait = self.shell.loop_runner_map[param]
            return None

        if param in self.shell.user_ns :
            self.shell.loop_runner = self.shell.user_ns[param]
            self.shell.autoawait = True
            return None

        runner = import_item(param)

        self.shell.loop_runner = runner
        self.shell.autoawait = True
Example #22
0
 def handle_comm_opened(comm, msg):
     """Static method, called when a widget is constructed."""
     widget_class = import_item(str(msg['content']['data']['widget_class']))
     widget = widget_class(comm=comm)