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