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