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