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