##// END OF EJS Templates
deprecate format arg in reads/writes...
MinRK -
Show More
@@ -1,209 +1,186 b''
1 1 """The official API for working with notebooks in the current format version."""
2 2
3 3 # Copyright (c) IPython Development Team.
4 4 # Distributed under the terms of the Modified BSD License.
5 5
6 6 from __future__ import print_function
7 7
8 8 import re
9
10 from IPython.utils.py3compat import unicode_type
9 import warnings
11 10
12 11 from IPython.nbformat.v3 import (
13 12 NotebookNode,
14 13 new_code_cell, new_text_cell, new_notebook, new_output, new_worksheet,
15 14 parse_filename, new_metadata, new_author, new_heading_cell, nbformat,
16 nbformat_minor, nbformat_schema, to_notebook_json
15 nbformat_minor, nbformat_schema, to_notebook_json,
17 16 )
18 17 from IPython.nbformat import v3 as _v_latest
19 18
20 19 from .reader import reads as reader_reads
21 20 from .reader import versions
22 21 from .convert import convert
23 22 from .validator import validate, ValidationError
24 23
25 24 from IPython.utils.log import get_logger
26 25
27 26 __all__ = ['NotebookNode', 'new_code_cell', 'new_text_cell', 'new_notebook',
28 27 'new_output', 'new_worksheet', 'parse_filename', 'new_metadata', 'new_author',
29 28 'new_heading_cell', 'nbformat', 'nbformat_minor', 'nbformat_schema',
30 29 'to_notebook_json', 'convert', 'validate', 'NBFormatError', 'parse_py',
31 30 'reads_json', 'writes_json', 'reads_py', 'writes_py', 'reads', 'writes', 'read',
32 31 'write']
33 32
34 33 current_nbformat = nbformat
35 34 current_nbformat_minor = nbformat_minor
36 35 current_nbformat_module = _v_latest.__name__
37 36
38 37
39 38 class NBFormatError(ValueError):
40 39 pass
41 40
42 41
42 def _warn_format():
43 warnings.warn("""Non-JSON file support in nbformat is deprecated.
44 Use nbconvert to create files of other formats.""")
45
46
43 47 def parse_py(s, **kwargs):
44 48 """Parse a string into a (nbformat, string) tuple."""
45 49 nbf = current_nbformat
46 50 nbm = current_nbformat_minor
47 51
48 52 pattern = r'# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>'
49 53 m = re.search(pattern,s)
50 54 if m is not None:
51 55 digits = m.group('nbformat').split('.')
52 56 nbf = int(digits[0])
53 57 if len(digits) > 1:
54 58 nbm = int(digits[1])
55 59
56 60 return nbf, nbm, s
57 61
58 62
59 63 def reads_json(nbjson, **kwargs):
60 """Read a JSON notebook from a string and return the NotebookNode
61 object. Report if any JSON format errors are detected.
62
63 """
64 nb = reader_reads(nbjson, **kwargs)
65 nb_current = convert(nb, current_nbformat)
66 try:
67 validate(nb_current)
68 except ValidationError as e:
69 get_logger().error("Notebook JSON is invalid: %s", e)
70 return nb_current
71
64 """DEPRECATED, use reads"""
65 warnings.warn("reads_json is deprecated, use reads")
66 return reads(nbjson)
72 67
73 68 def writes_json(nb, **kwargs):
74 """Take a NotebookNode object and write out a JSON string. Report if
75 any JSON format errors are detected.
76
77 """
78 try:
79 validate(nb)
80 except ValidationError as e:
81 get_logger().error("Notebook JSON is invalid: %s", e)
82 nbjson = versions[current_nbformat].writes_json(nb, **kwargs)
83 return nbjson
84
69 """DEPRECATED, use writes"""
70 warnings.warn("writes_json is deprecated, use writes")
71 return writes(nb, **kwargs)
85 72
86 73 def reads_py(s, **kwargs):
87 """Read a .py notebook from a string and return the NotebookNode object."""
74 """DEPRECATED: use nbconvert"""
75 _warn_format()
88 76 nbf, nbm, s = parse_py(s, **kwargs)
89 77 if nbf in (2, 3):
90 78 nb = versions[nbf].to_notebook_py(s, **kwargs)
91 79 else:
92 80 raise NBFormatError('Unsupported PY nbformat version: %i' % nbf)
93 81 return nb
94 82
95
96 83 def writes_py(nb, **kwargs):
97 # nbformat 3 is the latest format that supports py
84 """DEPRECATED: use nbconvert"""
85 _warn_format()
98 86 return versions[3].writes_py(nb, **kwargs)
99 87
100 88
101 89 # High level API
102 90
103 91
104 92 def reads(s, format='DEPRECATED', version=current_nbformat, **kwargs):
105 93 """Read a notebook from a string and return the NotebookNode object.
106 94
107 95 This function properly handles notebooks of any version. The notebook
108 96 returned will always be in the current version's format.
109 97
110 98 Parameters
111 99 ----------
112 100 s : unicode
113 101 The raw unicode string to read the notebook from.
114 102
115 103 Returns
116 104 -------
117 105 nb : NotebookNode
118 106 The notebook that was read.
119 107 """
120 nb = versions[version].reads_json(s, **kwargs)
108 if format not in {'DEPRECATED', 'json'}:
109 _warn_format()
110 nb = reader_reads(s, **kwargs)
121 111 nb = convert(nb, version)
122 112 try:
123 113 validate(nb)
124 114 except ValidationError as e:
125 115 get_logger().error("Notebook JSON is invalid: %s", e)
126 116 return nb
127 117
128 118
129 119 def writes(nb, format='DEPRECATED', version=current_nbformat, **kwargs):
130 120 """Write a notebook to a string in a given format in the current nbformat version.
131 121
132 122 This function always writes the notebook in the current nbformat version.
133 123
134 124 Parameters
135 125 ----------
136 126 nb : NotebookNode
137 127 The notebook to write.
138 128 version : int
139 129 The nbformat version to write.
140 130 Used for downgrading notebooks.
141 131
142 132 Returns
143 133 -------
144 134 s : unicode
145 135 The notebook string.
146 136 """
137 if format not in {'DEPRECATED', 'json'}:
138 _warn_format()
139 nb = convert(nb, version)
147 140 try:
148 141 validate(nb)
149 142 except ValidationError as e:
150 143 get_logger().error("Notebook JSON is invalid: %s", e)
151 nb = convert(nb, version)
152 144 return versions[version].writes_json(nb, **kwargs)
153 145
154 146
155 147 def read(fp, format='DEPRECATED', **kwargs):
156 148 """Read a notebook from a file and return the NotebookNode object.
157 149
158 150 This function properly handles notebooks of any version. The notebook
159 151 returned will always be in the current version's format.
160 152
161 153 Parameters
162 154 ----------
163 155 fp : file
164 156 Any file-like object with a read method.
165 157
166 158 Returns
167 159 -------
168 160 nb : NotebookNode
169 161 The notebook that was read.
170 162 """
171 163 return reads(fp.read(), **kwargs)
172 164
173 165
174 166 def write(nb, fp, format='DEPRECATED', **kwargs):
175 167 """Write a notebook to a file in a given format in the current nbformat version.
176 168
177 169 This function always writes the notebook in the current nbformat version.
178 170
179 171 Parameters
180 172 ----------
181 173 nb : NotebookNode
182 174 The notebook to write.
183 175 fp : file
184 176 Any file-like object with a write method.
185 177 format : (u'json', u'ipynb', u'py')
186 178 The format to write the notebook in.
187 179
188 180 Returns
189 181 -------
190 182 s : unicode
191 183 The notebook string.
192 184 """
193 185 return fp.write(writes(nb, **kwargs))
194 186
195 def _convert_to_metadata():
196 """Convert to a notebook having notebook metadata."""
197 import glob
198 for fname in glob.glob('*.ipynb'):
199 print('Converting file:',fname)
200 with open(fname,'r') as f:
201 nb = read(f,u'json')
202 md = new_metadata()
203 if u'name' in nb:
204 md.name = nb.name
205 del nb[u'name']
206 nb.metadata = md
207 with open(fname,'w') as f:
208 write(nb, f, u'json')
209
General Comments 0
You need to be logged in to leave comments. Login now