##// END OF EJS Templates
Fixing names for aliases.
damianavila -
Show More
@@ -1,323 +1,323 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """NBConvert is a utility for conversion of .ipynb files.
2 """NBConvert is a utility for conversion of .ipynb files.
3
3
4 Command-line interface for the NbConvert conversion utility.
4 Command-line interface for the NbConvert conversion utility.
5 """
5 """
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 #Copyright (c) 2013, the IPython Development Team.
7 #Copyright (c) 2013, the IPython Development Team.
8 #
8 #
9 #Distributed under the terms of the Modified BSD License.
9 #Distributed under the terms of the Modified BSD License.
10 #
10 #
11 #The full license is in the file COPYING.txt, distributed with this software.
11 #The full license is in the file COPYING.txt, distributed with this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 #Imports
15 #Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 # Stdlib imports
18 # Stdlib imports
19 from __future__ import print_function
19 from __future__ import print_function
20
20
21 import logging
21 import logging
22 import sys
22 import sys
23 import os
23 import os
24 import glob
24 import glob
25
25
26 # From IPython
26 # From IPython
27 from IPython.core.application import BaseIPythonApplication, base_aliases, base_flags
27 from IPython.core.application import BaseIPythonApplication, base_aliases, base_flags
28 from IPython.config import catch_config_error, Configurable
28 from IPython.config import catch_config_error, Configurable
29 from IPython.utils.traitlets import (
29 from IPython.utils.traitlets import (
30 Unicode, List, Instance, DottedObjectName, Type, CaselessStrEnum,
30 Unicode, List, Instance, DottedObjectName, Type, CaselessStrEnum,
31 )
31 )
32 from IPython.utils.importstring import import_item
32 from IPython.utils.importstring import import_item
33 from IPython.utils.text import dedent
33 from IPython.utils.text import dedent
34
34
35 from .exporters.export import get_export_names, exporter_map
35 from .exporters.export import get_export_names, exporter_map
36 from IPython.nbconvert import exporters, transformers, writers, post_processors
36 from IPython.nbconvert import exporters, transformers, writers, post_processors
37 from .utils.base import NbConvertBase
37 from .utils.base import NbConvertBase
38 from .utils.exceptions import ConversionException
38 from .utils.exceptions import ConversionException
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 #Classes and functions
41 #Classes and functions
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 class DottedOrNone(DottedObjectName):
44 class DottedOrNone(DottedObjectName):
45 """
45 """
46 A string holding a valid dotted object name in Python, such as A.b3._c
46 A string holding a valid dotted object name in Python, such as A.b3._c
47 Also allows for None type."""
47 Also allows for None type."""
48
48
49 default_value = u''
49 default_value = u''
50
50
51 def validate(self, obj, value):
51 def validate(self, obj, value):
52 if value is not None and len(value) > 0:
52 if value is not None and len(value) > 0:
53 return super(DottedOrNone, self).validate(obj, value)
53 return super(DottedOrNone, self).validate(obj, value)
54 else:
54 else:
55 return value
55 return value
56
56
57 nbconvert_aliases = {}
57 nbconvert_aliases = {}
58 nbconvert_aliases.update(base_aliases)
58 nbconvert_aliases.update(base_aliases)
59 nbconvert_aliases.update({
59 nbconvert_aliases.update({
60 'to' : 'NbConvertApp.export_format',
60 'to' : 'NbConvertApp.export_format',
61 'template' : 'Exporter.template_file',
61 'template' : 'Exporter.template_file',
62 'notebooks' : 'NbConvertApp.notebooks',
62 'notebooks' : 'NbConvertApp.notebooks',
63 'writer' : 'NbConvertApp.writer_class',
63 'writer' : 'NbConvertApp.writer_class',
64 'post': 'NbConvertApp.post_processor_class',
64 'post': 'NbConvertApp.post_processor_class',
65 'output': 'NbConvertApp.output_base',
65 'output': 'NbConvertApp.output_base',
66 'local': 'RevealHelpTransformer.url_prefix',
66 'offline-slides': 'RevealHelpTransformer.url_prefix',
67 'notes': 'RevealHelpTransformer.speaker_notes'
67 'slide-notes': 'RevealHelpTransformer.speaker_notes'
68 })
68 })
69
69
70 nbconvert_flags = {}
70 nbconvert_flags = {}
71 nbconvert_flags.update(base_flags)
71 nbconvert_flags.update(base_flags)
72 nbconvert_flags.update({
72 nbconvert_flags.update({
73 'stdout' : (
73 'stdout' : (
74 {'NbConvertApp' : {'writer_class' : "StdoutWriter"}},
74 {'NbConvertApp' : {'writer_class' : "StdoutWriter"}},
75 "Write notebook output to stdout instead of files."
75 "Write notebook output to stdout instead of files."
76 )
76 )
77 })
77 })
78
78
79
79
80 class NbConvertApp(BaseIPythonApplication):
80 class NbConvertApp(BaseIPythonApplication):
81 """Application used to convert to and from notebook file type (*.ipynb)"""
81 """Application used to convert to and from notebook file type (*.ipynb)"""
82
82
83 name = 'ipython-nbconvert'
83 name = 'ipython-nbconvert'
84 aliases = nbconvert_aliases
84 aliases = nbconvert_aliases
85 flags = nbconvert_flags
85 flags = nbconvert_flags
86
86
87 def _log_level_default(self):
87 def _log_level_default(self):
88 return logging.INFO
88 return logging.INFO
89
89
90 def _classes_default(self):
90 def _classes_default(self):
91 classes = [NbConvertBase]
91 classes = [NbConvertBase]
92 for pkg in (exporters, transformers, writers):
92 for pkg in (exporters, transformers, writers):
93 for name in dir(pkg):
93 for name in dir(pkg):
94 cls = getattr(pkg, name)
94 cls = getattr(pkg, name)
95 if isinstance(cls, type) and issubclass(cls, Configurable):
95 if isinstance(cls, type) and issubclass(cls, Configurable):
96 classes.append(cls)
96 classes.append(cls)
97 return classes
97 return classes
98
98
99 description = Unicode(
99 description = Unicode(
100 u"""This application is used to convert notebook files (*.ipynb)
100 u"""This application is used to convert notebook files (*.ipynb)
101 to various other formats.
101 to various other formats.
102
102
103 WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES.""")
103 WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES.""")
104
104
105 output_base = Unicode('', config=True, help='''overwrite base name use for output files.
105 output_base = Unicode('', config=True, help='''overwrite base name use for output files.
106 can only be use when converting one notebook at a time.
106 can only be use when converting one notebook at a time.
107 ''')
107 ''')
108
108
109 examples = Unicode(u"""
109 examples = Unicode(u"""
110 The simplest way to use nbconvert is
110 The simplest way to use nbconvert is
111
111
112 > ipython nbconvert mynotebook.ipynb
112 > ipython nbconvert mynotebook.ipynb
113
113
114 which will convert mynotebook.ipynb to the default format (probably HTML).
114 which will convert mynotebook.ipynb to the default format (probably HTML).
115
115
116 You can specify the export format with `--to`.
116 You can specify the export format with `--to`.
117 Options include {0}
117 Options include {0}
118
118
119 > ipython nbconvert --to latex mynotebook.ipnynb
119 > ipython nbconvert --to latex mynotebook.ipnynb
120
120
121 Both HTML and LaTeX support multiple output templates. LaTeX includes
121 Both HTML and LaTeX support multiple output templates. LaTeX includes
122 'basic', 'book', and 'article'. HTML includes 'basic' and 'full'. You
122 'basic', 'book', and 'article'. HTML includes 'basic' and 'full'. You
123 can specify the flavor of the format used.
123 can specify the flavor of the format used.
124
124
125 > ipython nbconvert --to html --template basic mynotebook.ipynb
125 > ipython nbconvert --to html --template basic mynotebook.ipynb
126
126
127 You can also pipe the output to stdout, rather than a file
127 You can also pipe the output to stdout, rather than a file
128
128
129 > ipython nbconvert mynotebook.ipynb --stdout
129 > ipython nbconvert mynotebook.ipynb --stdout
130
130
131 A post-processor can be used to compile a PDF
131 A post-processor can be used to compile a PDF
132
132
133 > ipython nbconvert mynotebook.ipynb --to latex --post PDF
133 > ipython nbconvert mynotebook.ipynb --to latex --post PDF
134
134
135 You can get (and serve) a Reveal.js-powered slideshow
135 You can get (and serve) a Reveal.js-powered slideshow
136
136
137 > ipython nbconvert myslides.ipynb --to slides --post serve
137 > ipython nbconvert myslides.ipynb --to slides --post serve
138
138
139 Multiple notebooks can be given at the command line in a couple of
139 Multiple notebooks can be given at the command line in a couple of
140 different ways:
140 different ways:
141
141
142 > ipython nbconvert notebook*.ipynb
142 > ipython nbconvert notebook*.ipynb
143 > ipython nbconvert notebook1.ipynb notebook2.ipynb
143 > ipython nbconvert notebook1.ipynb notebook2.ipynb
144
144
145 or you can specify the notebooks list in a config file, containing::
145 or you can specify the notebooks list in a config file, containing::
146
146
147 c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
147 c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
148
148
149 > ipython nbconvert --config mycfg.py
149 > ipython nbconvert --config mycfg.py
150 """.format(get_export_names()))
150 """.format(get_export_names()))
151
151
152 # Writer specific variables
152 # Writer specific variables
153 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
153 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
154 help="""Instance of the writer class used to write the
154 help="""Instance of the writer class used to write the
155 results of the conversion.""")
155 results of the conversion.""")
156 writer_class = DottedObjectName('FilesWriter', config=True,
156 writer_class = DottedObjectName('FilesWriter', config=True,
157 help="""Writer class used to write the
157 help="""Writer class used to write the
158 results of the conversion""")
158 results of the conversion""")
159 writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter',
159 writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter',
160 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter',
160 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter',
161 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
161 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
162 writer_factory = Type()
162 writer_factory = Type()
163
163
164 def _writer_class_changed(self, name, old, new):
164 def _writer_class_changed(self, name, old, new):
165 if new in self.writer_aliases:
165 if new in self.writer_aliases:
166 new = self.writer_aliases[new]
166 new = self.writer_aliases[new]
167 self.writer_factory = import_item(new)
167 self.writer_factory = import_item(new)
168
168
169 # Post-processor specific variables
169 # Post-processor specific variables
170 post_processor = Instance('IPython.nbconvert.post_processors.base.PostProcessorBase',
170 post_processor = Instance('IPython.nbconvert.post_processors.base.PostProcessorBase',
171 help="""Instance of the PostProcessor class used to write the
171 help="""Instance of the PostProcessor class used to write the
172 results of the conversion.""")
172 results of the conversion.""")
173
173
174 post_processor_class = DottedOrNone(config=True,
174 post_processor_class = DottedOrNone(config=True,
175 help="""PostProcessor class used to write the
175 help="""PostProcessor class used to write the
176 results of the conversion""")
176 results of the conversion""")
177 post_processor_aliases = {'PDF': 'IPython.nbconvert.post_processors.pdf.PDFPostProcessor',
177 post_processor_aliases = {'PDF': 'IPython.nbconvert.post_processors.pdf.PDFPostProcessor',
178 'serve': 'IPython.nbconvert.post_processors.serve.ServePostProcessor'}
178 'serve': 'IPython.nbconvert.post_processors.serve.ServePostProcessor'}
179 post_processor_factory = Type()
179 post_processor_factory = Type()
180
180
181 def _post_processor_class_changed(self, name, old, new):
181 def _post_processor_class_changed(self, name, old, new):
182 if new in self.post_processor_aliases:
182 if new in self.post_processor_aliases:
183 new = self.post_processor_aliases[new]
183 new = self.post_processor_aliases[new]
184 if new:
184 if new:
185 self.post_processor_factory = import_item(new)
185 self.post_processor_factory = import_item(new)
186
186
187
187
188 # Other configurable variables
188 # Other configurable variables
189 export_format = CaselessStrEnum(get_export_names(),
189 export_format = CaselessStrEnum(get_export_names(),
190 default_value="html",
190 default_value="html",
191 config=True,
191 config=True,
192 help="""The export format to be used."""
192 help="""The export format to be used."""
193 )
193 )
194
194
195 notebooks = List([], config=True, help="""List of notebooks to convert.
195 notebooks = List([], config=True, help="""List of notebooks to convert.
196 Wildcards are supported.
196 Wildcards are supported.
197 Filenames passed positionally will be added to the list.
197 Filenames passed positionally will be added to the list.
198 """)
198 """)
199
199
200 @catch_config_error
200 @catch_config_error
201 def initialize(self, argv=None):
201 def initialize(self, argv=None):
202 super(NbConvertApp, self).initialize(argv)
202 super(NbConvertApp, self).initialize(argv)
203 self.init_syspath()
203 self.init_syspath()
204 self.init_notebooks()
204 self.init_notebooks()
205 self.init_writer()
205 self.init_writer()
206 self.init_post_processor()
206 self.init_post_processor()
207
207
208
208
209
209
210 def init_syspath(self):
210 def init_syspath(self):
211 """
211 """
212 Add the cwd to the sys.path ($PYTHONPATH)
212 Add the cwd to the sys.path ($PYTHONPATH)
213 """
213 """
214 sys.path.insert(0, os.getcwd())
214 sys.path.insert(0, os.getcwd())
215
215
216
216
217 def init_notebooks(self):
217 def init_notebooks(self):
218 """Construct the list of notebooks.
218 """Construct the list of notebooks.
219 If notebooks are passed on the command-line,
219 If notebooks are passed on the command-line,
220 they override notebooks specified in config files.
220 they override notebooks specified in config files.
221 Glob each notebook to replace notebook patterns with filenames.
221 Glob each notebook to replace notebook patterns with filenames.
222 """
222 """
223
223
224 # Specifying notebooks on the command-line overrides (rather than adds)
224 # Specifying notebooks on the command-line overrides (rather than adds)
225 # the notebook list
225 # the notebook list
226 if self.extra_args:
226 if self.extra_args:
227 patterns = self.extra_args
227 patterns = self.extra_args
228 else:
228 else:
229 patterns = self.notebooks
229 patterns = self.notebooks
230
230
231 # Use glob to replace all the notebook patterns with filenames.
231 # Use glob to replace all the notebook patterns with filenames.
232 filenames = []
232 filenames = []
233 for pattern in patterns:
233 for pattern in patterns:
234
234
235 # Use glob to find matching filenames. Allow the user to convert
235 # Use glob to find matching filenames. Allow the user to convert
236 # notebooks without having to type the extension.
236 # notebooks without having to type the extension.
237 globbed_files = glob.glob(pattern)
237 globbed_files = glob.glob(pattern)
238 globbed_files.extend(glob.glob(pattern + '.ipynb'))
238 globbed_files.extend(glob.glob(pattern + '.ipynb'))
239 if not globbed_files:
239 if not globbed_files:
240 self.log.warn("pattern %r matched no files", pattern)
240 self.log.warn("pattern %r matched no files", pattern)
241
241
242 for filename in globbed_files:
242 for filename in globbed_files:
243 if not filename in filenames:
243 if not filename in filenames:
244 filenames.append(filename)
244 filenames.append(filename)
245 self.notebooks = filenames
245 self.notebooks = filenames
246
246
247 def init_writer(self):
247 def init_writer(self):
248 """
248 """
249 Initialize the writer (which is stateless)
249 Initialize the writer (which is stateless)
250 """
250 """
251 self._writer_class_changed(None, self.writer_class, self.writer_class)
251 self._writer_class_changed(None, self.writer_class, self.writer_class)
252 self.writer = self.writer_factory(parent=self)
252 self.writer = self.writer_factory(parent=self)
253
253
254 def init_post_processor(self):
254 def init_post_processor(self):
255 """
255 """
256 Initialize the post_processor (which is stateless)
256 Initialize the post_processor (which is stateless)
257 """
257 """
258 self._post_processor_class_changed(None, self.post_processor_class,
258 self._post_processor_class_changed(None, self.post_processor_class,
259 self.post_processor_class)
259 self.post_processor_class)
260 if self.post_processor_factory:
260 if self.post_processor_factory:
261 self.post_processor = self.post_processor_factory(parent=self)
261 self.post_processor = self.post_processor_factory(parent=self)
262
262
263 def start(self):
263 def start(self):
264 """
264 """
265 Ran after initialization completed
265 Ran after initialization completed
266 """
266 """
267 super(NbConvertApp, self).start()
267 super(NbConvertApp, self).start()
268 self.convert_notebooks()
268 self.convert_notebooks()
269
269
270 def convert_notebooks(self):
270 def convert_notebooks(self):
271 """
271 """
272 Convert the notebooks in the self.notebook traitlet
272 Convert the notebooks in the self.notebook traitlet
273 """
273 """
274 # Export each notebook
274 # Export each notebook
275 conversion_success = 0
275 conversion_success = 0
276
276
277 if self.output_base != '' and len(self.notebooks) > 1:
277 if self.output_base != '' and len(self.notebooks) > 1:
278 self.log.error(
278 self.log.error(
279 """UsageError: --output flag or `NbConvertApp.output_base` config option
279 """UsageError: --output flag or `NbConvertApp.output_base` config option
280 cannot be used when converting multiple notebooks.
280 cannot be used when converting multiple notebooks.
281 """)
281 """)
282 self.exit(1)
282 self.exit(1)
283
283
284 exporter = exporter_map[self.export_format](config=self.config)
284 exporter = exporter_map[self.export_format](config=self.config)
285
285
286 for notebook_filename in self.notebooks:
286 for notebook_filename in self.notebooks:
287 self.log.info("Converting notebook %s to %s", notebook_filename, self.export_format)
287 self.log.info("Converting notebook %s to %s", notebook_filename, self.export_format)
288
288
289 # Get a unique key for the notebook and set it in the resources object.
289 # Get a unique key for the notebook and set it in the resources object.
290 basename = os.path.basename(notebook_filename)
290 basename = os.path.basename(notebook_filename)
291 notebook_name = basename[:basename.rfind('.')]
291 notebook_name = basename[:basename.rfind('.')]
292 if self.output_base:
292 if self.output_base:
293 notebook_name = self.output_base
293 notebook_name = self.output_base
294 resources = {}
294 resources = {}
295 resources['unique_key'] = notebook_name
295 resources['unique_key'] = notebook_name
296 resources['output_files_dir'] = '%s_files' % notebook_name
296 resources['output_files_dir'] = '%s_files' % notebook_name
297 self.log.info("Support files will be in %s", os.path.join(resources['output_files_dir'], ''))
297 self.log.info("Support files will be in %s", os.path.join(resources['output_files_dir'], ''))
298
298
299 # Try to export
299 # Try to export
300 try:
300 try:
301 output, resources = exporter.from_filename(notebook_filename, resources=resources)
301 output, resources = exporter.from_filename(notebook_filename, resources=resources)
302 except ConversionException as e:
302 except ConversionException as e:
303 self.log.error("Error while converting '%s'", notebook_filename,
303 self.log.error("Error while converting '%s'", notebook_filename,
304 exc_info=True)
304 exc_info=True)
305 self.exit(1)
305 self.exit(1)
306 else:
306 else:
307 write_resultes = self.writer.write(output, resources, notebook_name=notebook_name)
307 write_resultes = self.writer.write(output, resources, notebook_name=notebook_name)
308
308
309 #Post-process if post processor has been defined.
309 #Post-process if post processor has been defined.
310 if hasattr(self, 'post_processor') and self.post_processor:
310 if hasattr(self, 'post_processor') and self.post_processor:
311 self.post_processor(write_resultes)
311 self.post_processor(write_resultes)
312 conversion_success += 1
312 conversion_success += 1
313
313
314 # If nothing was converted successfully, help the user.
314 # If nothing was converted successfully, help the user.
315 if conversion_success == 0:
315 if conversion_success == 0:
316 self.print_help()
316 self.print_help()
317 sys.exit(-1)
317 sys.exit(-1)
318
318
319 #-----------------------------------------------------------------------------
319 #-----------------------------------------------------------------------------
320 # Main entry point
320 # Main entry point
321 #-----------------------------------------------------------------------------
321 #-----------------------------------------------------------------------------
322
322
323 launch_new_instance = NbConvertApp.launch_instance
323 launch_new_instance = NbConvertApp.launch_instance
@@ -1,217 +1,217 b''
1 .. _nbconvert:
1 .. _nbconvert:
2
2
3 Converting notebooks to other formats
3 Converting notebooks to other formats
4 =====================================
4 =====================================
5
5
6 Newly added in the 1.0 release of IPython is the ``nbconvert`` tool, which
6 Newly added in the 1.0 release of IPython is the ``nbconvert`` tool, which
7 allows you to convert an ``.ipynb`` notebook document file into various static
7 allows you to convert an ``.ipynb`` notebook document file into various static
8 formats.
8 formats.
9
9
10 Currently, ``nbconvert`` is provided as a command line tool, run as a script
10 Currently, ``nbconvert`` is provided as a command line tool, run as a script
11 using IPython. A direct export capability from within the
11 using IPython. A direct export capability from within the
12 IPython Notebook web app is planned.
12 IPython Notebook web app is planned.
13
13
14 The command-line syntax to run the ``nbconvert`` script is::
14 The command-line syntax to run the ``nbconvert`` script is::
15
15
16 $ ipython nbconvert --to FORMAT notebook.ipynb
16 $ ipython nbconvert --to FORMAT notebook.ipynb
17
17
18 This will convert the IPython document file ``notebook.ipynb`` into the output
18 This will convert the IPython document file ``notebook.ipynb`` into the output
19 format given by the ``FORMAT`` string.
19 format given by the ``FORMAT`` string.
20
20
21 The default output format is html, for which the ``--to`` argument may be
21 The default output format is html, for which the ``--to`` argument may be
22 omitted::
22 omitted::
23
23
24 $ ipython nbconvert notebook.ipynb
24 $ ipython nbconvert notebook.ipynb
25
25
26 IPython provides a few templates for some output formats, and these can be
26 IPython provides a few templates for some output formats, and these can be
27 specified via an additional ``--template`` argument.
27 specified via an additional ``--template`` argument.
28
28
29 The currently supported export formats are:
29 The currently supported export formats are:
30
30
31 * ``--to html``
31 * ``--to html``
32
32
33 - ``--template full`` (default)
33 - ``--template full`` (default)
34
34
35 A full static HTML render of the notebook.
35 A full static HTML render of the notebook.
36 This looks very similar to the interactive view.
36 This looks very similar to the interactive view.
37
37
38 - ``--template basic``
38 - ``--template basic``
39
39
40 Simplified HTML, useful for embedding in webpages, blogs, etc.
40 Simplified HTML, useful for embedding in webpages, blogs, etc.
41 This excludes HTML headers.
41 This excludes HTML headers.
42
42
43 * ``--to latex``
43 * ``--to latex``
44
44
45 Latex export. This generates ``NOTEBOOK_NAME.tex`` file,
45 Latex export. This generates ``NOTEBOOK_NAME.tex`` file,
46 ready for export. You can automatically run latex on it to generate a PDF
46 ready for export. You can automatically run latex on it to generate a PDF
47 by adding ``--post PDF``.
47 by adding ``--post PDF``.
48
48
49 - ``--template article`` (default)
49 - ``--template article`` (default)
50
50
51 Latex article, derived from Sphinx's howto template.
51 Latex article, derived from Sphinx's howto template.
52
52
53 - ``--template book``
53 - ``--template book``
54
54
55 Latex book, derived from Sphinx's manual template.
55 Latex book, derived from Sphinx's manual template.
56
56
57 - ``--template basic``
57 - ``--template basic``
58
58
59 Very basic latex output - mainly meant as a starting point for custom templates.
59 Very basic latex output - mainly meant as a starting point for custom templates.
60
60
61 * ``--to slides``
61 * ``--to slides``
62
62
63 This generates a Reveal.js HTML slideshow.
63 This generates a Reveal.js HTML slideshow.
64 It must be served by an HTTP server. The easiest way to get this is to add
64 It must be served by an HTTP server. The easiest way to get this is to add
65 ``--post serve`` on the command-line.
65 ``--post serve`` on the command-line.
66 If you want to use the speaker notes plugin, just add
66 If you want to use the speaker notes plugin, just add
67 ``--notes True`` on the command-line.
67 ``--slide-notes True`` on the command-line.
68 For low connectivity environments, you can use a local copy of the reveal.js library,
68 For low connectivity environments, you can use a local copy of the reveal.js library,
69 just add ``--local reveal.js`` on the command-line, and do not forget to move your
69 just add ``--offline-slides reveal.js`` on the command-line, and do not forget to move
70 downloaded ``reveal.js`` library to the same folder where your slides are located.
70 your downloaded ``reveal.js`` library to the same folder where your slides are located.
71
71
72 * ``--to markdown``
72 * ``--to markdown``
73
73
74 Simple markdown output. Markdown cells are unaffected,
74 Simple markdown output. Markdown cells are unaffected,
75 and code cells are placed in triple-backtick (``\`\`\```) blocks.
75 and code cells are placed in triple-backtick (``\`\`\```) blocks.
76
76
77 * ``--to rst``
77 * ``--to rst``
78
78
79 Basic reStructuredText output. Useful as a starting point for embedding notebooks
79 Basic reStructuredText output. Useful as a starting point for embedding notebooks
80 in Sphinx docs.
80 in Sphinx docs.
81
81
82 * ``--to python``
82 * ``--to python``
83
83
84 Convert a notebook to an executable Python script.
84 Convert a notebook to an executable Python script.
85 This is the simplest way to get a Python script out of a notebook.
85 This is the simplest way to get a Python script out of a notebook.
86 If there were any magics in the notebook, this may only be executable from
86 If there were any magics in the notebook, this may only be executable from
87 an IPython session.
87 an IPython session.
88
88
89 .. note::
89 .. note::
90
90
91 nbconvert uses pandoc_ to convert between various markup languages,
91 nbconvert uses pandoc_ to convert between various markup languages,
92 so pandoc is a dependency of most nbconvert transforms,
92 so pandoc is a dependency of most nbconvert transforms,
93 excluding Markdown and Python.
93 excluding Markdown and Python.
94
94
95 .. _pandoc: http://johnmacfarlane.net/pandoc/
95 .. _pandoc: http://johnmacfarlane.net/pandoc/
96
96
97 The output file created by ``nbconvert`` will have the same base name as
97 The output file created by ``nbconvert`` will have the same base name as
98 the notebook and will be placed in the current working directory. Any
98 the notebook and will be placed in the current working directory. Any
99 supporting files (graphics, etc) will be placed in a new directory with the
99 supporting files (graphics, etc) will be placed in a new directory with the
100 same base name as the notebook, suffixed with ``_files``::
100 same base name as the notebook, suffixed with ``_files``::
101
101
102 $ ipython nbconvert notebook.ipynb
102 $ ipython nbconvert notebook.ipynb
103 $ ls
103 $ ls
104 notebook.ipynb notebook.html notebook_files/
104 notebook.ipynb notebook.html notebook_files/
105
105
106 For simple single-file output, such as html, markdown, etc.,
106 For simple single-file output, such as html, markdown, etc.,
107 the output may be sent to standard output with::
107 the output may be sent to standard output with::
108
108
109 $ ipython nbconvert --to markdown notebook.ipynb --stdout
109 $ ipython nbconvert --to markdown notebook.ipynb --stdout
110
110
111 Multiple notebooks can be specified from the command line::
111 Multiple notebooks can be specified from the command line::
112
112
113 $ ipython nbconvert notebook*.ipynb
113 $ ipython nbconvert notebook*.ipynb
114 $ ipython nbconvert notebook1.ipynb notebook2.ipynb
114 $ ipython nbconvert notebook1.ipynb notebook2.ipynb
115
115
116 or via a list in a configuration file, say ``mycfg.py``, containing the text::
116 or via a list in a configuration file, say ``mycfg.py``, containing the text::
117
117
118 c = get_config()
118 c = get_config()
119 c.NbConvertApp.notebooks = ["notebook1.ipynb", "notebook2.ipynb"]
119 c.NbConvertApp.notebooks = ["notebook1.ipynb", "notebook2.ipynb"]
120
120
121 and using the command::
121 and using the command::
122
122
123 $ ipython nbconvert --config mycfg.py
123 $ ipython nbconvert --config mycfg.py
124
124
125
125
126 .. _notebook_format:
126 .. _notebook_format:
127
127
128 Notebook JSON file format
128 Notebook JSON file format
129 -------------------------
129 -------------------------
130
130
131 Notebook documents are JSON files with an ``.ipynb`` extension, formatted
131 Notebook documents are JSON files with an ``.ipynb`` extension, formatted
132 as legibly as possible with minimal extra indentation and cell content broken
132 as legibly as possible with minimal extra indentation and cell content broken
133 across lines to make them reasonably friendly to use in version-control
133 across lines to make them reasonably friendly to use in version-control
134 workflows. You should be very careful if you ever manually edit this JSON
134 workflows. You should be very careful if you ever manually edit this JSON
135 data, as it is extremely easy to corrupt its internal structure and make the
135 data, as it is extremely easy to corrupt its internal structure and make the
136 file impossible to load. In general, you should consider the notebook as a
136 file impossible to load. In general, you should consider the notebook as a
137 file meant only to be edited by the IPython Notebook app itself, not for
137 file meant only to be edited by the IPython Notebook app itself, not for
138 hand-editing.
138 hand-editing.
139
139
140 .. note::
140 .. note::
141
141
142 Binary data such as figures are also saved directly in the JSON file.
142 Binary data such as figures are also saved directly in the JSON file.
143 This provides convenient single-file portability, but means that the
143 This provides convenient single-file portability, but means that the
144 files can be large; a ``diff`` of binary data is also not very
144 files can be large; a ``diff`` of binary data is also not very
145 meaningful. Since the binary blobs are encoded in a single line, they
145 meaningful. Since the binary blobs are encoded in a single line, they
146 affect only one line of the ``diff`` output, but they are typically very
146 affect only one line of the ``diff`` output, but they are typically very
147 long lines. You can use the ``Cell | All Output | Clear`` menu option to
147 long lines. You can use the ``Cell | All Output | Clear`` menu option to
148 remove all output from a notebook prior to committing it to version
148 remove all output from a notebook prior to committing it to version
149 control, if this is a concern.
149 control, if this is a concern.
150
150
151 The notebook server can also generate a pure Python version of your notebook,
151 The notebook server can also generate a pure Python version of your notebook,
152 using the ``File | Download as`` menu option. The resulting ``.py`` file will
152 using the ``File | Download as`` menu option. The resulting ``.py`` file will
153 contain all the code cells from your notebook verbatim, and all Markdown cells
153 contain all the code cells from your notebook verbatim, and all Markdown cells
154 prepended with a comment marker. The separation between code and Markdown
154 prepended with a comment marker. The separation between code and Markdown
155 cells is indicated with special comments and there is a header indicating the
155 cells is indicated with special comments and there is a header indicating the
156 format version. All output is removed when exporting to Python.
156 format version. All output is removed when exporting to Python.
157
157
158 As an example, consider a simple notebook called ``simple.ipynb`` which
158 As an example, consider a simple notebook called ``simple.ipynb`` which
159 contains one Markdown cell, with the content ``The simplest notebook.``, one
159 contains one Markdown cell, with the content ``The simplest notebook.``, one
160 code input cell with the content ``print "Hello, IPython!"``, and the
160 code input cell with the content ``print "Hello, IPython!"``, and the
161 corresponding output.
161 corresponding output.
162
162
163 The contents of the notebook document ``simple.ipynb`` is the following JSON
163 The contents of the notebook document ``simple.ipynb`` is the following JSON
164 container::
164 container::
165
165
166 {
166 {
167 "metadata": {
167 "metadata": {
168 "name": "simple"
168 "name": "simple"
169 },
169 },
170 "nbformat": 3,
170 "nbformat": 3,
171 "nbformat_minor": 0,
171 "nbformat_minor": 0,
172 "worksheets": [
172 "worksheets": [
173 {
173 {
174 "cells": [
174 "cells": [
175 {
175 {
176 "cell_type": "markdown",
176 "cell_type": "markdown",
177 "metadata": {},
177 "metadata": {},
178 "source": "The simplest notebook."
178 "source": "The simplest notebook."
179 },
179 },
180 {
180 {
181 "cell_type": "code",
181 "cell_type": "code",
182 "collapsed": false,
182 "collapsed": false,
183 "input": "print \"Hello, IPython\"",
183 "input": "print \"Hello, IPython\"",
184 "language": "python",
184 "language": "python",
185 "metadata": {},
185 "metadata": {},
186 "outputs": [
186 "outputs": [
187 {
187 {
188 "output_type": "stream",
188 "output_type": "stream",
189 "stream": "stdout",
189 "stream": "stdout",
190 "text": "Hello, IPython\n"
190 "text": "Hello, IPython\n"
191 }
191 }
192 ],
192 ],
193 "prompt_number": 1
193 "prompt_number": 1
194 }
194 }
195 ],
195 ],
196 "metadata": {}
196 "metadata": {}
197 }
197 }
198 ]
198 ]
199 }
199 }
200
200
201
201
202 The corresponding Python script is::
202 The corresponding Python script is::
203
203
204 # -*- coding: utf-8 -*-
204 # -*- coding: utf-8 -*-
205 # <nbformat>3.0</nbformat>
205 # <nbformat>3.0</nbformat>
206
206
207 # <markdowncell>
207 # <markdowncell>
208
208
209 # The simplest notebook.
209 # The simplest notebook.
210
210
211 # <codecell>
211 # <codecell>
212
212
213 print "Hello, IPython"
213 print "Hello, IPython"
214
214
215 Note that indeed the output of the code cell, which is present in the JSON
215 Note that indeed the output of the code cell, which is present in the JSON
216 container, has been removed in the ``.py`` script.
216 container, has been removed in the ``.py`` script.
217
217
General Comments 0
You need to be logged in to leave comments. Login now