##// END OF EJS Templates
Updated help string
Jonathan Frederic -
Show More
@@ -1,243 +1,249 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 import sys
20 import sys
21 import os
21 import os
22 import glob
22 import glob
23
23
24 # From IPython
24 # From IPython
25 from IPython.core.application import BaseIPythonApplication, base_aliases, base_flags
25 from IPython.core.application import BaseIPythonApplication, base_aliases, base_flags
26 from IPython.config import catch_config_error, Configurable
26 from IPython.config import catch_config_error, Configurable
27 from IPython.utils.traitlets import (
27 from IPython.utils.traitlets import (
28 Unicode, List, Instance, DottedObjectName, Type, CaselessStrEnum,
28 Unicode, List, Instance, DottedObjectName, Type, CaselessStrEnum,
29 )
29 )
30 from IPython.utils.importstring import import_item
30 from IPython.utils.importstring import import_item
31
31
32 from .exporters.export import export_by_name, get_export_names, ExporterNameError
32 from .exporters.export import export_by_name, get_export_names, ExporterNameError
33 from IPython.nbconvert import exporters, transformers, writers
33 from IPython.nbconvert import exporters, transformers, writers
34 from .utils.base import NbConvertBase
34 from .utils.base import NbConvertBase
35 from .utils.exceptions import ConversionException
35 from .utils.exceptions import ConversionException
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 #Classes and functions
38 #Classes and functions
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41 nbconvert_aliases = {}
41 nbconvert_aliases = {}
42 nbconvert_aliases.update(base_aliases)
42 nbconvert_aliases.update(base_aliases)
43 nbconvert_aliases.update({
43 nbconvert_aliases.update({
44 'to' : 'NbConvertApp.export_format',
44 'to' : 'NbConvertApp.export_format',
45 'flavor' : 'Exporter.flavor',
45 'flavor' : 'Exporter.flavor',
46 'template' : 'Exporter.template_file',
46 'template' : 'Exporter.template_file',
47 'notebooks' : 'NbConvertApp.notebooks',
47 'notebooks' : 'NbConvertApp.notebooks',
48 'writer' : 'NbConvertApp.writer_class',
48 'writer' : 'NbConvertApp.writer_class',
49 })
49 })
50
50
51 nbconvert_flags = {}
51 nbconvert_flags = {}
52 nbconvert_flags.update(base_flags)
52 nbconvert_flags.update(base_flags)
53 nbconvert_flags.update({
53 nbconvert_flags.update({
54 'stdout' : (
54 'stdout' : (
55 {'NbConvertApp' : {'writer_class' : "StdoutWriter"}},
55 {'NbConvertApp' : {'writer_class' : "StdoutWriter"}},
56 "Write notebook output to stdout instead of files."
56 "Write notebook output to stdout instead of files."
57 )
57 )
58 })
58 })
59
59
60
60
61 class NbConvertApp(BaseIPythonApplication):
61 class NbConvertApp(BaseIPythonApplication):
62 """Application used to convert to and from notebook file type (*.ipynb)"""
62 """Application used to convert to and from notebook file type (*.ipynb)"""
63
63
64 name = 'ipython-nbconvert'
64 name = 'ipython-nbconvert'
65 aliases = nbconvert_aliases
65 aliases = nbconvert_aliases
66 flags = nbconvert_flags
66 flags = nbconvert_flags
67
67
68 def _classes_default(self):
68 def _classes_default(self):
69 classes = [NbConvertBase]
69 classes = [NbConvertBase]
70 for pkg in (exporters, transformers, writers):
70 for pkg in (exporters, transformers, writers):
71 for name in dir(pkg):
71 for name in dir(pkg):
72 cls = getattr(pkg, name)
72 cls = getattr(pkg, name)
73 if isinstance(cls, type) and issubclass(cls, Configurable):
73 if isinstance(cls, type) and issubclass(cls, Configurable):
74 classes.append(cls)
74 classes.append(cls)
75 return classes
75 return classes
76
76
77 description = Unicode(
77 description = Unicode(
78 u"""This application is used to convert notebook files (*.ipynb)
78 u"""This application is used to convert notebook files (*.ipynb)
79 to various other formats.""")
79 to various other formats.""")
80
80
81 examples = Unicode(u"""
81 examples = Unicode(u"""
82 The simplest way to use nbconvert is
82 The simplest way to use nbconvert is
83
83
84 > ipython nbconvert mynotebook.ipynb
84 > ipython nbconvert mynotebook.ipynb
85
85
86 which will convert mynotebook.ipynb to the default format (probably HTML).
86 which will convert mynotebook.ipynb to the default format (probably HTML).
87
87
88 You can specify the export format with `--format`.
88 You can specify the export format with `--to`.
89 Options include {0}
89 Options include {0}
90
90
91 > ipython nbconvert --format latex mynotebook.ipnynb
91 > ipython nbconvert --to latex mynotebook.ipnynb
92
93 Both HTML and LaTeX support multiple flavors of output. LaTeX includes
94 'basic', 'book', and 'article'. HTML includes 'basic', 'full', and
95 'reveal'. You can specify the flavor of the format used.
96
97 > ipython nbconvert --to html --flavor reveal mynotebook.ipnynb
92
98
93 You can also pipe the output to stdout, rather than a file
99 You can also pipe the output to stdout, rather than a file
94
100
95 > ipython nbconvert mynotebook.ipynb --stdout
101 > ipython nbconvert mynotebook.ipynb --stdout
96
102
97 Multiple notebooks can be given at the command line in a couple of
103 Multiple notebooks can be given at the command line in a couple of
98 different ways:
104 different ways:
99
105
100 > ipython nbconvert notebook*.ipynb
106 > ipython nbconvert notebook*.ipynb
101 > ipython nbconvert notebook1.ipynb notebook2.ipynb
107 > ipython nbconvert notebook1.ipynb notebook2.ipynb
102
108
103 or you can specify the notebooks list in a config file, containing::
109 or you can specify the notebooks list in a config file, containing::
104
110
105 c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
111 c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
106
112
107 > ipython nbconvert --config mycfg.py
113 > ipython nbconvert --config mycfg.py
108 """.format(get_export_names()))
114 """.format(get_export_names()))
109 # Writer specific variables
115 # Writer specific variables
110 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
116 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
111 help="""Instance of the writer class used to write the
117 help="""Instance of the writer class used to write the
112 results of the conversion.""")
118 results of the conversion.""")
113 writer_class = DottedObjectName('FilesWriter', config=True,
119 writer_class = DottedObjectName('FilesWriter', config=True,
114 help="""Writer class used to write the
120 help="""Writer class used to write the
115 results of the conversion""")
121 results of the conversion""")
116 writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter',
122 writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter',
117 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter',
123 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter',
118 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
124 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
119 writer_factory = Type()
125 writer_factory = Type()
120
126
121 def _writer_class_changed(self, name, old, new):
127 def _writer_class_changed(self, name, old, new):
122 if new in self.writer_aliases:
128 if new in self.writer_aliases:
123 new = self.writer_aliases[new]
129 new = self.writer_aliases[new]
124 self.writer_factory = import_item(new)
130 self.writer_factory = import_item(new)
125
131
126
132
127 # Other configurable variables
133 # Other configurable variables
128 export_format = CaselessStrEnum(get_export_names(),
134 export_format = CaselessStrEnum(get_export_names(),
129 default_value="html",
135 default_value="html",
130 config=True,
136 config=True,
131 help="""The export format to be used."""
137 help="""The export format to be used."""
132 )
138 )
133
139
134 notebooks = List([], config=True, help="""List of notebooks to convert.
140 notebooks = List([], config=True, help="""List of notebooks to convert.
135 Wildcards are supported.
141 Wildcards are supported.
136 Filenames passed positionally will be added to the list.
142 Filenames passed positionally will be added to the list.
137 """)
143 """)
138
144
139 @catch_config_error
145 @catch_config_error
140 def initialize(self, argv=None):
146 def initialize(self, argv=None):
141 super(NbConvertApp, self).initialize(argv)
147 super(NbConvertApp, self).initialize(argv)
142 self.init_syspath()
148 self.init_syspath()
143 self.init_notebooks()
149 self.init_notebooks()
144 self.init_writer()
150 self.init_writer()
145
151
146
152
147 def init_syspath(self):
153 def init_syspath(self):
148 """
154 """
149 Add the cwd to the sys.path ($PYTHONPATH)
155 Add the cwd to the sys.path ($PYTHONPATH)
150 """
156 """
151 sys.path.insert(0, os.getcwd())
157 sys.path.insert(0, os.getcwd())
152
158
153
159
154 def init_notebooks(self):
160 def init_notebooks(self):
155 """Construct the list of notebooks.
161 """Construct the list of notebooks.
156 If notebooks are passed on the command-line,
162 If notebooks are passed on the command-line,
157 they override notebooks specified in config files.
163 they override notebooks specified in config files.
158 Glob each notebook to replace notebook patterns with filenames.
164 Glob each notebook to replace notebook patterns with filenames.
159 """
165 """
160
166
161 # Specifying notebooks on the command-line overrides (rather than adds)
167 # Specifying notebooks on the command-line overrides (rather than adds)
162 # the notebook list
168 # the notebook list
163 if self.extra_args:
169 if self.extra_args:
164 patterns = self.extra_args
170 patterns = self.extra_args
165 else:
171 else:
166 patterns = self.notebooks
172 patterns = self.notebooks
167
173
168 # Use glob to replace all the notebook patterns with filenames.
174 # Use glob to replace all the notebook patterns with filenames.
169 filenames = []
175 filenames = []
170 for pattern in patterns:
176 for pattern in patterns:
171
177
172 # Use glob to find matching filenames. Allow the user to convert
178 # Use glob to find matching filenames. Allow the user to convert
173 # notebooks without having to type the extension.
179 # notebooks without having to type the extension.
174 globbed_files = glob.glob(pattern)
180 globbed_files = glob.glob(pattern)
175 globbed_files.extend(glob.glob(pattern + '.ipynb'))
181 globbed_files.extend(glob.glob(pattern + '.ipynb'))
176
182
177 for filename in globbed_files:
183 for filename in globbed_files:
178 if not filename in filenames:
184 if not filename in filenames:
179 filenames.append(filename)
185 filenames.append(filename)
180 self.notebooks = filenames
186 self.notebooks = filenames
181
187
182 def init_writer(self):
188 def init_writer(self):
183 """
189 """
184 Initialize the writer (which is stateless)
190 Initialize the writer (which is stateless)
185 """
191 """
186 self._writer_class_changed(None, self.writer_class, self.writer_class)
192 self._writer_class_changed(None, self.writer_class, self.writer_class)
187 self.writer = self.writer_factory(parent=self)
193 self.writer = self.writer_factory(parent=self)
188
194
189 def start(self):
195 def start(self):
190 """
196 """
191 Ran after initialization completed
197 Ran after initialization completed
192 """
198 """
193 super(NbConvertApp, self).start()
199 super(NbConvertApp, self).start()
194 self.convert_notebooks()
200 self.convert_notebooks()
195
201
196 def convert_notebooks(self):
202 def convert_notebooks(self):
197 """
203 """
198 Convert the notebooks in the self.notebook traitlet
204 Convert the notebooks in the self.notebook traitlet
199 """
205 """
200 # Export each notebook
206 # Export each notebook
201 conversion_success = 0
207 conversion_success = 0
202 for notebook_filename in self.notebooks:
208 for notebook_filename in self.notebooks:
203
209
204 # Get a unique key for the notebook and set it in the resources object.
210 # Get a unique key for the notebook and set it in the resources object.
205 basename = os.path.basename(notebook_filename)
211 basename = os.path.basename(notebook_filename)
206 notebook_name = basename[:basename.rfind('.')]
212 notebook_name = basename[:basename.rfind('.')]
207 resources = {}
213 resources = {}
208 resources['unique_key'] = notebook_name
214 resources['unique_key'] = notebook_name
209 resources['output_files_dir'] = '%s_files' % notebook_name
215 resources['output_files_dir'] = '%s_files' % notebook_name
210
216
211 # Try to export
217 # Try to export
212 try:
218 try:
213 output, resources = export_by_name(self.export_format,
219 output, resources = export_by_name(self.export_format,
214 notebook_filename,
220 notebook_filename,
215 resources=resources,
221 resources=resources,
216 config=self.config)
222 config=self.config)
217 except ExporterNameError as e:
223 except ExporterNameError as e:
218 print("Error while converting '%s': '%s' exporter not found."
224 print("Error while converting '%s': '%s' exporter not found."
219 %(notebook_filename, self.export_format),
225 %(notebook_filename, self.export_format),
220 file=sys.stderr)
226 file=sys.stderr)
221 print("Known exporters are:",
227 print("Known exporters are:",
222 "\n\t" + "\n\t".join(get_export_names()),
228 "\n\t" + "\n\t".join(get_export_names()),
223 file=sys.stderr)
229 file=sys.stderr)
224 self.exit(1)
230 self.exit(1)
225 except ConversionException as e:
231 except ConversionException as e:
226 print("Error while converting '%s': %s" %(notebook_filename, e),
232 print("Error while converting '%s': %s" %(notebook_filename, e),
227 file=sys.stderr)
233 file=sys.stderr)
228 self.exit(1)
234 self.exit(1)
229 else:
235 else:
230 self.writer.write(output, resources, notebook_name=notebook_name)
236 self.writer.write(output, resources, notebook_name=notebook_name)
231 conversion_success += 1
237 conversion_success += 1
232
238
233 # If nothing was converted successfully, help the user.
239 # If nothing was converted successfully, help the user.
234 if conversion_success == 0:
240 if conversion_success == 0:
235 self.print_help()
241 self.print_help()
236 sys.exit(-1)
242 sys.exit(-1)
237
243
238
244
239 #-----------------------------------------------------------------------------
245 #-----------------------------------------------------------------------------
240 # Main entry point
246 # Main entry point
241 #-----------------------------------------------------------------------------
247 #-----------------------------------------------------------------------------
242
248
243 launch_new_instance = NbConvertApp.launch_instance
249 launch_new_instance = NbConvertApp.launch_instance
General Comments 0
You need to be logged in to leave comments. Login now