Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nbconvert/exporters/base.py: 25%
69 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 06:10 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 06:10 +0000
1"""Module containing single call export functions."""
3# Copyright (c) Jupyter Development Team.
4# Distributed under the terms of the Modified BSD License.
6import os
7import sys
9if sys.version_info < (3, 10):
10 from importlib_metadata import entry_points
11else:
12 from importlib.metadata import entry_points
13from nbformat import NotebookNode
14from traitlets.config import get_config
15from traitlets.log import get_logger
16from traitlets.utils.importstring import import_item
18from .exporter import Exporter
20# -----------------------------------------------------------------------------
21# Functions
22# -----------------------------------------------------------------------------
24__all__ = [
25 "export",
26 "Exporter",
27 "get_exporter",
28 "get_export_names",
29 "ExporterNameError",
30]
33class ExporterNameError(NameError):
34 """An exporter name error."""
36 pass
39class ExporterDisabledError(ValueError):
40 """An exporter disabled error."""
42 pass
45def export(exporter, nb, **kw):
46 """
47 Export a notebook object using specific exporter class.
49 Parameters
50 ----------
51 exporter : ``Exporter`` class or instance
52 Class or instance of the exporter that should be used. If the
53 method initializes its own instance of the class, it is ASSUMED that
54 the class type provided exposes a constructor (``__init__``) with the same
55 signature as the base Exporter class.
56 nb : :class:`~nbformat.NotebookNode`
57 The notebook to export.
58 config : config (optional, keyword arg)
59 User configuration instance.
60 resources : dict (optional, keyword arg)
61 Resources used in the conversion process.
63 Returns
64 -------
65 tuple
66 output : str
67 The resulting converted notebook.
68 resources : dictionary
69 Dictionary of resources used prior to and during the conversion
70 process.
71 """
73 # Check arguments
74 if exporter is None:
75 msg = "Exporter is None"
76 raise TypeError(msg)
77 elif not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
78 msg = "exporter does not inherit from Exporter (base)"
79 raise TypeError(msg)
80 if nb is None:
81 msg = "nb is None"
82 raise TypeError(msg)
84 # Create the exporter
85 resources = kw.pop("resources", None)
86 exporter_instance = exporter if isinstance(exporter, Exporter) else exporter(**kw)
88 # Try to convert the notebook using the appropriate conversion function.
89 if isinstance(nb, NotebookNode):
90 output, resources = exporter_instance.from_notebook_node(nb, resources)
91 elif isinstance(nb, (str,)):
92 output, resources = exporter_instance.from_filename(nb, resources)
93 else:
94 output, resources = exporter_instance.from_file(nb, resources)
95 return output, resources
98def get_exporter(name, config=get_config()): # noqa
99 """Given an exporter name or import path, return a class ready to be instantiated
101 Raises ExporterName if exporter is not found or ExporterDisabledError if not enabled
102 """
104 if name == "ipynb":
105 name = "notebook"
107 try:
108 exporters = entry_points(group="nbconvert.exporters")
109 exporter = [e for e in exporters if e.name == name or e.name == name.lower()][0].load()
110 if getattr(exporter(config=config), "enabled", True):
111 return exporter
112 else:
113 raise ExporterDisabledError('Exporter "%s" disabled in configuration' % (name))
114 except IndexError:
115 pass
117 if "." in name:
118 try:
119 exporter = import_item(name)
120 if getattr(exporter(config=config), "enabled", True):
121 return exporter
122 else:
123 raise ExporterDisabledError('Exporter "%s" disabled in configuration' % (name))
124 except ImportError:
125 log = get_logger()
126 log.error("Error importing %s" % name, exc_info=True)
128 msg = 'Unknown exporter "{}", did you mean one of: {}?'.format(
129 name, ", ".join(get_export_names())
130 )
131 raise ExporterNameError(msg)
134def get_export_names(config=get_config()): # noqa
135 """Return a list of the currently supported export targets
137 Exporters can be found in external packages by registering
138 them as an nbconvert.exporter entrypoint.
139 """
140 exporters = sorted(e.name for e in entry_points(group="nbconvert.exporters"))
141 if os.environ.get("NBCONVERT_DISABLE_CONFIG_EXPORTERS"):
142 get_logger().info(
143 "Config exporter loading disabled, no additional exporters will be automatically included."
144 )
145 return exporters
147 enabled_exporters = []
148 for exporter_name in exporters:
149 try:
150 e = get_exporter(exporter_name)(config=config)
151 if e.enabled:
152 enabled_exporters.append(exporter_name)
153 except (ExporterDisabledError, ValueError):
154 pass
155 return enabled_exporters