convert.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """Code for converting notebooks to and from the v2 format.
  2. Authors:
  3. * Brian Granger
  4. * Jonathan Frederic
  5. """
  6. #-----------------------------------------------------------------------------
  7. # Copyright (C) 2008-2011 The IPython Development Team
  8. #
  9. # Distributed under the terms of the BSD License. The full license is in
  10. # the file COPYING, distributed as part of this software.
  11. #-----------------------------------------------------------------------------
  12. #-----------------------------------------------------------------------------
  13. # Imports
  14. #-----------------------------------------------------------------------------
  15. from .nbbase import (
  16. new_code_cell, new_text_cell, new_worksheet, new_notebook, new_output
  17. )
  18. #-----------------------------------------------------------------------------
  19. # Code
  20. #-----------------------------------------------------------------------------
  21. def upgrade(nb, from_version=1):
  22. """Convert a notebook to the v2 format.
  23. Parameters
  24. ----------
  25. nb : NotebookNode
  26. The Python representation of the notebook to convert.
  27. from_version : int
  28. The version of the notebook to convert from.
  29. """
  30. if from_version == 1:
  31. newnb = new_notebook()
  32. ws = new_worksheet()
  33. for cell in nb.cells:
  34. if cell.cell_type == u'code':
  35. newcell = new_code_cell(input=cell.get('code'),prompt_number=cell.get('prompt_number'))
  36. elif cell.cell_type == u'text':
  37. newcell = new_text_cell(u'markdown',source=cell.get('text'))
  38. ws.cells.append(newcell)
  39. newnb.worksheets.append(ws)
  40. return newnb
  41. else:
  42. raise ValueError('Cannot convert a notebook from v%s to v2' % from_version)
  43. def downgrade(nb):
  44. """Convert a v2 notebook to v1.
  45. Parameters
  46. ----------
  47. nb : NotebookNode
  48. The Python representation of the notebook to convert.
  49. """
  50. raise Exception("Downgrade from notebook v2 to v1 is not supported.")