##// END OF EJS Templates
cleanup flags / aliases for NbConvertApp...
MinRK -
Show More
@@ -1,197 +1,199 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 Commandline interface for the NBConvert conversion utility. Read the
4 Command-line interface for the NbConvert conversion utility.
5 readme.rst for usage information
6 """
5 """
7 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
8 #Copyright (c) 2013, the IPython Development Team.
7 #Copyright (c) 2013, the IPython Development Team.
9 #
8 #
10 #Distributed under the terms of the Modified BSD License.
9 #Distributed under the terms of the Modified BSD License.
11 #
10 #
12 #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.
13 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
14
13
15 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
16 #Imports
15 #Imports
17 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
18
17
19 #Stdlib imports
18 #Stdlib imports
20 from __future__ import print_function
19 from __future__ import print_function
21 import sys
20 import sys
22 import os
21 import os
23 import glob
22 import glob
24
23
25 #From IPython
24 #From IPython
26 from IPython.core.application import BaseIPythonApplication
25 from IPython.core.application import BaseIPythonApplication, base_aliases, base_flags
27 from IPython.config.application import catch_config_error
26 from IPython.config.application import catch_config_error
28 from IPython.utils.traitlets import Unicode, List, Instance, DottedObjectName, Type
27 from IPython.utils.traitlets import Unicode, List, Instance, DottedObjectName, Type
29 from IPython.utils.importstring import import_item
28 from IPython.utils.importstring import import_item
30
29
31 from .exporters.export import export_by_name, get_export_names, ExporterNameError
30 from .exporters.export import export_by_name, get_export_names, ExporterNameError
32 from .exporters.exporter import Exporter
31 from .exporters.exporter import Exporter
33 from .writers.base import WriterBase
32 from .writers.base import WriterBase
34 from .utils.base import NbConvertBase
33 from .utils.base import NbConvertBase
35
34
36 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
37 #Classes and functions
36 #Classes and functions
38 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
39
38
39 nbconvert_aliases = {}
40 nbconvert_aliases.update(base_aliases)
41 nbconvert_aliases.update({
42 'format' : 'NbConvertApp.export_format',
43 'notebooks' : 'NbConvertApp.notebooks',
44 'writer' : 'NbConvertApp.writer_class',
45 })
46
47 nbconvert_flags = {}
48 nbconvert_flags.update(base_flags)
49 nbconvert_flags.update({
50 'stdout' : (
51 {'NbConvertApp' : {'writer_class' : "StdoutWriter"}},
52 "Write notebook output to stdout instead of files."
53 )
54 })
55
56
40 class NbConvertApp(BaseIPythonApplication):
57 class NbConvertApp(BaseIPythonApplication):
41 """Application used to convert to and from notebook file type (*.ipynb)"""
58 """Application used to convert to and from notebook file type (*.ipynb)"""
42
59
43 name = 'ipython-nbconvert'
60 name = 'ipython-nbconvert'
61 aliases = nbconvert_aliases
62 flags = nbconvert_flags
63
64 def _classes_default(self):
65 return [
66 Exporter,
67 WriterBase,
68 NbConvertBase,
69 ]
44
70
45 description = Unicode(
71 description = Unicode(
46 u"""This application is used to convert notebook files (*.ipynb).
72 u"""This application is used to convert notebook files (*.ipynb).
47 An ipython config file can be used to batch convert notebooks in the
73 An ipython config file can be used to batch convert notebooks in the
48 current directory.""")
74 current directory.""")
49
75
50 examples = Unicode(u"""
76 examples = Unicode(u"""
51 Running `ipython nbconvert` will read the directory config file and then
52 apply it to one or more notebooks.
53
54 Multiple notebooks can be given at the command line in a couple of
77 Multiple notebooks can be given at the command line in a couple of
55 different ways:
78 different ways:
56
79
57 > ipython nbconvert notebook*.ipynb
80 > ipython nbconvert notebook*.ipynb
58 > ipython nbconvert notebook1.ipynb notebook2.ipynb
81 > ipython nbconvert notebook1.ipynb notebook2.ipynb
59 > ipython nbconvert # this will use the config file to fill in the notebooks
82 > ipython nbconvert --format sphinx_howto notebook.ipynb
60 """)
83 """)
61
62 #Writer specific variables
84 #Writer specific variables
63 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
85 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
64 help="""Instance of the writer class used to write the
86 help="""Instance of the writer class used to write the
65 results of the conversion.""")
87 results of the conversion.""")
66 writer_class = DottedObjectName('FilesWriter', config=True,
88 writer_class = DottedObjectName('FilesWriter', config=True,
67 help="""Writer class used to write the
89 help="""Writer class used to write the
68 results of the conversion""")
90 results of the conversion""")
69 writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter',
91 writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter',
70 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter',
92 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter',
71 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
93 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
72 writer_factory = Type()
94 writer_factory = Type()
73
95
74 def _writer_class_changed(self, name, old, new):
96 def _writer_class_changed(self, name, old, new):
75 if new in self.writer_aliases:
97 if new in self.writer_aliases:
76 new = self.writer_aliases[new]
98 new = self.writer_aliases[new]
77 self.writer_factory = import_item(new)
99 self.writer_factory = import_item(new)
78
100
79
101
80 #Other configurable variables
102 #Other configurable variables
81 export_format = Unicode(
103 export_format = Unicode(
82 "full_html", config=True,
104 "full_html", config=True,
83 help="""If specified, nbconvert will convert the document(s) specified
105 help="""If specified, nbconvert will convert the document(s) specified
84 using this format.""")
106 using this format.""")
85
107
86 notebooks = List([], config=True, help="""List of notebooks to convert.
108 notebooks = List([], config=True, help="""List of notebooks to convert.
87 Search patterns are supported.""")
109 Search patterns are supported.""")
88
110
89 nbconvert_aliases = {'format':'NbConvertApp.export_format',
90 'notebooks':'NbConvertApp.notebooks',
91 'writer':'NbConvertApp.writer_class'}
92
93
94 @catch_config_error
111 @catch_config_error
95 def initialize(self, argv=None):
112 def initialize(self, argv=None):
96 self.aliases.update(self.nbconvert_aliases)
97
98 super(NbConvertApp, self).initialize(argv)
113 super(NbConvertApp, self).initialize(argv)
99
114 self.init_notebooks()
100 #Register class here to have help with help all
101 self.classes.insert(0, Exporter)
102 self.classes.insert(0, WriterBase)
103 self.classes.insert(0, NbConvertBase)
104
105 #Init
106 self.init_config(self.extra_args)
107 self.init_writer()
115 self.init_writer()
108
116
109
117 def init_notebooks(self):
110 def init_config(self, extra_args):
111 """
118 """
112 Add notebooks to the config if needed. Glob each notebook to replace
119 Add notebooks to the config if needed. Glob each notebook to replace
113 notebook patterns with filenames.
120 notebook patterns with filenames.
114 """
121 """
115
122
116 #Get any additional notebook patterns from the commandline
123 #Get any additional notebook patterns from the commandline
117 if len(extra_args) > 0:
124 patterns = self.notebooks + self.extra_args
118 for pattern in extra_args:
119 self.notebooks.append(pattern)
120
125
121 #Use glob to replace all the notebook patterns with filenames.
126 #Use glob to replace all the notebook patterns with filenames.
122 filenames = []
127 filenames = []
123 for pattern in self.notebooks:
128 for pattern in patterns:
124 for filename in glob.glob(pattern):
129 for filename in glob.glob(pattern):
125 if not filename in filenames:
130 if not filename in filenames:
126 filenames.append(filename)
131 filenames.append(filename)
127 self.notebooks = filenames
132 self.notebooks = filenames
128
133
129
130 def init_writer(self):
134 def init_writer(self):
131 """
135 """
132 Initialize the writer (which is stateless)
136 Initialize the writer (which is stateless)
133 """
137 """
134 self._writer_class_changed(None, self.writer_class, self.writer_class)
138 self._writer_class_changed(None, self.writer_class, self.writer_class)
135 self.writer = self.writer_factory(parent=self)
139 self.writer = self.writer_factory(parent=self)
136
140
137
141 def start(self):
138 def start(self, argv=None):
139 """
142 """
140 Ran after initiialization completed
143 Ran after initialization completed
141 """
144 """
142 super(NbConvertApp, self).start()
145 super(NbConvertApp, self).start()
143 self.convert_notebooks()
146 self.convert_notebooks()
144
147
145
146 def convert_notebooks(self):
148 def convert_notebooks(self):
147 """
149 """
148 Convert the notebooks in the self.notebook traitlet
150 Convert the notebooks in the self.notebook traitlet
149 """
151 """
150 #Export each notebook
152 #Export each notebook
151 conversion_success = 0
153 conversion_success = 0
152 for notebook_filename in self.notebooks:
154 for notebook_filename in self.notebooks:
153
155
154 #Get a unique key for the notebook and set it in the resources object.
156 #Get a unique key for the notebook and set it in the resources object.
155 basename = os.path.basename(notebook_filename)
157 basename = os.path.basename(notebook_filename)
156 notebook_name = basename[:basename.rfind('.')]
158 notebook_name = basename[:basename.rfind('.')]
157 resources = {}
159 resources = {}
158 resources['unique_key'] = notebook_name
160 resources['unique_key'] = notebook_name
159
161
160 #Try to export
162 #Try to export
161 try:
163 try:
162 output, resources = export_by_name(self.export_format,
164 output, resources = export_by_name(self.export_format,
163 notebook_filename,
165 notebook_filename,
164 resources=resources,
166 resources=resources,
165 config=self.config)
167 config=self.config)
166 except ExporterNameError as e:
168 except ExporterNameError as e:
167 print("Error: '%s' exporter not found." % self.export_format,
169 print("Error: '%s' exporter not found." % self.export_format,
168 file=sys.stderr)
170 file=sys.stderr)
169 print("Known exporters are:",
171 print("Known exporters are:",
170 "\n\t" + "\n\t".join(get_export_names()),
172 "\n\t" + "\n\t".join(get_export_names()),
171 file=sys.stderr)
173 file=sys.stderr)
172 sys.exit(-1)
174 sys.exit(-1)
173 #except Exception as e:
175 #except Exception as e:
174 #print("Error: could not export '%s'" % notebook_filename, file=sys.stderr)
176 #print("Error: could not export '%s'" % notebook_filename, file=sys.stderr)
175 #print(e, file=sys.stderr)
177 #print(e, file=sys.stderr)
176 else:
178 else:
177 self.writer.write(output, resources, notebook_name=notebook_name)
179 self.writer.write(output, resources, notebook_name=notebook_name)
178 conversion_success += 1
180 conversion_success += 1
179
181
180 #If nothing was converted successfully, help the user.
182 #If nothing was converted successfully, help the user.
181 if conversion_success == 0:
183 if conversion_success == 0:
182
184
183 #No notebooks were specified, show help.
185 #No notebooks were specified, show help.
184 if len(self.notebooks) == 0:
186 if len(self.notebooks) == 0:
185 self.print_help()
187 self.print_help()
186
188
187 #Notebooks were specified, but not converted successfully. Show how
189 #Notebooks were specified, but not converted successfully. Show how
188 #to access help.
190 #to access help.
189 else:
191 else:
190 print('For help, use "ipython nbconvert --help"')
192 print('For help, use "ipython nbconvert --help"')
191
193
192
194
193 #-----------------------------------------------------------------------------
195 #-----------------------------------------------------------------------------
194 # Main entry point
196 # Main entry point
195 #-----------------------------------------------------------------------------
197 #-----------------------------------------------------------------------------
196
198
197 launch_new_instance = NbConvertApp.launch_instance
199 launch_new_instance = NbConvertApp.launch_instance
General Comments 0
You need to be logged in to leave comments. Login now