notebook.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """NotebookExporter class"""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import nbformat
  5. from traitlets import Enum, default
  6. from .exporter import Exporter
  7. class NotebookExporter(Exporter):
  8. """Exports to an IPython notebook.
  9. This is useful when you want to use nbconvert's preprocessors to operate on
  10. a notebook (e.g. to execute it) and then write it back to a notebook file.
  11. """
  12. nbformat_version = Enum(
  13. list(nbformat.versions),
  14. default_value=nbformat.current_nbformat,
  15. help="""The nbformat version to write.
  16. Use this to downgrade notebooks.
  17. """,
  18. ).tag(config=True)
  19. @default("file_extension")
  20. def _file_extension_default(self):
  21. return ".ipynb"
  22. output_mimetype = "application/json"
  23. export_from_notebook = "Notebook"
  24. def from_notebook_node(self, nb, resources=None, **kw):
  25. """Convert from notebook node."""
  26. nb_copy, resources = super().from_notebook_node(nb, resources, **kw)
  27. if self.nbformat_version != nb_copy.nbformat:
  28. resources["output_suffix"] = ".v%i" % self.nbformat_version
  29. else:
  30. resources["output_suffix"] = ".nbconvert"
  31. output = nbformat.writes(nb_copy, version=self.nbformat_version)
  32. if not output.endswith("\n"):
  33. output = output + "\n"
  34. return output, resources