nbbase.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. """Python API for composing notebook elements
  2. The Python representation of a notebook is a nested structure of
  3. dictionary subclasses that support attribute access
  4. (ipython_genutils.ipstruct.Struct). The functions in this module are merely
  5. helpers to build the structs in the right form.
  6. """
  7. # Copyright (c) IPython Development Team.
  8. # Distributed under the terms of the Modified BSD License.
  9. from ..notebooknode import NotebookNode
  10. # Change this when incrementing the nbformat version
  11. nbformat = 4
  12. nbformat_minor = 2
  13. nbformat_schema = 'nbformat.v4.schema.json'
  14. def validate(node, ref=None):
  15. """validate a v4 node"""
  16. from .. import validate
  17. return validate(node, ref=ref, version=nbformat)
  18. def new_output(output_type, data=None, **kwargs):
  19. """Create a new output, to go in the ``cell.outputs`` list of a code cell."""
  20. output = NotebookNode(output_type=output_type)
  21. # populate defaults:
  22. if output_type == 'stream':
  23. output.name = u'stdout'
  24. output.text = u''
  25. elif output_type in {'execute_result', 'display_data'}:
  26. output.metadata = NotebookNode()
  27. output.data = NotebookNode()
  28. # load from args:
  29. output.update(kwargs)
  30. if data is not None:
  31. output.data = data
  32. # validate
  33. validate(output, output_type)
  34. return output
  35. def output_from_msg(msg):
  36. """Create a NotebookNode for an output from a kernel's IOPub message.
  37. Returns
  38. -------
  39. NotebookNode: the output as a notebook node.
  40. Raises
  41. ------
  42. ValueError: if the message is not an output message.
  43. """
  44. msg_type = msg['header']['msg_type']
  45. content = msg['content']
  46. if msg_type == 'execute_result':
  47. return new_output(output_type=msg_type,
  48. metadata=content['metadata'],
  49. data=content['data'],
  50. execution_count=content['execution_count'],
  51. )
  52. elif msg_type == 'stream':
  53. return new_output(output_type=msg_type,
  54. name=content['name'],
  55. text=content['text'],
  56. )
  57. elif msg_type == 'display_data':
  58. return new_output(output_type=msg_type,
  59. metadata=content['metadata'],
  60. data=content['data'],
  61. )
  62. elif msg_type == 'error':
  63. return new_output(output_type=msg_type,
  64. ename=content['ename'],
  65. evalue=content['evalue'],
  66. traceback=content['traceback'],
  67. )
  68. else:
  69. raise ValueError("Unrecognized output msg type: %r" % msg_type)
  70. def new_code_cell(source='', **kwargs):
  71. """Create a new code cell"""
  72. cell = NotebookNode(
  73. cell_type='code',
  74. metadata=NotebookNode(),
  75. execution_count=None,
  76. source=source,
  77. outputs=[],
  78. )
  79. cell.update(kwargs)
  80. validate(cell, 'code_cell')
  81. return cell
  82. def new_markdown_cell(source='', **kwargs):
  83. """Create a new markdown cell"""
  84. cell = NotebookNode(
  85. cell_type='markdown',
  86. source=source,
  87. metadata=NotebookNode(),
  88. )
  89. cell.update(kwargs)
  90. validate(cell, 'markdown_cell')
  91. return cell
  92. def new_raw_cell(source='', **kwargs):
  93. """Create a new raw cell"""
  94. cell = NotebookNode(
  95. cell_type='raw',
  96. source=source,
  97. metadata=NotebookNode(),
  98. )
  99. cell.update(kwargs)
  100. validate(cell, 'raw_cell')
  101. return cell
  102. def new_notebook(**kwargs):
  103. """Create a new notebook"""
  104. nb = NotebookNode(
  105. nbformat=nbformat,
  106. nbformat_minor=nbformat_minor,
  107. metadata=NotebookNode(),
  108. cells=[],
  109. )
  110. nb.update(kwargs)
  111. validate(nb)
  112. return nb