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