##// END OF EJS Templates
Comment & Refactor, utils and nbconvert main.
Jonathan Frederic -
Show More
@@ -0,0 +1,121 b''
1 """Utility functions for interacting with the console"""
2 #-----------------------------------------------------------------------------
3 # Copyright (c) 2013, the IPython Development Team.
4 #
5 # Distributed under the terms of the Modified BSD License.
6 #
7 # The full license is in the file COPYING.txt, distributed with this software.
8 #-----------------------------------------------------------------------------
9
10 #-----------------------------------------------------------------------------
11 # Imports
12 #-----------------------------------------------------------------------------
13
14 # Used to determine python version
15 import sys
16
17 #-----------------------------------------------------------------------------
18 # Classes and functions
19 #-----------------------------------------------------------------------------
20
21 def input(self, prompt_text):
22 """
23 Prompt the user for input.
24
25 The input command will change depending on the version of python
26 installed. To maintain support for 2 and earlier, we must use
27 raw_input in that case. Else use input.
28
29 Parameters
30 ----------
31 prompt_text : str
32 Prompt to display to the user.
33 """
34
35 # Try to get the python version. This command is only available in
36 # python 2 and later, so it's important that we catch the exception
37 # if the command isn't found.
38 try:
39 majorversion = sys.version_info[0]
40 except:
41 majorversion = 1
42
43 # Use the correct function to prompt the user for input depending on
44 # what python version the code is running in.
45 if majorversion >= 3:
46 return input(prompt_text)
47 else:
48 return raw_input(prompt_text)
49
50
51 def prompt_boolean(self, prompt, default=False):
52 """
53 Prompt the user for a boolean response.
54
55 Parameters
56 ----------
57 prompt : str
58 prompt to display to the user
59 default : bool, optional
60 response to return if none is given by the user
61 """
62
63 response = self._input(prompt)
64 response = response.strip().lower()
65
66 #Catch 1, true, yes as True
67 if len(response) > 0 and (response == "1" or response[0] == "t" or response[0] == "y"):
68 return True
69
70 #Catch 0, false, no as False
71 elif len(response) > 0 and (response == "0" or response[0] == "f" or response[0] == "n"):
72 return False
73
74 else:
75 return default
76
77
78 def prompt_dictionary(self, choices, default_style=1, menu_comments={}):
79 """
80 Prompt the user to chose one of many selections from a menu.
81
82 Parameters
83 ----------
84 choices : dictionary
85 Keys - choice numbers (int)
86 Values - choice value (str), this is what the function will return
87 default_style : int, optional
88 Choice to select if the user doesn't respond
89 menu_comments : dictionary, optional
90 Additional comments to append to the menu as it is displayed
91 in the console.
92 Keys - choice numbers (int)
93 Values - comment (str), what will be appended to the
94 corresponding choice
95 """
96
97 # Build the menu that will be displayed to the user with
98 # all of the options available.
99 prompt = ""
100 for key, value in choices.iteritems():
101 prompt += "%d %s " % (key, value)
102 if key in menu_comments:
103 prompt += menu_comments[key]
104 prompt += "\n"
105
106 # Continue to ask the user for a style until an appropriate
107 # one is specified.
108 response = -1
109 while (not response in choices):
110 try:
111 text_response = self._input(prompt)
112
113 # Use default option if no input.
114 if len(text_response.strip()) == 0:
115 response = default_style
116 else:
117 response = int(text_response)
118 except:
119 print("Error: Value is not an available option. 0 selects the default.\n")
120 return choices[response]
121 No newline at end of file
@@ -1,5 +1,4 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2
3 """NBConvert is a utility for conversion of IPYNB files.
2 """NBConvert is a utility for conversion of IPYNB files.
4
3
5 Commandline interface for the NBConvert conversion utility. Read the
4 Commandline interface for the NBConvert conversion utility. Read the
@@ -26,15 +25,16 b' import os'
26 #From IPython
25 #From IPython
27 #All the stuff needed for the configurable things
26 #All the stuff needed for the configurable things
28 from IPython.config.application import Application
27 from IPython.config.application import Application
28 from IPython.utils.traitlets import (Bool)
29
29
30 #Local imports
30 #Local imports
31 from nbconvert.api.convert import export_by_name
31 from nbconvert.api.convert import export_by_name
32 from nbconvert.api.exporter import Exporter
32 from nbconvert.api.exporter import Exporter
33 from nbconvert.transformers import extractfigure
33
34
34 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
35 #Globals and constants
36 #Globals and constants
36 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
37 NBCONVERT_DIR = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
38
38
39 #'Keys in resources' user prompt.
39 #'Keys in resources' user prompt.
40 KEYS_PROMPT_HEAD = "====================== Keys in Resources =================================="
40 KEYS_PROMPT_HEAD = "====================== Keys in Resources =================================="
@@ -46,56 +46,62 b" the 'write' (boolean) flag of the converter."
46 ===========================================================================
46 ===========================================================================
47 """
47 """
48
48
49 #Error Messages
50 ERROR_CONFIG_NOT_FOUND = "Config file for profile '%s' not found, giving up."
51
52 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
53 #Classes and functions
50 #Classes and functions
54 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
55 class NbconvertApp(Application):
52
56 """A basic application to convert ipynb files"""
53 class NbConvertApp(Application):
57
54 """Application used to convert to and from notebook file type (*.ipynb)"""
58 aliases = {
55
59 'stdout':'NbconvertApp.stdout',
56 stdout = Bool(
60 'write':'NbconvertApp.write'
57 True, config=True,
61 }
58 help="""Whether to print the converted IPYNB file to stdout
62
59 use full do diff files without actually writing a new file"""
63 flags = {}
64 flags['no-stdout'] = (
65 {'NbconvertApp' : {'stdout' : False}},
66 """Do not print converted file to stdout, equivalent to
67 --stdout=False"""
68 )
60 )
69
61
62 write = Bool(
63 False, config=True,
64 help="""Should the converted notebook file be written to disk
65 along with potential extracted resources."""
66 )
67
68
70 def __init__(self, **kwargs):
69 def __init__(self, **kwargs):
71 """Public constructor"""
70 """Public constructor"""
72
71
73 #Call base class
72 #Call base class
74 super(NbconvertApp, self).__init__(**kwargs)
73 super(NbConvertApp, self).__init__(**kwargs)
75
74
76 #Register class here to have help with help all
75 #Register class here to have help with help all
77 self.classes.insert(0, Exporter)
76 self.classes.insert(0, Exporter)
78
77
79
78
80 def start(self, argv=None):
79 def start(self, argv=None):
81 """Convert a notebook in one step"""
80 """Entrypoint of NbConvert application.
81
82 Parameters
83 ----------
84 argv : list
85 Commandline arguments
86 """
82
87
83 #Parse the commandline options.
88 #Parse the commandline options.
84 self.parse_command_line(argv)
89 self.parse_command_line(argv)
85
90
86 #Call base
91 #Call base
87 super(NbconvertApp, self).start()
92 super(NbConvertApp, self).start()
88
93
89 #The last arguments in chain of arguments will be used as conversion type
94 #The last arguments in list will be used by nbconvert
90 ipynb_file = (self.extra_args)[2]
91 export_type = (self.extra_args)[1]
95 export_type = (self.extra_args)[1]
96 ipynb_file = (self.extra_args)[2]
92
97
93 #Export
98 #Export
94 output, resources, exporter = export_by_name(ipynb_file, export_type)
99 output, resources, exporter = export_by_name(ipynb_file, export_type)
95
100
101 #TODO: Allow user to set output directory and file.
96 destination_filename = None
102 destination_filename = None
97 destination_directory = None
103 destination_directory = None
98 if exporter.write:
104 if self.write:
99
105
100 #Get the file name without the '.ipynb' (6 chars) extension and then
106 #Get the file name without the '.ipynb' (6 chars) extension and then
101 #remove any addition periods and spaces. The resulting name will
107 #remove any addition periods and spaces. The resulting name will
@@ -109,11 +115,33 b' class NbconvertApp(Application):'
109 os.mkdir(destination_directory)
115 os.mkdir(destination_directory)
110
116
111 #Write the results
117 #Write the results
112 if exporter.stdout or exporter.write:
118 if self.stdout or not (destination_filename is None and destination_directory is None):
113 self._write_results(exporter.stdout, destination_filename, destination_directory, output, resources)
119 self._write_results(output, resources, self.stdout, destination_filename, destination_directory)
114
120
121
122 def _write_results(self, output, resources, stdout=False, destination_filename=None, destination_directory=None):
123 """Output the conversion results to the console and/or filesystem
124
125 Parameters
126 ----------
127 output : str
128 Output of conversion
129 resources : dictionary
130 Additional input/output used by the transformers. For
131 example, the ExtractFigure transformer outputs the
132 figures it extracts into this dictionary. This method
133 relies on the figures being in this dictionary when
134 attempting to write the figures to the file system.
135 stdout : bool, Optional
136 Whether or not to echo output to console
137 destination_filename : str, Optional
138 Filename to write output into. If None, output is not
139 written to a file.
140 destination_directory : str, Optional
141 Directory to write notebook data (i.e. figures) to. If
142 None, figures are not written to the file system.
143 """
115
144
116 def _write_results(self, stdout, destination_filename, destination_directory, output, resources):
117 if stdout:
145 if stdout:
118 print(output.encode('utf-8'))
146 print(output.encode('utf-8'))
119
147
@@ -122,34 +150,41 b' class NbconvertApp(Application):'
122 with io.open(destination_filename, 'w') as f:
150 with io.open(destination_filename, 'w') as f:
123 f.write(output)
151 f.write(output)
124
152
153 #Get the key names used by the extract figure transformer
154 figures_key = extractfigure.FIGURES_KEY
155 binary_key = extractfigure.BINARY_KEY
156 text_key = extractfigure.TEXT_KEY
157
125 #Output any associate figures into the same "root" directory.
158 #Output any associate figures into the same "root" directory.
126 binkeys = resources.get('figures', {}).get('binary',{}).keys()
159 binkeys = resources.get(figures_key, {}).get(binary_key,{}).keys()
127 textkeys = resources.get('figures', {}).get('text',{}).keys()
160 textkeys = resources.get(figures_key, {}).get(text_key,{}).keys()
128 if binkeys or textkeys :
161 if binkeys or textkeys :
129 if not destination_directory is None:
162 if not destination_directory is None:
130 for key in binkeys:
163 for key in binkeys:
131 with io.open(os.path.join(destination_directory, key), 'wb') as f:
164 with io.open(os.path.join(destination_directory, key), 'wb') as f:
132 f.write(resources['figures']['binary'][key])
165 f.write(resources[figures_key][binary_key][key])
133 for key in textkeys:
166 for key in textkeys:
134 with io.open(os.path.join(destination_directory, key), 'w') as f:
167 with io.open(os.path.join(destination_directory, key), 'w') as f:
135 f.write(resources['figures']['text'][key])
168 f.write(resources[figures_key][text_key][key])
136
169
137 #Figures that weren't exported which will need to be created by the
170 #Figures that weren't exported which will need to be created by the
138 #user. Tell the user what figures these are.
171 #user. Tell the user what figures these are.
139 if stdout:
172 if stdout:
140 print(KEYS_PROMPT_HEAD)
173 print(KEYS_PROMPT_HEAD)
141 print(resources['figures'].keys())
174 print(resources[figures_key].keys())
142 print(KEYS_PROMPT_BODY)
175 print(KEYS_PROMPT_BODY)
143
176
144 #-----------------------------------------------------------------------------
177 #-----------------------------------------------------------------------------
145 #Script main
178 #Script main
146 #-----------------------------------------------------------------------------
179 #-----------------------------------------------------------------------------
180
147 def main():
181 def main():
148 """Convert a notebook in one step"""
182 """Application entry point"""
149
183
150 app = NbconvertApp.instance()
184 app = NbConvertApp.instance()
151 app.description = __doc__
185 app.description = __doc__
152 app.start(argv=sys.argv)
186 app.start(argv=sys.argv)
153
187
188 #Check to see if python is calling this file directly.
154 if __name__ == '__main__':
189 if __name__ == '__main__':
155 main() No newline at end of file
190 main()
@@ -1,4 +1,4 b''
1 """Contains all of the exceptions used in NBConvert explicitly"""
1 """NbConvert specific exceptions"""
2 #-----------------------------------------------------------------------------
2 #-----------------------------------------------------------------------------
3 # Copyright (c) 2013, the IPython Development Team.
3 # Copyright (c) 2013, the IPython Development Team.
4 #
4 #
@@ -8,13 +8,9 b''
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Imports
12 #-----------------------------------------------------------------------------
13 from __future__ import print_function
14
15 #-----------------------------------------------------------------------------
16 # Classes and functions
11 # Classes and functions
17 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
18 class ConversionException(Exception):
14 class ConversionException(Exception):
19 """An exception raised by the conversion process."""
15 """An exception raised by the conversion process."""
20
16
@@ -4,7 +4,7 b" Informs The pygments highlighting library of the quirks of IPython's superset"
4 of Python -- magic commands, !shell commands, etc.
4 of Python -- magic commands, !shell commands, etc.
5 """
5 """
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (c) 2012, the IPython Development Team.
7 # Copyright (c) 2013, the IPython Development Team.
8 #
8 #
9 # Distributed under the terms of the Modified BSD License.
9 # Distributed under the terms of the Modified BSD License.
10 #
10 #
@@ -20,15 +20,23 b' from pygments.lexers import PythonLexer, BashLexer'
20 from pygments.lexer import bygroups, using
20 from pygments.lexer import bygroups, using
21 from pygments.token import Keyword, Operator, Text
21 from pygments.token import Keyword, Operator, Text
22
22
23
24 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
25 # Class declarations
24 # Class declarations
26 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
27
26
28 class IPythonLexer(PythonLexer):
27 class IPythonLexer(PythonLexer):
28 """
29 Pygments Lexer for use with IPython code. Inherits from
30 PythonLexer and adds information about IPython specific
31 keywords (i.e. magic commands, shell commands, etc.)
32 """
33
34 #Basic properties
29 name = 'IPython'
35 name = 'IPython'
30 aliases = ['ip', 'ipython']
36 aliases = ['ip', 'ipython']
31 filenames = ['*.ipy']
37 filenames = ['*.ipy']
38
39 #Highlighting information
32 tokens = PythonLexer.tokens.copy()
40 tokens = PythonLexer.tokens.copy()
33 tokens['root'] = [
41 tokens['root'] = [
34 (r'(\%+)(\w+)\s+(\.*)(\n)', bygroups(Operator, Keyword,
42 (r'(\%+)(\w+)\s+(\.*)(\n)', bygroups(Operator, Keyword,
General Comments 0
You need to be logged in to leave comments. Login now