reader.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """API for reading notebooks of different versions"""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import json
  5. class NotJSONError(ValueError):
  6. pass
  7. def parse_json(s, **kwargs):
  8. """Parse a JSON string into a dict."""
  9. try:
  10. nb_dict = json.loads(s, **kwargs)
  11. except ValueError:
  12. # Limit the error message to 80 characters. Display whatever JSON will fit.
  13. raise NotJSONError(("Notebook does not appear to be JSON: %r" % s)[:77] + "...")
  14. return nb_dict
  15. # High level API
  16. def get_version(nb):
  17. """Get the version of a notebook.
  18. Parameters
  19. ----------
  20. nb : dict
  21. NotebookNode or dict containing notebook data.
  22. Returns
  23. -------
  24. Tuple containing major (int) and minor (int) version numbers
  25. """
  26. major = nb.get('nbformat', 1)
  27. minor = nb.get('nbformat_minor', 0)
  28. return (major, minor)
  29. def reads(s, **kwargs):
  30. """Read a notebook from a json string and return the
  31. NotebookNode object.
  32. This function properly reads notebooks of any version. No version
  33. conversion is performed.
  34. Parameters
  35. ----------
  36. s : unicode
  37. The raw unicode string to read the notebook from.
  38. Returns
  39. -------
  40. nb : NotebookNode
  41. The notebook that was read.
  42. """
  43. from . import versions, NBFormatError
  44. nb_dict = parse_json(s, **kwargs)
  45. (major, minor) = get_version(nb_dict)
  46. if major in versions:
  47. return versions[major].to_notebook_json(nb_dict, minor=minor)
  48. else:
  49. raise NBFormatError('Unsupported nbformat version %s' % major)
  50. def read(fp, **kwargs):
  51. """Read a notebook from a file and return the NotebookNode object.
  52. This function properly reads notebooks of any version. No version
  53. conversion is performed.
  54. Parameters
  55. ----------
  56. fp : file
  57. Any file-like object with a read method.
  58. Returns
  59. -------
  60. nb : NotebookNode
  61. The notebook that was read.
  62. """
  63. return reads(fp.read(), **kwargs)