Show More
@@ -1,239 +1,239 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 |
|
99 | |||
100 | or you can specify the notebooks list in a config file, containing:: |
|
100 | or you can specify the notebooks list in a config file, containing:: | |
101 |
|
101 | |||
102 | c.NbConvertApp.notebooks = ["my_notebook.ipynb"] |
|
102 | c.NbConvertApp.notebooks = ["my_notebook.ipynb"] | |
103 |
|
103 | |||
104 | > ipython nbconvert --config mycfg.py |
|
104 | > ipython nbconvert --config mycfg.py | |
105 | """.format(get_export_names())) |
|
105 | """.format(get_export_names())) | |
106 | # Writer specific variables |
|
106 | # Writer specific variables | |
107 | writer = Instance('IPython.nbconvert.writers.base.WriterBase', |
|
107 | writer = Instance('IPython.nbconvert.writers.base.WriterBase', | |
108 | help="""Instance of the writer class used to write the |
|
108 | help="""Instance of the writer class used to write the | |
109 | results of the conversion.""") |
|
109 | results of the conversion.""") | |
110 | writer_class = DottedObjectName('FilesWriter', config=True, |
|
110 | writer_class = DottedObjectName('FilesWriter', config=True, | |
111 | help="""Writer class used to write the |
|
111 | help="""Writer class used to write the | |
112 | results of the conversion""") |
|
112 | results of the conversion""") | |
113 | writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter', |
|
113 | writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter', | |
114 | 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter', |
|
114 | 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter', | |
115 | 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'} |
|
115 | 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'} | |
116 | writer_factory = Type() |
|
116 | writer_factory = Type() | |
117 |
|
117 | |||
118 | def _writer_class_changed(self, name, old, new): |
|
118 | def _writer_class_changed(self, name, old, new): | |
119 | if new in self.writer_aliases: |
|
119 | if new in self.writer_aliases: | |
120 | new = self.writer_aliases[new] |
|
120 | new = self.writer_aliases[new] | |
121 | self.writer_factory = import_item(new) |
|
121 | self.writer_factory = import_item(new) | |
122 |
|
122 | |||
123 |
|
123 | |||
124 | # Other configurable variables |
|
124 | # Other configurable variables | |
125 | export_format = CaselessStrEnum(get_export_names(), |
|
125 | export_format = CaselessStrEnum(get_export_names(), | |
126 | default_value="full_html", |
|
126 | default_value="full_html", | |
127 | config=True, |
|
127 | config=True, | |
128 | help="""The export format to be used.""" |
|
128 | help="""The export format to be used.""" | |
129 | ) |
|
129 | ) | |
130 |
|
130 | |||
131 | notebooks = List([], config=True, help="""List of notebooks to convert. |
|
131 | notebooks = List([], config=True, help="""List of notebooks to convert. | |
132 | Wildcards are supported. |
|
132 | Wildcards are supported. | |
133 | Filenames passed positionally will be added to the list. |
|
133 | Filenames passed positionally will be added to the list. | |
134 | """) |
|
134 | """) | |
135 |
|
135 | |||
136 | @catch_config_error |
|
136 | @catch_config_error | |
137 | def initialize(self, argv=None): |
|
137 | def initialize(self, argv=None): | |
138 | super(NbConvertApp, self).initialize(argv) |
|
138 | super(NbConvertApp, self).initialize(argv) | |
139 | self.init_syspath() |
|
139 | self.init_syspath() | |
140 | self.init_notebooks() |
|
140 | self.init_notebooks() | |
141 | self.init_writer() |
|
141 | self.init_writer() | |
142 |
|
142 | |||
143 |
|
143 | |||
144 | def init_syspath(self): |
|
144 | def init_syspath(self): | |
145 | """ |
|
145 | """ | |
146 | Add the cwd to the sys.path ($PYTHONPATH) |
|
146 | Add the cwd to the sys.path ($PYTHONPATH) | |
147 | """ |
|
147 | """ | |
148 |
sys.path. |
|
148 | sys.path.insert(0, os.getcwd()) | |
149 |
|
149 | |||
150 |
|
150 | |||
151 | def init_notebooks(self): |
|
151 | def init_notebooks(self): | |
152 | """Construct the list of notebooks. |
|
152 | """Construct the list of notebooks. | |
153 | If notebooks are passed on the command-line, |
|
153 | If notebooks are passed on the command-line, | |
154 | they override notebooks specified in config files. |
|
154 | they override notebooks specified in config files. | |
155 | Glob each notebook to replace notebook patterns with filenames. |
|
155 | Glob each notebook to replace notebook patterns with filenames. | |
156 | """ |
|
156 | """ | |
157 |
|
157 | |||
158 | # Specifying notebooks on the command-line overrides (rather than adds) |
|
158 | # Specifying notebooks on the command-line overrides (rather than adds) | |
159 | # the notebook list |
|
159 | # the notebook list | |
160 | if self.extra_args: |
|
160 | if self.extra_args: | |
161 | patterns = self.extra_args |
|
161 | patterns = self.extra_args | |
162 | else: |
|
162 | else: | |
163 | patterns = self.notebooks |
|
163 | patterns = self.notebooks | |
164 |
|
164 | |||
165 | # Use glob to replace all the notebook patterns with filenames. |
|
165 | # Use glob to replace all the notebook patterns with filenames. | |
166 | filenames = [] |
|
166 | filenames = [] | |
167 | for pattern in patterns: |
|
167 | for pattern in patterns: | |
168 | for filename in glob.glob(pattern): |
|
168 | for filename in glob.glob(pattern): | |
169 | if not filename in filenames: |
|
169 | if not filename in filenames: | |
170 | filenames.append(filename) |
|
170 | filenames.append(filename) | |
171 | self.notebooks = filenames |
|
171 | self.notebooks = filenames | |
172 |
|
172 | |||
173 | def init_writer(self): |
|
173 | def init_writer(self): | |
174 | """ |
|
174 | """ | |
175 | Initialize the writer (which is stateless) |
|
175 | Initialize the writer (which is stateless) | |
176 | """ |
|
176 | """ | |
177 | self._writer_class_changed(None, self.writer_class, self.writer_class) |
|
177 | self._writer_class_changed(None, self.writer_class, self.writer_class) | |
178 | self.writer = self.writer_factory(parent=self) |
|
178 | self.writer = self.writer_factory(parent=self) | |
179 |
|
179 | |||
180 | def start(self): |
|
180 | def start(self): | |
181 | """ |
|
181 | """ | |
182 | Ran after initialization completed |
|
182 | Ran after initialization completed | |
183 | """ |
|
183 | """ | |
184 | super(NbConvertApp, self).start() |
|
184 | super(NbConvertApp, self).start() | |
185 | self.convert_notebooks() |
|
185 | self.convert_notebooks() | |
186 |
|
186 | |||
187 | def convert_notebooks(self): |
|
187 | def convert_notebooks(self): | |
188 | """ |
|
188 | """ | |
189 | Convert the notebooks in the self.notebook traitlet |
|
189 | Convert the notebooks in the self.notebook traitlet | |
190 | """ |
|
190 | """ | |
191 | # Export each notebook |
|
191 | # Export each notebook | |
192 | conversion_success = 0 |
|
192 | conversion_success = 0 | |
193 | for notebook_filename in self.notebooks: |
|
193 | for notebook_filename in self.notebooks: | |
194 |
|
194 | |||
195 | # Get a unique key for the notebook and set it in the resources object. |
|
195 | # Get a unique key for the notebook and set it in the resources object. | |
196 | basename = os.path.basename(notebook_filename) |
|
196 | basename = os.path.basename(notebook_filename) | |
197 | notebook_name = basename[:basename.rfind('.')] |
|
197 | notebook_name = basename[:basename.rfind('.')] | |
198 | resources = {} |
|
198 | resources = {} | |
199 | resources['unique_key'] = notebook_name |
|
199 | resources['unique_key'] = notebook_name | |
200 | resources['output_files_dir'] = '%s_files' % notebook_name |
|
200 | resources['output_files_dir'] = '%s_files' % notebook_name | |
201 |
|
201 | |||
202 | # Try to export |
|
202 | # Try to export | |
203 | try: |
|
203 | try: | |
204 | output, resources = export_by_name(self.export_format, |
|
204 | output, resources = export_by_name(self.export_format, | |
205 | notebook_filename, |
|
205 | notebook_filename, | |
206 | resources=resources, |
|
206 | resources=resources, | |
207 | config=self.config) |
|
207 | config=self.config) | |
208 | except ExporterNameError as e: |
|
208 | except ExporterNameError as e: | |
209 | print("Error: '%s' exporter not found." % self.export_format, |
|
209 | print("Error: '%s' exporter not found." % self.export_format, | |
210 | file=sys.stderr) |
|
210 | file=sys.stderr) | |
211 | print("Known exporters are:", |
|
211 | print("Known exporters are:", | |
212 | "\n\t" + "\n\t".join(get_export_names()), |
|
212 | "\n\t" + "\n\t".join(get_export_names()), | |
213 | file=sys.stderr) |
|
213 | file=sys.stderr) | |
214 | sys.exit(-1) |
|
214 | sys.exit(-1) | |
215 | # except Exception as e: |
|
215 | # except Exception as e: | |
216 | # print("Error: could not export '%s'" % notebook_filename, file=sys.stderr) |
|
216 | # print("Error: could not export '%s'" % notebook_filename, file=sys.stderr) | |
217 | # print(e, file=sys.stderr) |
|
217 | # print(e, file=sys.stderr) | |
218 | else: |
|
218 | else: | |
219 | self.writer.write(output, resources, notebook_name=notebook_name) |
|
219 | self.writer.write(output, resources, notebook_name=notebook_name) | |
220 | conversion_success += 1 |
|
220 | conversion_success += 1 | |
221 |
|
221 | |||
222 | # If nothing was converted successfully, help the user. |
|
222 | # If nothing was converted successfully, help the user. | |
223 | if conversion_success == 0: |
|
223 | if conversion_success == 0: | |
224 |
|
224 | |||
225 | # No notebooks were specified, show help. |
|
225 | # No notebooks were specified, show help. | |
226 | if len(self.notebooks) == 0: |
|
226 | if len(self.notebooks) == 0: | |
227 | self.print_help() |
|
227 | self.print_help() | |
228 |
|
228 | |||
229 | # Notebooks were specified, but not converted successfully. Show how |
|
229 | # Notebooks were specified, but not converted successfully. Show how | |
230 | # to access help. |
|
230 | # to access help. | |
231 | else: |
|
231 | else: | |
232 | print('For help, use "ipython nbconvert --help"') |
|
232 | print('For help, use "ipython nbconvert --help"') | |
233 |
|
233 | |||
234 |
|
234 | |||
235 | #----------------------------------------------------------------------------- |
|
235 | #----------------------------------------------------------------------------- | |
236 | # Main entry point |
|
236 | # Main entry point | |
237 | #----------------------------------------------------------------------------- |
|
237 | #----------------------------------------------------------------------------- | |
238 |
|
238 | |||
239 | launch_new_instance = NbConvertApp.launch_instance |
|
239 | launch_new_instance = NbConvertApp.launch_instance |
General Comments 0
You need to be logged in to leave comments.
Login now