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