__init__.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. """The Jupyter notebook format
  2. Use this module to read or write notebook files as particular nbformat versions.
  3. """
  4. # Copyright (c) IPython Development Team.
  5. # Distributed under the terms of the Modified BSD License.
  6. import io
  7. from ipython_genutils import py3compat
  8. from traitlets.log import get_logger
  9. from ._version import version_info, __version__
  10. from . import v1
  11. from . import v2
  12. from . import v3
  13. from . import v4
  14. from .sentinel import Sentinel
  15. __all__ = ['versions', 'validate', 'ValidationError', 'convert', 'from_dict',
  16. 'NotebookNode', 'current_nbformat', 'current_nbformat_minor',
  17. 'NBFormatError', 'NO_CONVERT', 'reads', 'read', 'writes', 'write',
  18. 'version_info', '__version__',
  19. ]
  20. versions = {
  21. 1: v1,
  22. 2: v2,
  23. 3: v3,
  24. 4: v4,
  25. }
  26. from .validator import validate, ValidationError
  27. from .converter import convert
  28. from . import reader
  29. from .notebooknode import from_dict, NotebookNode
  30. from .v4 import (
  31. nbformat as current_nbformat,
  32. nbformat_minor as current_nbformat_minor,
  33. )
  34. class NBFormatError(ValueError):
  35. pass
  36. # no-conversion singleton
  37. NO_CONVERT = Sentinel('NO_CONVERT', __name__,
  38. """Value to prevent nbformat to convert notebooks to most recent version.
  39. """)
  40. def reads(s, as_version, **kwargs):
  41. """Read a notebook from a string and return the NotebookNode object as the given version.
  42. The string can contain a notebook of any version.
  43. The notebook will be returned `as_version`, converting, if necessary.
  44. Notebook format errors will be logged.
  45. Parameters
  46. ----------
  47. s : unicode
  48. The raw unicode string to read the notebook from.
  49. as_version : int
  50. The version of the notebook format to return.
  51. The notebook will be converted, if necessary.
  52. Pass nbformat.NO_CONVERT to prevent conversion.
  53. Returns
  54. -------
  55. nb : NotebookNode
  56. The notebook that was read.
  57. """
  58. nb = reader.reads(s, **kwargs)
  59. if as_version is not NO_CONVERT:
  60. nb = convert(nb, as_version)
  61. try:
  62. validate(nb)
  63. except ValidationError as e:
  64. get_logger().error("Notebook JSON is invalid: %s", e)
  65. return nb
  66. def writes(nb, version=NO_CONVERT, **kwargs):
  67. """Write a notebook to a string in a given format in the given nbformat version.
  68. Any notebook format errors will be logged.
  69. Parameters
  70. ----------
  71. nb : NotebookNode
  72. The notebook to write.
  73. version : int, optional
  74. The nbformat version to write.
  75. If unspecified, or specified as nbformat.NO_CONVERT,
  76. the notebook's own version will be used and no conversion performed.
  77. Returns
  78. -------
  79. s : unicode
  80. The notebook as a JSON string.
  81. """
  82. if version is not NO_CONVERT:
  83. nb = convert(nb, version)
  84. else:
  85. version, _ = reader.get_version(nb)
  86. try:
  87. validate(nb)
  88. except ValidationError as e:
  89. get_logger().error("Notebook JSON is invalid: %s", e)
  90. return versions[version].writes_json(nb, **kwargs)
  91. def read(fp, as_version, **kwargs):
  92. """Read a notebook from a file as a NotebookNode of the given version.
  93. The string can contain a notebook of any version.
  94. The notebook will be returned `as_version`, converting, if necessary.
  95. Notebook format errors will be logged.
  96. Parameters
  97. ----------
  98. fp : file or str
  99. A file-like object with a read method that returns unicode (use
  100. ``io.open()`` in Python 2), or a path to a file.
  101. as_version: int
  102. The version of the notebook format to return.
  103. The notebook will be converted, if necessary.
  104. Pass nbformat.NO_CONVERT to prevent conversion.
  105. Returns
  106. -------
  107. nb : NotebookNode
  108. The notebook that was read.
  109. """
  110. if isinstance(fp, (py3compat.unicode_type, bytes)):
  111. with io.open(fp, encoding='utf-8') as f:
  112. return read(f, as_version, **kwargs)
  113. return reads(fp.read(), as_version, **kwargs)
  114. def write(nb, fp, version=NO_CONVERT, **kwargs):
  115. """Write a notebook to a file in a given nbformat version.
  116. The file-like object must accept unicode input.
  117. Parameters
  118. ----------
  119. nb : NotebookNode
  120. The notebook to write.
  121. fp : file or str
  122. Any file-like object with a write method that accepts unicode, or
  123. a path to write a file.
  124. version : int, optional
  125. The nbformat version to write.
  126. If nb is not this version, it will be converted.
  127. If unspecified, or specified as nbformat.NO_CONVERT,
  128. the notebook's own version will be used and no conversion performed.
  129. """
  130. if isinstance(fp, (py3compat.unicode_type, bytes)):
  131. with io.open(fp, 'w', encoding='utf-8') as f:
  132. return write(nb, f, version=version, **kwargs)
  133. s = writes(nb, version, **kwargs)
  134. if isinstance(s, bytes):
  135. s = s.decode('utf8')
  136. fp.write(s)
  137. if not s.endswith(u'\n'):
  138. fp.write(u'\n')