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