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