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