base.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. """Module containing single call export functions."""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import warnings
  5. import entrypoints
  6. from traitlets.log import get_logger
  7. from traitlets.utils.importstring import import_item
  8. from nbformat import NotebookNode
  9. from ipython_genutils.py3compat import string_types
  10. from .exporter import Exporter
  11. #-----------------------------------------------------------------------------
  12. # Functions
  13. #-----------------------------------------------------------------------------
  14. __all__ = [
  15. 'export',
  16. 'Exporter',
  17. 'get_exporter',
  18. 'get_export_names',
  19. 'ExporterNameError',
  20. ]
  21. class ExporterNameError(NameError):
  22. pass
  23. def export(exporter, nb, **kw):
  24. """
  25. Export a notebook object using specific exporter class.
  26. Parameters
  27. ----------
  28. exporter : :class:`~nbconvert.exporters.exporter.Exporter` class or instance
  29. Class or instance of the exporter that should be used. If the
  30. method initializes its own instance of the class, it is ASSUMED that
  31. the class type provided exposes a constructor (``__init__``) with the same
  32. signature as the base Exporter class.
  33. nb : :class:`~nbformat.NotebookNode`
  34. The notebook to export.
  35. config : config (optional, keyword arg)
  36. User configuration instance.
  37. resources : dict (optional, keyword arg)
  38. Resources used in the conversion process.
  39. Returns
  40. -------
  41. tuple
  42. output : str
  43. The resulting converted notebook.
  44. resources : dictionary
  45. Dictionary of resources used prior to and during the conversion
  46. process.
  47. """
  48. #Check arguments
  49. if exporter is None:
  50. raise TypeError("Exporter is None")
  51. elif not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
  52. raise TypeError("exporter does not inherit from Exporter (base)")
  53. if nb is None:
  54. raise TypeError("nb is None")
  55. #Create the exporter
  56. resources = kw.pop('resources', None)
  57. if isinstance(exporter, Exporter):
  58. exporter_instance = exporter
  59. else:
  60. exporter_instance = exporter(**kw)
  61. #Try to convert the notebook using the appropriate conversion function.
  62. if isinstance(nb, NotebookNode):
  63. output, resources = exporter_instance.from_notebook_node(nb, resources)
  64. elif isinstance(nb, string_types):
  65. output, resources = exporter_instance.from_filename(nb, resources)
  66. else:
  67. output, resources = exporter_instance.from_file(nb, resources)
  68. return output, resources
  69. def get_exporter(name):
  70. """Given an exporter name or import path, return a class ready to be instantiated
  71. Raises ValueError if exporter is not found
  72. """
  73. if name == 'ipynb':
  74. name = 'notebook'
  75. try:
  76. return entrypoints.get_single('nbconvert.exporters', name).load()
  77. except entrypoints.NoSuchEntryPoint:
  78. try:
  79. return entrypoints.get_single('nbconvert.exporters', name.lower()).load()
  80. except entrypoints.NoSuchEntryPoint:
  81. pass
  82. if '.' in name:
  83. try:
  84. return import_item(name)
  85. except ImportError:
  86. log = get_logger()
  87. log.error("Error importing %s" % name, exc_info=True)
  88. raise ValueError('Unknown exporter "%s", did you mean one of: %s?'
  89. % (name, ', '.join(get_export_names())))
  90. def get_export_names():
  91. """Return a list of the currently supported export targets
  92. Exporters can be found in external packages by registering
  93. them as an nbconvert.exporter entrypoint.
  94. """
  95. return sorted(entrypoints.get_group_named('nbconvert.exporters'))