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