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