##// END OF EJS Templates
Removed non-existant PDFWriter alias
Jonathan Frederic -
Show More
@@ -1,302 +1,301
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, post_processors
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 class DottedOrNone(DottedObjectName):
42 42 """
43 43 A string holding a valid dotted object name in Python, such as A.b3._c
44 44 Also allows for None type."""
45 45
46 46 default_value = u''
47 47
48 48 def validate(self, obj, value):
49 49 if value is not None and len(value) > 0:
50 50 return super(DottedOrNone, self).validate(obj, value)
51 51 else:
52 52 return value
53 53
54 54 nbconvert_aliases = {}
55 55 nbconvert_aliases.update(base_aliases)
56 56 nbconvert_aliases.update({
57 57 'to' : 'NbConvertApp.export_format',
58 58 'template' : 'Exporter.template_file',
59 59 'notebooks' : 'NbConvertApp.notebooks',
60 60 'writer' : 'NbConvertApp.writer_class',
61 61 'post': 'NbConvertApp.post_processor_class'
62 62 })
63 63
64 64 nbconvert_flags = {}
65 65 nbconvert_flags.update(base_flags)
66 66 nbconvert_flags.update({
67 67 'stdout' : (
68 68 {'NbConvertApp' : {'writer_class' : "StdoutWriter"}},
69 69 "Write notebook output to stdout instead of files."
70 70 )
71 71 })
72 72
73 73
74 74 class NbConvertApp(BaseIPythonApplication):
75 75 """Application used to convert to and from notebook file type (*.ipynb)"""
76 76
77 77 name = 'ipython-nbconvert'
78 78 aliases = nbconvert_aliases
79 79 flags = nbconvert_flags
80 80
81 81 def _classes_default(self):
82 82 classes = [NbConvertBase]
83 83 for pkg in (exporters, transformers, writers):
84 84 for name in dir(pkg):
85 85 cls = getattr(pkg, name)
86 86 if isinstance(cls, type) and issubclass(cls, Configurable):
87 87 classes.append(cls)
88 88 return classes
89 89
90 90 description = Unicode(
91 91 u"""This application is used to convert notebook files (*.ipynb)
92 92 to various other formats.
93 93
94 94 WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES.""")
95 95
96 96 examples = Unicode(u"""
97 97 The simplest way to use nbconvert is
98 98
99 99 > ipython nbconvert mynotebook.ipynb
100 100
101 101 which will convert mynotebook.ipynb to the default format (probably HTML).
102 102
103 103 You can specify the export format with `--to`.
104 104 Options include {0}
105 105
106 106 > ipython nbconvert --to latex mynotebook.ipnynb
107 107
108 108 Both HTML and LaTeX support multiple output templates. LaTeX includes
109 109 'basic', 'book', and 'article'. HTML includes 'basic' and 'full'. You
110 110 can specify the flavor of the format used.
111 111
112 112 > ipython nbconvert --to html --template basic mynotebook.ipynb
113 113
114 114 You can also pipe the output to stdout, rather than a file
115 115
116 116 > ipython nbconvert mynotebook.ipynb --stdout
117 117
118 118 A post-processor can be used to compile a PDF
119 119
120 120 > ipython nbconvert mynotebook.ipynb --to latex --post PDF
121 121
122 122 Multiple notebooks can be given at the command line in a couple of
123 123 different ways:
124 124
125 125 > ipython nbconvert notebook*.ipynb
126 126 > ipython nbconvert notebook1.ipynb notebook2.ipynb
127 127
128 128 or you can specify the notebooks list in a config file, containing::
129 129
130 130 c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
131 131
132 132 > ipython nbconvert --config mycfg.py
133 133 """.format(get_export_names()))
134 134
135 135 # Writer specific variables
136 136 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
137 137 help="""Instance of the writer class used to write the
138 138 results of the conversion.""")
139 139 writer_class = DottedObjectName('FilesWriter', config=True,
140 140 help="""Writer class used to write the
141 141 results of the conversion""")
142 142 writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter',
143 'PDFWriter': 'IPython.nbconvert.writers.pdf.PDFWriter',
144 143 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter',
145 144 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
146 145 writer_factory = Type()
147 146
148 147 def _writer_class_changed(self, name, old, new):
149 148 if new in self.writer_aliases:
150 149 new = self.writer_aliases[new]
151 150 self.writer_factory = import_item(new)
152 151
153 152 # Post-processor specific variables
154 153 post_processor = Instance('IPython.nbconvert.post_processors.base.PostProcessorBase',
155 154 help="""Instance of the PostProcessor class used to write the
156 155 results of the conversion.""")
157 156
158 157 post_processor_class = DottedOrNone(config=True,
159 158 help="""PostProcessor class used to write the
160 159 results of the conversion""")
161 160 post_processor_aliases = {'PDF': 'IPython.nbconvert.post_processors.pdf.PDFPostProcessor'}
162 161 post_processor_factory = Type()
163 162
164 163 def _post_processor_class_changed(self, name, old, new):
165 164 if new in self.post_processor_aliases:
166 165 new = self.post_processor_aliases[new]
167 166 if new:
168 167 self.post_processor_factory = import_item(new)
169 168
170 169
171 170 # Other configurable variables
172 171 export_format = CaselessStrEnum(get_export_names(),
173 172 default_value="html",
174 173 config=True,
175 174 help="""The export format to be used."""
176 175 )
177 176
178 177 notebooks = List([], config=True, help="""List of notebooks to convert.
179 178 Wildcards are supported.
180 179 Filenames passed positionally will be added to the list.
181 180 """)
182 181
183 182 @catch_config_error
184 183 def initialize(self, argv=None):
185 184 super(NbConvertApp, self).initialize(argv)
186 185 self.init_syspath()
187 186 self.init_notebooks()
188 187 self.init_writer()
189 188 self.init_post_processor()
190 189
191 190
192 191
193 192 def init_syspath(self):
194 193 """
195 194 Add the cwd to the sys.path ($PYTHONPATH)
196 195 """
197 196 sys.path.insert(0, os.getcwd())
198 197
199 198
200 199 def init_notebooks(self):
201 200 """Construct the list of notebooks.
202 201 If notebooks are passed on the command-line,
203 202 they override notebooks specified in config files.
204 203 Glob each notebook to replace notebook patterns with filenames.
205 204 """
206 205
207 206 # Specifying notebooks on the command-line overrides (rather than adds)
208 207 # the notebook list
209 208 if self.extra_args:
210 209 patterns = self.extra_args
211 210 else:
212 211 patterns = self.notebooks
213 212
214 213 # Use glob to replace all the notebook patterns with filenames.
215 214 filenames = []
216 215 for pattern in patterns:
217 216
218 217 # Use glob to find matching filenames. Allow the user to convert
219 218 # notebooks without having to type the extension.
220 219 globbed_files = glob.glob(pattern)
221 220 globbed_files.extend(glob.glob(pattern + '.ipynb'))
222 221
223 222 for filename in globbed_files:
224 223 if not filename in filenames:
225 224 filenames.append(filename)
226 225 self.notebooks = filenames
227 226
228 227 def init_writer(self):
229 228 """
230 229 Initialize the writer (which is stateless)
231 230 """
232 231 self._writer_class_changed(None, self.writer_class, self.writer_class)
233 232 self.writer = self.writer_factory(parent=self)
234 233
235 234 def init_post_processor(self):
236 235 """
237 236 Initialize the post_processor (which is stateless)
238 237 """
239 238 self._post_processor_class_changed(None, self.post_processor_class,
240 239 self.post_processor_class)
241 240 if self.post_processor_factory:
242 241 self.post_processor = self.post_processor_factory(parent=self)
243 242
244 243 def start(self):
245 244 """
246 245 Ran after initialization completed
247 246 """
248 247 super(NbConvertApp, self).start()
249 248 self.convert_notebooks()
250 249
251 250 def convert_notebooks(self):
252 251 """
253 252 Convert the notebooks in the self.notebook traitlet
254 253 """
255 254 # Export each notebook
256 255 conversion_success = 0
257 256 for notebook_filename in self.notebooks:
258 257
259 258 # Get a unique key for the notebook and set it in the resources object.
260 259 basename = os.path.basename(notebook_filename)
261 260 notebook_name = basename[:basename.rfind('.')]
262 261 resources = {}
263 262 resources['unique_key'] = notebook_name
264 263 resources['output_files_dir'] = '%s_files' % notebook_name
265 264
266 265 # Try to export
267 266 try:
268 267 output, resources = export_by_name(self.export_format,
269 268 notebook_filename,
270 269 resources=resources,
271 270 config=self.config)
272 271 except ExporterNameError as e:
273 272 print("Error while converting '%s': '%s' exporter not found."
274 273 %(notebook_filename, self.export_format),
275 274 file=sys.stderr)
276 275 print("Known exporters are:",
277 276 "\n\t" + "\n\t".join(get_export_names()),
278 277 file=sys.stderr)
279 278 self.exit(1)
280 279 except ConversionException as e:
281 280 print("Error while converting '%s': %s" %(notebook_filename, e),
282 281 file=sys.stderr)
283 282 self.exit(1)
284 283 else:
285 284 write_resultes = self.writer.write(output, resources, notebook_name=notebook_name)
286 285
287 286 #Post-process if post processor has been defined.
288 287 if hasattr(self, 'post_processor') and self.post_processor:
289 288 self.post_processor(write_resultes)
290 289 conversion_success += 1
291 290
292 291 # If nothing was converted successfully, help the user.
293 292 if conversion_success == 0:
294 293 self.print_help()
295 294 sys.exit(-1)
296 295
297 296
298 297 #-----------------------------------------------------------------------------
299 298 # Main entry point
300 299 #-----------------------------------------------------------------------------
301 300
302 301 launch_new_instance = NbConvertApp.launch_instance
General Comments 0
You need to be logged in to leave comments. Login now