##// END OF EJS Templates
print supported TARGETs for nbconvert --help
Paul Ivanov -
Show More
@@ -1,226 +1,234 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 Commandline interface for the NBConvert conversion utility. Read the
5 readme.rst for usage information
5 readme.rst for usage information
6 """
6 """
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 #Copyright (c) 2013, the IPython Development Team.
8 #Copyright (c) 2013, the IPython Development Team.
9 #
9 #
10 #Distributed under the terms of the Modified BSD License.
10 #Distributed under the terms of the Modified BSD License.
11 #
11 #
12 #The full license is in the file COPYING.txt, distributed with this software.
12 #The full license is in the file COPYING.txt, distributed with this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 #Imports
16 #Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #Stdlib imports
19 #Stdlib imports
20 from __future__ import print_function
20 from __future__ import print_function
21 import sys
21 import sys
22 import io
22 import io
23 import os
23 import os
24
24
25 #From IPython
25 #From IPython
26 from IPython.config.application import Application
26 from IPython.config.application import Application
27 from IPython.utils.traitlets import Bool, Unicode
27 from IPython.utils.traitlets import Bool, Unicode
28
28
29 from .exporters.export import export_by_name, get_export_names
29 from .exporters.export import export_by_name, get_export_names
30 from .exporters.exporter import Exporter
30 from .exporters.exporter import Exporter
31 from .transformers import extractfigure
31 from .transformers import extractfigure
32 from .utils.config import GlobalConfigurable
32 from .utils.config import GlobalConfigurable
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 #Globals and constants
35 #Globals and constants
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 #'Keys in resources' user prompt.
38 #'Keys in resources' user prompt.
39 KEYS_PROMPT_HEAD = "====================== Keys in Resources =================================="
39 KEYS_PROMPT_HEAD = "====================== Keys in Resources =================================="
40 KEYS_PROMPT_BODY = """
40 KEYS_PROMPT_BODY = """
41 ===========================================================================
41 ===========================================================================
42 You are responsible for writing these files into the appropriate
42 You are responsible for writing these files into the appropriate
43 directory(ies) if need be. If you do not want to see this message, enable
43 directory(ies) if need be. If you do not want to see this message, enable
44 the 'write' (boolean) flag of the converter.
44 the 'write' (boolean) flag of the converter.
45 ===========================================================================
45 ===========================================================================
46 """
46 """
47
47
48 _examples = """
48 _examples = """
49 ipython nbconvert rst Untitled0.ipynb # convert ipynb to ReStructured Text
49 ipython nbconvert rst Untitled0.ipynb # convert ipynb to ReStructured Text
50 ipython nbconvert latex Untitled0.ipynb # convert ipynb to LaTeX
50 ipython nbconvert latex Untitled0.ipynb # convert ipynb to LaTeX
51 ipython nbconvert reveal Untitled0.ipynb # convert to Reveal (HTML/JS) slideshow
51 ipython nbconvert reveal Untitled0.ipynb # convert to Reveal (HTML/JS) slideshow
52 """
52 """
53
53
54
54 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
55 #Classes and functions
56 #Classes and functions
56 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
57
58
58 class NbConvertApp(Application):
59 class NbConvertApp(Application):
59 """Application used to convert to and from notebook file type (*.ipynb)"""
60 __doc__ = """IPython notebook conversion utility
61
62 Convert to and from notebook file type (*.ipynb)
63
64 ipython nbconvert TARGET FILENAME
65
66 Supported export TARGETs are: %s
67 """ % (" ".join(get_export_names()))
60 description = Unicode(__doc__)
68 description = Unicode(__doc__)
61
69
62 examples = _examples
70 examples = _examples
63
71
64 stdout = Bool(
72 stdout = Bool(
65 False, config=True,
73 False, config=True,
66 help="""Whether to print the converted IPYNB file to stdout
74 help="""Whether to print the converted IPYNB file to stdout
67 use full do diff files without actually writing a new file"""
75 use full do diff files without actually writing a new file"""
68 )
76 )
69
77
70 write = Bool(
78 write = Bool(
71 True, config=True,
79 True, config=True,
72 help="""Should the converted notebook file be written to disk
80 help="""Should the converted notebook file be written to disk
73 along with potential extracted resources."""
81 along with potential extracted resources."""
74 )
82 )
75
83
76 aliases = {
84 aliases = {
77 'stdout':'NbConvertApp.stdout',
85 'stdout':'NbConvertApp.stdout',
78 'write':'NbConvertApp.write',
86 'write':'NbConvertApp.write',
79 }
87 }
80
88
81 flags = {}
89 flags = {}
82
90
83 flags['stdout'] = (
91 flags['stdout'] = (
84 {'NbConvertApp' : {'stdout' : True}},
92 {'NbConvertApp' : {'stdout' : True}},
85 """Print converted file to stdout, equivalent to --stdout=True
93 """Print converted file to stdout, equivalent to --stdout=True
86 """
94 """
87 )
95 )
88
96
89 flags['no-write'] = (
97 flags['no-write'] = (
90 {'NbConvertApp' : {'write' : True}},
98 {'NbConvertApp' : {'write' : True}},
91 """Do not write to disk, equivalent to --write=False
99 """Do not write to disk, equivalent to --write=False
92 """
100 """
93 )
101 )
94
102
95
103
96 def __init__(self, **kwargs):
104 def __init__(self, **kwargs):
97 """Public constructor"""
105 """Public constructor"""
98
106
99 #Call base class
107 #Call base class
100 super(NbConvertApp, self).__init__(**kwargs)
108 super(NbConvertApp, self).__init__(**kwargs)
101
109
102 #Register class here to have help with help all
110 #Register class here to have help with help all
103 self.classes.insert(0, Exporter)
111 self.classes.insert(0, Exporter)
104 self.classes.insert(0, GlobalConfigurable)
112 self.classes.insert(0, GlobalConfigurable)
105
113
106
114
107 def start(self, argv=None):
115 def start(self, argv=None):
108 """Entrypoint of NbConvert application.
116 """Entrypoint of NbConvert application.
109
117
110 Parameters
118 Parameters
111 ----------
119 ----------
112 argv : list
120 argv : list
113 Commandline arguments
121 Commandline arguments
114 """
122 """
115
123
116 #Parse the commandline options.
124 #Parse the commandline options.
117 self.parse_command_line(argv)
125 self.parse_command_line(argv)
118
126
119 #Call base
127 #Call base
120 super(NbConvertApp, self).start()
128 super(NbConvertApp, self).start()
121
129
122 #The last arguments in list will be used by nbconvert
130 #The last arguments in list will be used by nbconvert
123 if len(self.extra_args) is not 3:
131 if len(self.extra_args) is not 3:
124 print( "Wrong number of arguments, use --help flag for usage", file=sys.stderr)
132 print( "Wrong number of arguments, use --help flag for usage", file=sys.stderr)
125 sys.exit(-1)
133 sys.exit(-1)
126 export_type = (self.extra_args)[1]
134 export_type = (self.extra_args)[1]
127 ipynb_file = (self.extra_args)[2]
135 ipynb_file = (self.extra_args)[2]
128
136
129 #Export
137 #Export
130 try:
138 try:
131 return_value = export_by_name(export_type, ipynb_file)
139 return_value = export_by_name(export_type, ipynb_file)
132 except NameError as e:
140 except NameError as e:
133 print("Error: '%s' exporter not found." % export_type,
141 print("Error: '%s' exporter not found." % export_type,
134 file=sys.stderr)
142 file=sys.stderr)
135 print("Known exporters are:",
143 print("Known exporters are:",
136 "\n\t" + "\n\t".join(get_export_names()),
144 "\n\t" + "\n\t".join(get_export_names()),
137 file=sys.stderr)
145 file=sys.stderr)
138 sys.exit(-1)
146 sys.exit(-1)
139 else:
147 else:
140 (output, resources, exporter) = return_value
148 (output, resources, exporter) = return_value
141
149
142 #TODO: Allow user to set output directory and file.
150 #TODO: Allow user to set output directory and file.
143 destination_filename = None
151 destination_filename = None
144 destination_directory = None
152 destination_directory = None
145 if self.write:
153 if self.write:
146
154
147 #Get the file name without the '.ipynb' (6 chars) extension and then
155 #Get the file name without the '.ipynb' (6 chars) extension and then
148 #remove any addition periods and spaces. The resulting name will
156 #remove any addition periods and spaces. The resulting name will
149 #be used to create the directory that the files will be exported
157 #be used to create the directory that the files will be exported
150 #into.
158 #into.
151 out_root = ipynb_file[:-6].replace('.', '_').replace(' ', '_')
159 out_root = ipynb_file[:-6].replace('.', '_').replace(' ', '_')
152 destination_filename = os.path.join(out_root+'.'+exporter.file_extension)
160 destination_filename = os.path.join(out_root+'.'+exporter.file_extension)
153
161
154 destination_directory = out_root+'_files'
162 destination_directory = out_root+'_files'
155 if not os.path.exists(destination_directory):
163 if not os.path.exists(destination_directory):
156 os.mkdir(destination_directory)
164 os.mkdir(destination_directory)
157
165
158 #Write the results
166 #Write the results
159 if self.stdout or not (destination_filename is None and destination_directory is None):
167 if self.stdout or not (destination_filename is None and destination_directory is None):
160 self._write_results(output, resources, destination_filename, destination_directory)
168 self._write_results(output, resources, destination_filename, destination_directory)
161
169
162
170
163 def _write_results(self, output, resources, destination_filename=None, destination_directory=None):
171 def _write_results(self, output, resources, destination_filename=None, destination_directory=None):
164 """Output the conversion results to the console and/or filesystem
172 """Output the conversion results to the console and/or filesystem
165
173
166 Parameters
174 Parameters
167 ----------
175 ----------
168 output : str
176 output : str
169 Output of conversion
177 Output of conversion
170 resources : dictionary
178 resources : dictionary
171 Additional input/output used by the transformers. For
179 Additional input/output used by the transformers. For
172 example, the ExtractFigure transformer outputs the
180 example, the ExtractFigure transformer outputs the
173 figures it extracts into this dictionary. This method
181 figures it extracts into this dictionary. This method
174 relies on the figures being in this dictionary when
182 relies on the figures being in this dictionary when
175 attempting to write the figures to the file system.
183 attempting to write the figures to the file system.
176 destination_filename : str, Optional
184 destination_filename : str, Optional
177 Filename to write output into. If None, output is not
185 Filename to write output into. If None, output is not
178 written to a file.
186 written to a file.
179 destination_directory : str, Optional
187 destination_directory : str, Optional
180 Directory to write notebook data (i.e. figures) to. If
188 Directory to write notebook data (i.e. figures) to. If
181 None, figures are not written to the file system.
189 None, figures are not written to the file system.
182 """
190 """
183
191
184 if self.stdout:
192 if self.stdout:
185 print(output.encode('utf-8'))
193 print(output.encode('utf-8'))
186
194
187 #Write file output from conversion.
195 #Write file output from conversion.
188 if not destination_filename is None:
196 if not destination_filename is None:
189 with io.open(destination_filename, 'w') as f:
197 with io.open(destination_filename, 'w') as f:
190 f.write(output)
198 f.write(output)
191
199
192 #Get the key names used by the extract figure transformer
200 #Get the key names used by the extract figure transformer
193 figures_key = extractfigure.FIGURES_KEY
201 figures_key = extractfigure.FIGURES_KEY
194 binary_key = extractfigure.BINARY_KEY
202 binary_key = extractfigure.BINARY_KEY
195 text_key = extractfigure.TEXT_KEY
203 text_key = extractfigure.TEXT_KEY
196
204
197 #Output any associate figures into the same "root" directory.
205 #Output any associate figures into the same "root" directory.
198 binkeys = resources.get(figures_key, {}).get(binary_key,{}).keys()
206 binkeys = resources.get(figures_key, {}).get(binary_key,{}).keys()
199 textkeys = resources.get(figures_key, {}).get(text_key,{}).keys()
207 textkeys = resources.get(figures_key, {}).get(text_key,{}).keys()
200 if binkeys or textkeys :
208 if binkeys or textkeys :
201 if not destination_directory is None:
209 if not destination_directory is None:
202 for key in binkeys:
210 for key in binkeys:
203 with io.open(os.path.join(destination_directory, key), 'wb') as f:
211 with io.open(os.path.join(destination_directory, key), 'wb') as f:
204 f.write(resources[figures_key][binary_key][key])
212 f.write(resources[figures_key][binary_key][key])
205 for key in textkeys:
213 for key in textkeys:
206 with io.open(os.path.join(destination_directory, key), 'w') as f:
214 with io.open(os.path.join(destination_directory, key), 'w') as f:
207 f.write(resources[figures_key][text_key][key])
215 f.write(resources[figures_key][text_key][key])
208
216
209 #Figures that weren't exported which will need to be created by the
217 #Figures that weren't exported which will need to be created by the
210 #user. Tell the user what figures these are.
218 #user. Tell the user what figures these are.
211 if self.stdout:
219 if self.stdout:
212 print(KEYS_PROMPT_HEAD, file=sys.stderr)
220 print(KEYS_PROMPT_HEAD, file=sys.stderr)
213 print(resources[figures_key].keys(), file=sys.stderr)
221 print(resources[figures_key].keys(), file=sys.stderr)
214 print(KEYS_PROMPT_BODY , file=sys.stderr)
222 print(KEYS_PROMPT_BODY , file=sys.stderr)
215
223
216 #-----------------------------------------------------------------------------
224 #-----------------------------------------------------------------------------
217 # Main entry point
225 # Main entry point
218 #-----------------------------------------------------------------------------
226 #-----------------------------------------------------------------------------
219
227
220 def launch_new_instance():
228 def launch_new_instance():
221 """Application entry point"""
229 """Application entry point"""
222
230
223 app = NbConvertApp.instance()
231 app = NbConvertApp.instance()
224 app.description = __doc__
232 app.description = __doc__
225 app.start(argv=sys.argv)
233 app.start(argv=sys.argv)
226
234
General Comments 0
You need to be logged in to leave comments. Login now