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