notebook.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """NotebookExporter class"""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from .exporter import Exporter
  5. import nbformat
  6. from traitlets import Enum, default
  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(list(nbformat.versions),
  13. default_value=nbformat.current_nbformat,
  14. help="""The nbformat version to write.
  15. Use this to downgrade notebooks.
  16. """
  17. ).tag(config=True)
  18. @default('file_extension')
  19. def _file_extension_default(self):
  20. return '.ipynb'
  21. output_mimetype = 'application/json'
  22. export_from_notebook = "Notebook"
  23. def from_notebook_node(self, nb, resources=None, **kw):
  24. nb_copy, resources = super(NotebookExporter, self).from_notebook_node(nb, resources, **kw)
  25. if self.nbformat_version != nb_copy.nbformat:
  26. resources['output_suffix'] = '.v%i' % self.nbformat_version
  27. else:
  28. resources['output_suffix'] = '.nbconvert'
  29. output = nbformat.writes(nb_copy, version=self.nbformat_version)
  30. if not output.endswith("\n"):
  31. output = output + "\n"
  32. return output, resources