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