Show More
@@ -1,594 +1,601 b'' | |||||
1 | """ History related magics and functionality """ |
|
1 | """ History related magics and functionality """ | |
2 | #----------------------------------------------------------------------------- |
|
2 | #----------------------------------------------------------------------------- | |
3 | # Copyright (C) 2010 The IPython Development Team. |
|
3 | # Copyright (C) 2010 The IPython Development Team. | |
4 | # |
|
4 | # | |
5 | # Distributed under the terms of the BSD License. |
|
5 | # Distributed under the terms of the BSD License. | |
6 | # |
|
6 | # | |
7 | # The full license is in the file COPYING.txt, distributed with this software. |
|
7 | # The full license is in the file COPYING.txt, distributed with this software. | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Imports |
|
11 | # Imports | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | from __future__ import print_function |
|
13 | from __future__ import print_function | |
14 |
|
14 | |||
15 | # Stdlib imports |
|
15 | # Stdlib imports | |
16 | import atexit |
|
16 | import atexit | |
17 | import fnmatch |
|
17 | import fnmatch | |
18 | import json |
|
18 | import json | |
19 | import os |
|
19 | import os | |
20 | import sys |
|
20 | import sys | |
21 | import threading |
|
21 | import threading | |
22 | import time |
|
22 | import time | |
23 |
|
23 | |||
24 | # Our own packages |
|
24 | # Our own packages | |
25 | import IPython.utils.io |
|
25 | import IPython.utils.io | |
26 |
|
26 | |||
27 | from IPython.testing import decorators as testdec |
|
27 | from IPython.testing import decorators as testdec | |
28 | from IPython.utils.pickleshare import PickleShareDB |
|
28 | from IPython.utils.pickleshare import PickleShareDB | |
29 | from IPython.utils.io import ask_yes_no |
|
29 | from IPython.utils.io import ask_yes_no | |
30 | from IPython.utils.warn import warn |
|
30 | from IPython.utils.warn import warn | |
31 |
|
31 | |||
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 | # Classes and functions |
|
33 | # Classes and functions | |
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 |
|
35 | |||
36 | class HistoryManager(object): |
|
36 | class HistoryManager(object): | |
37 | """A class to organize all history-related functionality in one place. |
|
37 | """A class to organize all history-related functionality in one place. | |
38 | """ |
|
38 | """ | |
39 | # Public interface |
|
39 | # Public interface | |
40 |
|
40 | |||
41 | # An instance of the IPython shell we are attached to |
|
41 | # An instance of the IPython shell we are attached to | |
42 | shell = None |
|
42 | shell = None | |
43 | # A list to hold processed history |
|
43 | # A list to hold processed history | |
44 | input_hist_parsed = None |
|
44 | input_hist_parsed = None | |
45 | # A list to hold raw history (as typed by user) |
|
45 | # A list to hold raw history (as typed by user) | |
46 | input_hist_raw = None |
|
46 | input_hist_raw = None | |
47 | # A list of directories visited during session |
|
47 | # A list of directories visited during session | |
48 | dir_hist = None |
|
48 | dir_hist = None | |
49 | # A dict of output history, keyed with ints from the shell's execution count |
|
49 | # A dict of output history, keyed with ints from the shell's execution count | |
50 | output_hist = None |
|
50 | output_hist = None | |
51 | # String with path to the history file |
|
51 | # String with path to the history file | |
52 | hist_file = None |
|
52 | hist_file = None | |
53 | # PickleShareDB instance holding the raw data for the shadow history |
|
53 | # PickleShareDB instance holding the raw data for the shadow history | |
54 | shadow_db = None |
|
54 | shadow_db = None | |
55 | # ShadowHist instance with the actual shadow history |
|
55 | # ShadowHist instance with the actual shadow history | |
56 | shadow_hist = None |
|
56 | shadow_hist = None | |
57 |
|
57 | |||
58 | # Offset so the first line of the current session is #1. Can be |
|
58 | # Offset so the first line of the current session is #1. Can be | |
59 | # updated after loading history from file. |
|
59 | # updated after loading history from file. | |
60 | session_offset = -1 |
|
60 | session_offset = -1 | |
61 |
|
61 | |||
62 | # Private interface |
|
62 | # Private interface | |
63 | # Variables used to store the three last inputs from the user. On each new |
|
63 | # Variables used to store the three last inputs from the user. On each new | |
64 | # history update, we populate the user's namespace with these, shifted as |
|
64 | # history update, we populate the user's namespace with these, shifted as | |
65 | # necessary. |
|
65 | # necessary. | |
66 | _i00, _i, _ii, _iii = '','','','' |
|
66 | _i00, _i, _ii, _iii = '','','','' | |
67 |
|
67 | |||
68 | # A set with all forms of the exit command, so that we don't store them in |
|
68 | # A set with all forms of the exit command, so that we don't store them in | |
69 | # the history (it's annoying to rewind the first entry and land on an exit |
|
69 | # the history (it's annoying to rewind the first entry and land on an exit | |
70 | # call). |
|
70 | # call). | |
71 | _exit_commands = None |
|
71 | _exit_commands = None | |
72 |
|
72 | |||
73 | def __init__(self, shell, load_history=False): |
|
73 | def __init__(self, shell, load_history=False): | |
74 | """Create a new history manager associated with a shell instance. |
|
74 | """Create a new history manager associated with a shell instance. | |
75 |
|
75 | |||
76 | Parameters |
|
76 | Parameters | |
77 | ---------- |
|
77 | ---------- | |
78 | load_history: bool, optional |
|
78 | load_history: bool, optional | |
79 | If True, history will be loaded from file, and the session |
|
79 | If True, history will be loaded from file, and the session | |
80 | offset set, so that the next line entered can be retrieved |
|
80 | offset set, so that the next line entered can be retrieved | |
81 | as #1. |
|
81 | as #1. | |
82 | """ |
|
82 | """ | |
83 | # We need a pointer back to the shell for various tasks. |
|
83 | # We need a pointer back to the shell for various tasks. | |
84 | self.shell = shell |
|
84 | self.shell = shell | |
85 |
|
85 | |||
86 | # List of input with multi-line handling. |
|
86 | # List of input with multi-line handling. | |
87 | self.input_hist_parsed = [] |
|
87 | self.input_hist_parsed = [] | |
88 | # This one will hold the 'raw' input history, without any |
|
88 | # This one will hold the 'raw' input history, without any | |
89 | # pre-processing. This will allow users to retrieve the input just as |
|
89 | # pre-processing. This will allow users to retrieve the input just as | |
90 | # it was exactly typed in by the user, with %hist -r. |
|
90 | # it was exactly typed in by the user, with %hist -r. | |
91 | self.input_hist_raw = [] |
|
91 | self.input_hist_raw = [] | |
92 |
|
92 | |||
93 | # list of visited directories |
|
93 | # list of visited directories | |
94 | try: |
|
94 | try: | |
95 | self.dir_hist = [os.getcwd()] |
|
95 | self.dir_hist = [os.getcwd()] | |
96 | except OSError: |
|
96 | except OSError: | |
97 | self.dir_hist = [] |
|
97 | self.dir_hist = [] | |
98 |
|
98 | |||
99 | # dict of output history |
|
99 | # dict of output history | |
100 | self.output_hist = {} |
|
100 | self.output_hist = {} | |
101 |
|
101 | |||
102 | # Now the history file |
|
102 | # Now the history file | |
103 | if shell.profile: |
|
103 | if shell.profile: | |
104 | histfname = 'history-%s' % shell.profile |
|
104 | histfname = 'history-%s' % shell.profile | |
105 | else: |
|
105 | else: | |
106 | histfname = 'history' |
|
106 | histfname = 'history' | |
107 | self.hist_file = os.path.join(shell.ipython_dir, histfname + '.json') |
|
107 | self.hist_file = os.path.join(shell.ipython_dir, histfname + '.json') | |
108 |
|
108 | |||
109 | # Objects related to shadow history management |
|
109 | # Objects related to shadow history management | |
110 | self._init_shadow_hist() |
|
110 | self._init_shadow_hist() | |
111 |
|
111 | |||
112 | self._i00, self._i, self._ii, self._iii = '','','','' |
|
112 | self._i00, self._i, self._ii, self._iii = '','','','' | |
113 |
|
113 | |||
114 | self._exit_commands = set(['Quit', 'quit', 'Exit', 'exit', '%Quit', |
|
114 | self._exit_commands = set(['Quit', 'quit', 'Exit', 'exit', '%Quit', | |
115 | '%quit', '%Exit', '%exit']) |
|
115 | '%quit', '%Exit', '%exit']) | |
116 |
|
116 | |||
117 | # Object is fully initialized, we can now call methods on it. |
|
117 | # Object is fully initialized, we can now call methods on it. | |
118 |
|
118 | |||
119 | if load_history: |
|
119 | if load_history: | |
120 | self.reload_history() |
|
120 | self.reload_history() | |
121 | self.session_offset = len(self.input_hist_raw) -1 |
|
121 | self.session_offset = len(self.input_hist_raw) -1 | |
122 |
|
122 | |||
123 | # Create and start the autosaver. |
|
123 | # Create and start the autosaver. | |
124 | self.autosave_flag = threading.Event() |
|
124 | self.autosave_flag = threading.Event() | |
125 | self.autosave_timer = HistorySaveThread(self.autosave_flag, 60) |
|
125 | self.autosave_timer = HistorySaveThread(self.autosave_flag, 60) | |
126 | self.autosave_timer.start() |
|
126 | self.autosave_timer.start() | |
127 | # Register the autosave handler to be triggered as a post execute |
|
127 | # Register the autosave handler to be triggered as a post execute | |
128 | # callback. |
|
128 | # callback. | |
129 | self.shell.register_post_execute(self.autosave_if_due) |
|
129 | self.shell.register_post_execute(self.autosave_if_due) | |
130 |
|
130 | |||
131 |
|
131 | |||
132 | def _init_shadow_hist(self): |
|
132 | def _init_shadow_hist(self): | |
133 | try: |
|
133 | try: | |
134 | self.shadow_db = PickleShareDB(os.path.join( |
|
134 | self.shadow_db = PickleShareDB(os.path.join( | |
135 | self.shell.ipython_dir, 'db')) |
|
135 | self.shell.ipython_dir, 'db')) | |
136 | except UnicodeDecodeError: |
|
136 | except UnicodeDecodeError: | |
137 | print("Your ipython_dir can't be decoded to unicode!") |
|
137 | print("Your ipython_dir can't be decoded to unicode!") | |
138 | print("Please set HOME environment variable to something that") |
|
138 | print("Please set HOME environment variable to something that") | |
139 | print(r"only has ASCII characters, e.g. c:\home") |
|
139 | print(r"only has ASCII characters, e.g. c:\home") | |
140 | print("Now it is", self.ipython_dir) |
|
140 | print("Now it is", self.ipython_dir) | |
141 | sys.exit() |
|
141 | sys.exit() | |
142 | self.shadow_hist = ShadowHist(self.shadow_db, self.shell) |
|
142 | self.shadow_hist = ShadowHist(self.shadow_db, self.shell) | |
143 |
|
143 | |||
144 | def populate_readline_history(self): |
|
144 | def populate_readline_history(self): | |
145 | """Populate the readline history from the raw history. |
|
145 | """Populate the readline history from the raw history. | |
146 |
|
146 | |||
147 | We only store one copy of the raw history, which is persisted to a json |
|
147 | We only store one copy of the raw history, which is persisted to a json | |
148 | file on disk. The readline history is repopulated from the contents of |
|
148 | file on disk. The readline history is repopulated from the contents of | |
149 | this file.""" |
|
149 | this file.""" | |
150 |
|
150 | |||
151 | try: |
|
151 | try: | |
152 | self.shell.readline.clear_history() |
|
152 | self.shell.readline.clear_history() | |
153 | except AttributeError: |
|
153 | except AttributeError: | |
154 | pass |
|
154 | pass | |
155 | else: |
|
155 | else: | |
156 | for h in self.input_hist_raw: |
|
156 | for h in self.input_hist_raw: | |
157 | if not h.isspace(): |
|
157 | if not h.isspace(): | |
158 | for line in h.splitlines(): |
|
158 | for line in h.splitlines(): | |
159 | self.shell.readline.add_history(line) |
|
159 | self.shell.readline.add_history(line) | |
160 |
|
160 | |||
161 | def save_history(self): |
|
161 | def save_history(self): | |
162 | """Save input history to a file (via readline library).""" |
|
162 | """Save input history to a file (via readline library).""" | |
163 | hist = dict(raw=self.input_hist_raw, #[-self.shell.history_length:], |
|
163 | hist = dict(raw=self.input_hist_raw, #[-self.shell.history_length:], | |
164 | parsed=self.input_hist_parsed) #[-self.shell.history_length:]) |
|
164 | parsed=self.input_hist_parsed) #[-self.shell.history_length:]) | |
165 | with open(self.hist_file,'wt') as hfile: |
|
165 | with open(self.hist_file,'wt') as hfile: | |
166 | json.dump(hist, hfile, |
|
166 | json.dump(hist, hfile, | |
167 | sort_keys=True, indent=4) |
|
167 | sort_keys=True, indent=4) | |
168 |
|
168 | |||
169 | def autosave_if_due(self): |
|
169 | def autosave_if_due(self): | |
170 | """Check if the autosave event is set; if so, save history. We do it |
|
170 | """Check if the autosave event is set; if so, save history. We do it | |
171 | this way so that the save takes place in the main thread.""" |
|
171 | this way so that the save takes place in the main thread.""" | |
172 | if self.autosave_flag.is_set(): |
|
172 | if self.autosave_flag.is_set(): | |
173 | self.save_history() |
|
173 | self.save_history() | |
174 | self.autosave_flag.clear() |
|
174 | self.autosave_flag.clear() | |
175 |
|
175 | |||
176 | def reload_history(self): |
|
176 | def reload_history(self): | |
177 | """Reload the input history from disk file.""" |
|
177 | """Reload the input history from disk file.""" | |
178 |
|
178 | |||
179 | with open(self.hist_file,'rt') as hfile: |
|
179 | with open(self.hist_file,'rt') as hfile: | |
180 | try: |
|
180 | try: | |
181 | hist = json.load(hfile) |
|
181 | hist = json.load(hfile) | |
182 | except ValueError: # Ignore it if JSON is corrupt. |
|
182 | except ValueError: # Ignore it if JSON is corrupt. | |
183 | return |
|
183 | return | |
184 | self.input_hist_parsed = hist['parsed'] |
|
184 | self.input_hist_parsed = hist['parsed'] | |
185 | self.input_hist_raw = hist['raw'] |
|
185 | self.input_hist_raw = hist['raw'] | |
186 | if self.shell.has_readline: |
|
186 | if self.shell.has_readline: | |
187 | self.populate_readline_history() |
|
187 | self.populate_readline_history() | |
188 |
|
188 | |||
189 | def get_history(self, index=None, raw=False, output=True): |
|
189 | def get_history(self, index=None, raw=False, output=True,this_session=True): | |
190 | """Get the history list. |
|
190 | """Get the history list. | |
191 |
|
191 | |||
192 | Get the input and output history. |
|
192 | Get the input and output history. | |
193 |
|
193 | |||
194 | Parameters |
|
194 | Parameters | |
195 | ---------- |
|
195 | ---------- | |
196 | index : n or (n1, n2) or None |
|
196 | index : n or (n1, n2) or None | |
197 | If n, then the last n entries. If a tuple, then all in |
|
197 | If n, then the last n entries. If a tuple, then all in | |
198 | range(n1, n2). If None, then all entries. Raises IndexError if |
|
198 | range(n1, n2). If None, then all entries. Raises IndexError if | |
199 | the format of index is incorrect. |
|
199 | the format of index is incorrect. | |
200 | raw : bool |
|
200 | raw : bool | |
201 | If True, return the raw input. |
|
201 | If True, return the raw input. | |
202 | output : bool |
|
202 | output : bool | |
203 | If True, then return the output as well. |
|
203 | If True, then return the output as well. | |
|
204 | this_session : bool | |||
|
205 | If True, indexing is from 1 at the start of this session. | |||
|
206 | If False, indexing is from 1 at the start of the whole history. | |||
204 |
|
207 | |||
205 | Returns |
|
208 | Returns | |
206 | ------- |
|
209 | ------- | |
207 | If output is True, then return a dict of tuples, keyed by the prompt |
|
210 | If output is True, then return a dict of tuples, keyed by the prompt | |
208 | numbers and with values of (input, output). If output is False, then |
|
211 | numbers and with values of (input, output). If output is False, then | |
209 | a dict, keyed by the prompt number with the values of input. |
|
212 | a dict, keyed by the prompt number with the values of input. | |
210 | """ |
|
213 | """ | |
211 | if raw: |
|
214 | if raw: | |
212 | input_hist = self.input_hist_raw |
|
215 | input_hist = self.input_hist_raw | |
213 | else: |
|
216 | else: | |
214 | input_hist = self.input_hist_parsed |
|
217 | input_hist = self.input_hist_parsed | |
215 | if output: |
|
218 | if output: | |
216 | output_hist = self.output_hist |
|
219 | output_hist = self.output_hist | |
|
220 | ||||
|
221 | if this_session: | |||
|
222 | offset = self.session_offset | |||
|
223 | else: | |||
|
224 | offset = -1 | |||
217 |
|
225 | |||
218 | n = len(input_hist) |
|
226 | n = len(input_hist) | |
219 | offset = self.session_offset |
|
|||
220 | if index is None: |
|
227 | if index is None: | |
221 | start=offset+1; stop=n |
|
228 | start=offset+1; stop=n | |
222 | elif isinstance(index, int): |
|
229 | elif isinstance(index, int): | |
223 | start=n-index; stop=n |
|
230 | start=n-index; stop=n | |
224 | elif len(index) == 2: |
|
231 | elif len(index) == 2: | |
225 | start = index[0] + offset |
|
232 | start = index[0] + offset | |
226 | stop = index[1] + offset |
|
233 | stop = index[1] + offset | |
227 | else: |
|
234 | else: | |
228 | raise IndexError('Not a valid index for the input history: %r' |
|
235 | raise IndexError('Not a valid index for the input history: %r' | |
229 | % index) |
|
236 | % index) | |
230 | hist = {} |
|
237 | hist = {} | |
231 | for i in range(start, stop): |
|
238 | for i in range(start, stop): | |
232 | if output: |
|
239 | if output: | |
233 | hist[i-offset] = (input_hist[i], output_hist.get(i-offset)) |
|
240 | hist[i-offset] = (input_hist[i], output_hist.get(i-offset)) | |
234 | else: |
|
241 | else: | |
235 | hist[i-offset] = input_hist[i] |
|
242 | hist[i-offset] = input_hist[i] | |
236 | return hist |
|
243 | return hist | |
237 |
|
244 | |||
238 | def store_inputs(self, source, source_raw=None): |
|
245 | def store_inputs(self, source, source_raw=None): | |
239 | """Store source and raw input in history and create input cache |
|
246 | """Store source and raw input in history and create input cache | |
240 | variables _i*. |
|
247 | variables _i*. | |
241 |
|
248 | |||
242 | Parameters |
|
249 | Parameters | |
243 | ---------- |
|
250 | ---------- | |
244 | source : str |
|
251 | source : str | |
245 | Python input. |
|
252 | Python input. | |
246 |
|
253 | |||
247 | source_raw : str, optional |
|
254 | source_raw : str, optional | |
248 | If given, this is the raw input without any IPython transformations |
|
255 | If given, this is the raw input without any IPython transformations | |
249 | applied to it. If not given, ``source`` is used. |
|
256 | applied to it. If not given, ``source`` is used. | |
250 | """ |
|
257 | """ | |
251 | if source_raw is None: |
|
258 | if source_raw is None: | |
252 | source_raw = source |
|
259 | source_raw = source | |
253 |
|
260 | |||
254 | # do not store exit/quit commands |
|
261 | # do not store exit/quit commands | |
255 | if source_raw.strip() in self._exit_commands: |
|
262 | if source_raw.strip() in self._exit_commands: | |
256 | return |
|
263 | return | |
257 |
|
264 | |||
258 | self.input_hist_parsed.append(source.rstrip()) |
|
265 | self.input_hist_parsed.append(source.rstrip()) | |
259 | self.input_hist_raw.append(source_raw.rstrip()) |
|
266 | self.input_hist_raw.append(source_raw.rstrip()) | |
260 | self.shadow_hist.add(source) |
|
267 | self.shadow_hist.add(source) | |
261 |
|
268 | |||
262 | # update the auto _i variables |
|
269 | # update the auto _i variables | |
263 | self._iii = self._ii |
|
270 | self._iii = self._ii | |
264 | self._ii = self._i |
|
271 | self._ii = self._i | |
265 | self._i = self._i00 |
|
272 | self._i = self._i00 | |
266 | self._i00 = source_raw |
|
273 | self._i00 = source_raw | |
267 |
|
274 | |||
268 | # hackish access to user namespace to create _i1,_i2... dynamically |
|
275 | # hackish access to user namespace to create _i1,_i2... dynamically | |
269 | new_i = '_i%s' % self.shell.execution_count |
|
276 | new_i = '_i%s' % self.shell.execution_count | |
270 | to_main = {'_i': self._i, |
|
277 | to_main = {'_i': self._i, | |
271 | '_ii': self._ii, |
|
278 | '_ii': self._ii, | |
272 | '_iii': self._iii, |
|
279 | '_iii': self._iii, | |
273 | new_i : self._i00 } |
|
280 | new_i : self._i00 } | |
274 | self.shell.user_ns.update(to_main) |
|
281 | self.shell.user_ns.update(to_main) | |
275 |
|
282 | |||
276 | def sync_inputs(self): |
|
283 | def sync_inputs(self): | |
277 | """Ensure raw and translated histories have same length.""" |
|
284 | """Ensure raw and translated histories have same length.""" | |
278 | if len(self.input_hist_parsed) != len (self.input_hist_raw): |
|
285 | if len(self.input_hist_parsed) != len (self.input_hist_raw): | |
279 | self.input_hist_raw[:] = self.input_hist_parsed |
|
286 | self.input_hist_raw[:] = self.input_hist_parsed | |
280 |
|
287 | |||
281 | def reset(self): |
|
288 | def reset(self): | |
282 | """Clear all histories managed by this object.""" |
|
289 | """Clear all histories managed by this object.""" | |
283 | self.input_hist_parsed[:] = [] |
|
290 | self.input_hist_parsed[:] = [] | |
284 | self.input_hist_raw[:] = [] |
|
291 | self.input_hist_raw[:] = [] | |
285 | self.output_hist.clear() |
|
292 | self.output_hist.clear() | |
286 | # The directory history can't be completely empty |
|
293 | # The directory history can't be completely empty | |
287 | self.dir_hist[:] = [os.getcwd()] |
|
294 | self.dir_hist[:] = [os.getcwd()] | |
288 | # Reset session offset to -1, so next command counts as #1 |
|
295 | # Reset session offset to -1, so next command counts as #1 | |
289 | self.session_offset = -1 |
|
296 | self.session_offset = -1 | |
290 |
|
297 | |||
291 | class HistorySaveThread(threading.Thread): |
|
298 | class HistorySaveThread(threading.Thread): | |
292 | """This thread makes IPython save history periodically. |
|
299 | """This thread makes IPython save history periodically. | |
293 |
|
300 | |||
294 | Without this class, IPython would only save the history on a clean exit. |
|
301 | Without this class, IPython would only save the history on a clean exit. | |
295 | This saves the history periodically (the current default is once per |
|
302 | This saves the history periodically (the current default is once per | |
296 | minute), so that it is not lost in the event of a crash. |
|
303 | minute), so that it is not lost in the event of a crash. | |
297 |
|
304 | |||
298 | The implementation sets an event to indicate that history should be saved. |
|
305 | The implementation sets an event to indicate that history should be saved. | |
299 | The actual save is carried out after executing a user command, to avoid |
|
306 | The actual save is carried out after executing a user command, to avoid | |
300 | thread issues. |
|
307 | thread issues. | |
301 | """ |
|
308 | """ | |
302 | daemon = True |
|
309 | daemon = True | |
303 |
|
310 | |||
304 | def __init__(self, autosave_flag, time_interval=60): |
|
311 | def __init__(self, autosave_flag, time_interval=60): | |
305 | threading.Thread.__init__(self) |
|
312 | threading.Thread.__init__(self) | |
306 | self.time_interval = time_interval |
|
313 | self.time_interval = time_interval | |
307 | self.autosave_flag = autosave_flag |
|
314 | self.autosave_flag = autosave_flag | |
308 | self.exit_now = threading.Event() |
|
315 | self.exit_now = threading.Event() | |
309 | # Ensure the thread is stopped tidily when exiting normally |
|
316 | # Ensure the thread is stopped tidily when exiting normally | |
310 | atexit.register(self.stop) |
|
317 | atexit.register(self.stop) | |
311 |
|
318 | |||
312 | def run(self): |
|
319 | def run(self): | |
313 | while True: |
|
320 | while True: | |
314 | self.exit_now.wait(self.time_interval) |
|
321 | self.exit_now.wait(self.time_interval) | |
315 | if self.exit_now.is_set(): |
|
322 | if self.exit_now.is_set(): | |
316 | break |
|
323 | break | |
317 | self.autosave_flag.set() |
|
324 | self.autosave_flag.set() | |
318 |
|
325 | |||
319 | def stop(self): |
|
326 | def stop(self): | |
320 | """Safely and quickly stop the autosave timer thread.""" |
|
327 | """Safely and quickly stop the autosave timer thread.""" | |
321 | self.exit_now.set() |
|
328 | self.exit_now.set() | |
322 | self.join() |
|
329 | self.join() | |
323 |
|
330 | |||
324 | @testdec.skip_doctest |
|
331 | @testdec.skip_doctest | |
325 | def magic_history(self, parameter_s = ''): |
|
332 | def magic_history(self, parameter_s = ''): | |
326 | """Print input history (_i<n> variables), with most recent last. |
|
333 | """Print input history (_i<n> variables), with most recent last. | |
327 |
|
334 | |||
328 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
335 | %history -> print at most 40 inputs (some may be multi-line)\\ | |
329 | %history n -> print at most n inputs\\ |
|
336 | %history n -> print at most n inputs\\ | |
330 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
337 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
331 |
|
338 | |||
332 | By default, input history is printed without line numbers so it can be |
|
339 | By default, input history is printed without line numbers so it can be | |
333 | directly pasted into an editor. |
|
340 | directly pasted into an editor. | |
334 |
|
341 | |||
335 | With -n, each input's number <n> is shown, and is accessible as the |
|
342 | With -n, each input's number <n> is shown, and is accessible as the | |
336 | automatically generated variable _i<n> as well as In[<n>]. Multi-line |
|
343 | automatically generated variable _i<n> as well as In[<n>]. Multi-line | |
337 | statements are printed starting at a new line for easy copy/paste. |
|
344 | statements are printed starting at a new line for easy copy/paste. | |
338 |
|
345 | |||
339 | Options: |
|
346 | Options: | |
340 |
|
347 | |||
341 | -n: print line numbers for each input. |
|
348 | -n: print line numbers for each input. | |
342 | This feature is only available if numbered prompts are in use. |
|
349 | This feature is only available if numbered prompts are in use. | |
343 |
|
350 | |||
344 | -o: also print outputs for each input. |
|
351 | -o: also print outputs for each input. | |
345 |
|
352 | |||
346 | -p: print classic '>>>' python prompts before each input. This is useful |
|
353 | -p: print classic '>>>' python prompts before each input. This is useful | |
347 | for making documentation, and in conjunction with -o, for producing |
|
354 | for making documentation, and in conjunction with -o, for producing | |
348 | doctest-ready output. |
|
355 | doctest-ready output. | |
349 |
|
356 | |||
350 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. |
|
357 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. | |
351 |
|
358 | |||
352 | -t: print the 'translated' history, as IPython understands it. IPython |
|
359 | -t: print the 'translated' history, as IPython understands it. IPython | |
353 | filters your input and converts it all into valid Python source before |
|
360 | filters your input and converts it all into valid Python source before | |
354 | executing it (things like magics or aliases are turned into function |
|
361 | executing it (things like magics or aliases are turned into function | |
355 | calls, for example). With this option, you'll see the native history |
|
362 | calls, for example). With this option, you'll see the native history | |
356 | instead of the user-entered version: '%cd /' will be seen as |
|
363 | instead of the user-entered version: '%cd /' will be seen as | |
357 | 'get_ipython().magic("%cd /")' instead of '%cd /'. |
|
364 | 'get_ipython().magic("%cd /")' instead of '%cd /'. | |
358 |
|
365 | |||
359 | -g: treat the arg as a pattern to grep for in (full) history. |
|
366 | -g: treat the arg as a pattern to grep for in (full) history. | |
360 | This includes the "shadow history" (almost all commands ever written). |
|
367 | This includes the "shadow history" (almost all commands ever written). | |
361 | Use '%hist -g' to show full shadow history (may be very long). |
|
368 | Use '%hist -g' to show full shadow history (may be very long). | |
362 | In shadow history, every index nuwber starts with 0. |
|
369 | In shadow history, every index nuwber starts with 0. | |
363 |
|
370 | |||
364 | -f FILENAME: instead of printing the output to the screen, redirect it to |
|
371 | -f FILENAME: instead of printing the output to the screen, redirect it to | |
365 | the given file. The file is always overwritten, though IPython asks for |
|
372 | the given file. The file is always overwritten, though IPython asks for | |
366 | confirmation first if it already exists. |
|
373 | confirmation first if it already exists. | |
367 |
|
374 | |||
368 | Examples |
|
375 | Examples | |
369 | -------- |
|
376 | -------- | |
370 | :: |
|
377 | :: | |
371 |
|
378 | |||
372 | In [6]: %hist -n 4 6 |
|
379 | In [6]: %hist -n 4 6 | |
373 | 4:a = 12 |
|
380 | 4:a = 12 | |
374 | 5:print a**2 |
|
381 | 5:print a**2 | |
375 |
|
382 | |||
376 | """ |
|
383 | """ | |
377 |
|
384 | |||
378 | if not self.shell.displayhook.do_full_cache: |
|
385 | if not self.shell.displayhook.do_full_cache: | |
379 | print('This feature is only available if numbered prompts are in use.') |
|
386 | print('This feature is only available if numbered prompts are in use.') | |
380 | return |
|
387 | return | |
381 | opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list') |
|
388 | opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list') | |
382 |
|
389 | |||
383 | # For brevity |
|
390 | # For brevity | |
384 | history_manager = self.shell.history_manager |
|
391 | history_manager = self.shell.history_manager | |
385 |
|
392 | |||
386 | # Check if output to specific file was requested. |
|
393 | # Check if output to specific file was requested. | |
387 | try: |
|
394 | try: | |
388 | outfname = opts['f'] |
|
395 | outfname = opts['f'] | |
389 | except KeyError: |
|
396 | except KeyError: | |
390 | outfile = IPython.utils.io.Term.cout # default |
|
397 | outfile = IPython.utils.io.Term.cout # default | |
391 | # We don't want to close stdout at the end! |
|
398 | # We don't want to close stdout at the end! | |
392 | close_at_end = False |
|
399 | close_at_end = False | |
393 | else: |
|
400 | else: | |
394 | if os.path.exists(outfname): |
|
401 | if os.path.exists(outfname): | |
395 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): |
|
402 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): | |
396 | print('Aborting.') |
|
403 | print('Aborting.') | |
397 | return |
|
404 | return | |
398 |
|
405 | |||
399 | outfile = open(outfname,'w') |
|
406 | outfile = open(outfname,'w') | |
400 | close_at_end = True |
|
407 | close_at_end = True | |
401 |
|
408 | |||
402 | print_nums = 'n' in opts |
|
409 | print_nums = 'n' in opts | |
403 | print_outputs = 'o' in opts |
|
410 | print_outputs = 'o' in opts | |
404 | pyprompts = 'p' in opts |
|
411 | pyprompts = 'p' in opts | |
405 | # Raw history is the default |
|
412 | # Raw history is the default | |
406 | raw = not('t' in opts) |
|
413 | raw = not('t' in opts) | |
407 |
|
414 | |||
408 | default_length = 40 |
|
415 | default_length = 40 | |
409 | pattern = None |
|
416 | pattern = None | |
410 | if 'g' in opts: |
|
417 | if 'g' in opts: | |
411 | index = None |
|
418 | index = None | |
412 | parts = parameter_s.split(None, 1) |
|
419 | parts = parameter_s.split(None, 1) | |
413 | if len(parts) == 1: |
|
420 | if len(parts) == 1: | |
414 | parts += '*' |
|
421 | parts += '*' | |
415 | head, pattern = parts |
|
422 | head, pattern = parts | |
416 | pattern = "*" + pattern + "*" |
|
423 | pattern = "*" + pattern + "*" | |
417 | elif len(args) == 0: |
|
424 | elif len(args) == 0: | |
418 | index = None |
|
425 | index = None | |
419 | elif len(args) == 1: |
|
426 | elif len(args) == 1: | |
420 | index = int(args[0]) |
|
427 | index = int(args[0]) | |
421 | elif len(args) == 2: |
|
428 | elif len(args) == 2: | |
422 | index = map(int, args) |
|
429 | index = map(int, args) | |
423 | else: |
|
430 | else: | |
424 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
431 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
425 | print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout) |
|
432 | print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout) | |
426 | return |
|
433 | return | |
427 |
|
434 | |||
428 | hist = history_manager.get_history(index, raw, print_outputs) |
|
435 | hist = history_manager.get_history(index, raw, print_outputs) | |
429 |
|
436 | |||
430 | width = len(str(max(hist.iterkeys()))) |
|
437 | width = len(str(max(hist.iterkeys()))) | |
431 | line_sep = ['','\n'] |
|
438 | line_sep = ['','\n'] | |
432 |
|
439 | |||
433 | found = False |
|
440 | found = False | |
434 | if pattern is not None: |
|
441 | if pattern is not None: | |
435 | sh = history_manager.shadow_hist.all() |
|
442 | sh = history_manager.shadow_hist.all() | |
436 | for idx, s in sh: |
|
443 | for idx, s in sh: | |
437 | if fnmatch.fnmatch(s, pattern): |
|
444 | if fnmatch.fnmatch(s, pattern): | |
438 | print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile) |
|
445 | print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile) | |
439 | found = True |
|
446 | found = True | |
440 |
|
447 | |||
441 | if found: |
|
448 | if found: | |
442 | print("===", file=outfile) |
|
449 | print("===", file=outfile) | |
443 | print("shadow history ends, fetch by %rep <number> (must start with 0)", |
|
450 | print("shadow history ends, fetch by %rep <number> (must start with 0)", | |
444 | file=outfile) |
|
451 | file=outfile) | |
445 | print("=== start of normal history ===", file=outfile) |
|
452 | print("=== start of normal history ===", file=outfile) | |
446 |
|
453 | |||
447 | for in_num, inline in sorted(hist.iteritems()): |
|
454 | for in_num, inline in sorted(hist.iteritems()): | |
448 | # Print user history with tabs expanded to 4 spaces. The GUI clients |
|
455 | # Print user history with tabs expanded to 4 spaces. The GUI clients | |
449 | # use hard tabs for easier usability in auto-indented code, but we want |
|
456 | # use hard tabs for easier usability in auto-indented code, but we want | |
450 | # to produce PEP-8 compliant history for safe pasting into an editor. |
|
457 | # to produce PEP-8 compliant history for safe pasting into an editor. | |
451 | if print_outputs: |
|
458 | if print_outputs: | |
452 | inline, output = inline |
|
459 | inline, output = inline | |
453 | inline = inline.expandtabs(4).rstrip() |
|
460 | inline = inline.expandtabs(4).rstrip() | |
454 |
|
461 | |||
455 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): |
|
462 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): | |
456 | continue |
|
463 | continue | |
457 |
|
464 | |||
458 | multiline = "\n" in inline |
|
465 | multiline = "\n" in inline | |
459 | if print_nums: |
|
466 | if print_nums: | |
460 | print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]), |
|
467 | print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]), | |
461 | file=outfile, end='') |
|
468 | file=outfile, end='') | |
462 | if pyprompts: |
|
469 | if pyprompts: | |
463 | print(">>> ", end="", file=outfile) |
|
470 | print(">>> ", end="", file=outfile) | |
464 | if multiline: |
|
471 | if multiline: | |
465 | inline = "\n... ".join(inline.splitlines()) + "\n..." |
|
472 | inline = "\n... ".join(inline.splitlines()) + "\n..." | |
466 | print(inline, file=outfile) |
|
473 | print(inline, file=outfile) | |
467 | if print_outputs and output: |
|
474 | if print_outputs and output: | |
468 | print(repr(output), file=outfile) |
|
475 | print(repr(output), file=outfile) | |
469 |
|
476 | |||
470 | if close_at_end: |
|
477 | if close_at_end: | |
471 | outfile.close() |
|
478 | outfile.close() | |
472 |
|
479 | |||
473 | # %hist is an alternative name |
|
480 | # %hist is an alternative name | |
474 | magic_hist = magic_history |
|
481 | magic_hist = magic_history | |
475 |
|
482 | |||
476 |
|
483 | |||
477 | def rep_f(self, arg): |
|
484 | def rep_f(self, arg): | |
478 | r""" Repeat a command, or get command to input line for editing |
|
485 | r""" Repeat a command, or get command to input line for editing | |
479 |
|
486 | |||
480 | - %rep (no arguments): |
|
487 | - %rep (no arguments): | |
481 |
|
488 | |||
482 | Place a string version of last computation result (stored in the special '_' |
|
489 | Place a string version of last computation result (stored in the special '_' | |
483 | variable) to the next input prompt. Allows you to create elaborate command |
|
490 | variable) to the next input prompt. Allows you to create elaborate command | |
484 | lines without using copy-paste:: |
|
491 | lines without using copy-paste:: | |
485 |
|
492 | |||
486 | $ l = ["hei", "vaan"] |
|
493 | $ l = ["hei", "vaan"] | |
487 | $ "".join(l) |
|
494 | $ "".join(l) | |
488 | ==> heivaan |
|
495 | ==> heivaan | |
489 | $ %rep |
|
496 | $ %rep | |
490 | $ heivaan_ <== cursor blinking |
|
497 | $ heivaan_ <== cursor blinking | |
491 |
|
498 | |||
492 | %rep 45 |
|
499 | %rep 45 | |
493 |
|
500 | |||
494 | Place history line 45 to next input prompt. Use %hist to find out the |
|
501 | Place history line 45 to next input prompt. Use %hist to find out the | |
495 | number. |
|
502 | number. | |
496 |
|
503 | |||
497 | %rep 1-4 6-7 3 |
|
504 | %rep 1-4 6-7 3 | |
498 |
|
505 | |||
499 | Repeat the specified lines immediately. Input slice syntax is the same as |
|
506 | Repeat the specified lines immediately. Input slice syntax is the same as | |
500 | in %macro and %save. |
|
507 | in %macro and %save. | |
501 |
|
508 | |||
502 | %rep foo |
|
509 | %rep foo | |
503 |
|
510 | |||
504 | Place the most recent line that has the substring "foo" to next input. |
|
511 | Place the most recent line that has the substring "foo" to next input. | |
505 | (e.g. 'svn ci -m foobar'). |
|
512 | (e.g. 'svn ci -m foobar'). | |
506 | """ |
|
513 | """ | |
507 |
|
514 | |||
508 | opts,args = self.parse_options(arg,'',mode='list') |
|
515 | opts,args = self.parse_options(arg,'',mode='list') | |
509 | if not args: |
|
516 | if not args: | |
510 | self.set_next_input(str(self.shell.user_ns["_"])) |
|
517 | self.set_next_input(str(self.shell.user_ns["_"])) | |
511 | return |
|
518 | return | |
512 |
|
519 | |||
513 | if len(args) == 1 and not '-' in args[0]: |
|
520 | if len(args) == 1 and not '-' in args[0]: | |
514 | arg = args[0] |
|
521 | arg = args[0] | |
515 | if len(arg) > 1 and arg.startswith('0'): |
|
522 | if len(arg) > 1 and arg.startswith('0'): | |
516 | # get from shadow hist |
|
523 | # get from shadow hist | |
517 | num = int(arg[1:]) |
|
524 | num = int(arg[1:]) | |
518 | line = self.shell.shadowhist.get(num) |
|
525 | line = self.shell.shadowhist.get(num) | |
519 | self.set_next_input(str(line)) |
|
526 | self.set_next_input(str(line)) | |
520 | return |
|
527 | return | |
521 | try: |
|
528 | try: | |
522 | num = int(args[0]) |
|
529 | num = int(args[0]) | |
523 | self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip()) |
|
530 | self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip()) | |
524 | return |
|
531 | return | |
525 | except ValueError: |
|
532 | except ValueError: | |
526 | pass |
|
533 | pass | |
527 |
|
534 | |||
528 | for h in reversed(self.shell.input_hist_raw): |
|
535 | for h in reversed(self.shell.input_hist_raw): | |
529 | if 'rep' in h: |
|
536 | if 'rep' in h: | |
530 | continue |
|
537 | continue | |
531 | if fnmatch.fnmatch(h,'*' + arg + '*'): |
|
538 | if fnmatch.fnmatch(h,'*' + arg + '*'): | |
532 | self.set_next_input(str(h).rstrip()) |
|
539 | self.set_next_input(str(h).rstrip()) | |
533 | return |
|
540 | return | |
534 |
|
541 | |||
535 | try: |
|
542 | try: | |
536 | lines = self.extract_input_slices(args, True) |
|
543 | lines = self.extract_input_slices(args, True) | |
537 | print("lines", lines) |
|
544 | print("lines", lines) | |
538 | self.run_cell(lines) |
|
545 | self.run_cell(lines) | |
539 | except ValueError: |
|
546 | except ValueError: | |
540 | print("Not found in recent history:", args) |
|
547 | print("Not found in recent history:", args) | |
541 |
|
548 | |||
542 |
|
549 | |||
543 | _sentinel = object() |
|
550 | _sentinel = object() | |
544 |
|
551 | |||
545 | class ShadowHist(object): |
|
552 | class ShadowHist(object): | |
546 | def __init__(self, db, shell): |
|
553 | def __init__(self, db, shell): | |
547 | # cmd => idx mapping |
|
554 | # cmd => idx mapping | |
548 | self.curidx = 0 |
|
555 | self.curidx = 0 | |
549 | self.db = db |
|
556 | self.db = db | |
550 | self.disabled = False |
|
557 | self.disabled = False | |
551 | self.shell = shell |
|
558 | self.shell = shell | |
552 |
|
559 | |||
553 | def inc_idx(self): |
|
560 | def inc_idx(self): | |
554 | idx = self.db.get('shadowhist_idx', 1) |
|
561 | idx = self.db.get('shadowhist_idx', 1) | |
555 | self.db['shadowhist_idx'] = idx + 1 |
|
562 | self.db['shadowhist_idx'] = idx + 1 | |
556 | return idx |
|
563 | return idx | |
557 |
|
564 | |||
558 | def add(self, ent): |
|
565 | def add(self, ent): | |
559 | if self.disabled: |
|
566 | if self.disabled: | |
560 | return |
|
567 | return | |
561 | try: |
|
568 | try: | |
562 | old = self.db.hget('shadowhist', ent, _sentinel) |
|
569 | old = self.db.hget('shadowhist', ent, _sentinel) | |
563 | if old is not _sentinel: |
|
570 | if old is not _sentinel: | |
564 | return |
|
571 | return | |
565 | newidx = self.inc_idx() |
|
572 | newidx = self.inc_idx() | |
566 | #print("new", newidx) # dbg |
|
573 | #print("new", newidx) # dbg | |
567 | self.db.hset('shadowhist',ent, newidx) |
|
574 | self.db.hset('shadowhist',ent, newidx) | |
568 | except: |
|
575 | except: | |
569 | self.shell.showtraceback() |
|
576 | self.shell.showtraceback() | |
570 | print("WARNING: disabling shadow history") |
|
577 | print("WARNING: disabling shadow history") | |
571 | self.disabled = True |
|
578 | self.disabled = True | |
572 |
|
579 | |||
573 | def all(self): |
|
580 | def all(self): | |
574 | d = self.db.hdict('shadowhist') |
|
581 | d = self.db.hdict('shadowhist') | |
575 | items = [(i,s) for (s,i) in d.iteritems()] |
|
582 | items = [(i,s) for (s,i) in d.iteritems()] | |
576 | items.sort() |
|
583 | items.sort() | |
577 | return items |
|
584 | return items | |
578 |
|
585 | |||
579 | def get(self, idx): |
|
586 | def get(self, idx): | |
580 | all = self.all() |
|
587 | all = self.all() | |
581 |
|
588 | |||
582 | for k, v in all: |
|
589 | for k, v in all: | |
583 | if k == idx: |
|
590 | if k == idx: | |
584 | return v |
|
591 | return v | |
585 |
|
592 | |||
586 |
|
593 | |||
587 | def init_ipython(ip): |
|
594 | def init_ipython(ip): | |
588 | ip.define_magic("rep",rep_f) |
|
595 | ip.define_magic("rep",rep_f) | |
589 | ip.define_magic("hist",magic_hist) |
|
596 | ip.define_magic("hist",magic_hist) | |
590 | ip.define_magic("history",magic_history) |
|
597 | ip.define_magic("history",magic_history) | |
591 |
|
598 | |||
592 | # XXX - ipy_completers are in quarantine, need to be updated to new apis |
|
599 | # XXX - ipy_completers are in quarantine, need to be updated to new apis | |
593 | #import ipy_completers |
|
600 | #import ipy_completers | |
594 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
|
601 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
@@ -1,2555 +1,2555 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Main IPython class.""" |
|
2 | """Main IPython class.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
7 | # Copyright (C) 2008-2011 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | from __future__ import with_statement |
|
17 | from __future__ import with_statement | |
18 | from __future__ import absolute_import |
|
18 | from __future__ import absolute_import | |
19 |
|
19 | |||
20 | import __builtin__ |
|
20 | import __builtin__ | |
21 | import __future__ |
|
21 | import __future__ | |
22 | import abc |
|
22 | import abc | |
23 | import atexit |
|
23 | import atexit | |
24 | import codeop |
|
24 | import codeop | |
25 | import os |
|
25 | import os | |
26 | import re |
|
26 | import re | |
27 | import sys |
|
27 | import sys | |
28 | import tempfile |
|
28 | import tempfile | |
29 | import types |
|
29 | import types | |
30 | from contextlib import nested |
|
30 | from contextlib import nested | |
31 |
|
31 | |||
32 | from IPython.config.configurable import Configurable |
|
32 | from IPython.config.configurable import Configurable | |
33 | from IPython.core import debugger, oinspect |
|
33 | from IPython.core import debugger, oinspect | |
34 | from IPython.core import history as ipcorehist |
|
34 | from IPython.core import history as ipcorehist | |
35 | from IPython.core import page |
|
35 | from IPython.core import page | |
36 | from IPython.core import prefilter |
|
36 | from IPython.core import prefilter | |
37 | from IPython.core import shadowns |
|
37 | from IPython.core import shadowns | |
38 | from IPython.core import ultratb |
|
38 | from IPython.core import ultratb | |
39 | from IPython.core.alias import AliasManager |
|
39 | from IPython.core.alias import AliasManager | |
40 | from IPython.core.builtin_trap import BuiltinTrap |
|
40 | from IPython.core.builtin_trap import BuiltinTrap | |
41 | from IPython.core.compilerop import CachingCompiler |
|
41 | from IPython.core.compilerop import CachingCompiler | |
42 | from IPython.core.display_trap import DisplayTrap |
|
42 | from IPython.core.display_trap import DisplayTrap | |
43 | from IPython.core.displayhook import DisplayHook |
|
43 | from IPython.core.displayhook import DisplayHook | |
44 | from IPython.core.displaypub import DisplayPublisher |
|
44 | from IPython.core.displaypub import DisplayPublisher | |
45 | from IPython.core.error import TryNext, UsageError |
|
45 | from IPython.core.error import TryNext, UsageError | |
46 | from IPython.core.extensions import ExtensionManager |
|
46 | from IPython.core.extensions import ExtensionManager | |
47 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
47 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
48 | from IPython.core.formatters import DisplayFormatter |
|
48 | from IPython.core.formatters import DisplayFormatter | |
49 | from IPython.core.history import HistoryManager |
|
49 | from IPython.core.history import HistoryManager | |
50 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
50 | from IPython.core.inputsplitter import IPythonInputSplitter | |
51 | from IPython.core.logger import Logger |
|
51 | from IPython.core.logger import Logger | |
52 | from IPython.core.magic import Magic |
|
52 | from IPython.core.magic import Magic | |
53 | from IPython.core.payload import PayloadManager |
|
53 | from IPython.core.payload import PayloadManager | |
54 | from IPython.core.plugin import PluginManager |
|
54 | from IPython.core.plugin import PluginManager | |
55 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
55 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
56 | from IPython.external.Itpl import ItplNS |
|
56 | from IPython.external.Itpl import ItplNS | |
57 | from IPython.utils import PyColorize |
|
57 | from IPython.utils import PyColorize | |
58 | from IPython.utils import io |
|
58 | from IPython.utils import io | |
59 | from IPython.utils import pickleshare |
|
59 | from IPython.utils import pickleshare | |
60 | from IPython.utils.doctestreload import doctest_reload |
|
60 | from IPython.utils.doctestreload import doctest_reload | |
61 | from IPython.utils.io import ask_yes_no, rprint |
|
61 | from IPython.utils.io import ask_yes_no, rprint | |
62 | from IPython.utils.ipstruct import Struct |
|
62 | from IPython.utils.ipstruct import Struct | |
63 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
63 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
64 | from IPython.utils.process import system, getoutput |
|
64 | from IPython.utils.process import system, getoutput | |
65 | from IPython.utils.strdispatch import StrDispatch |
|
65 | from IPython.utils.strdispatch import StrDispatch | |
66 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
66 | from IPython.utils.syspathcontext import prepended_to_syspath | |
67 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList |
|
67 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList | |
68 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
68 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |
69 | List, Unicode, Instance, Type) |
|
69 | List, Unicode, Instance, Type) | |
70 | from IPython.utils.warn import warn, error, fatal |
|
70 | from IPython.utils.warn import warn, error, fatal | |
71 | import IPython.core.hooks |
|
71 | import IPython.core.hooks | |
72 |
|
72 | |||
73 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
74 | # Globals |
|
74 | # Globals | |
75 | #----------------------------------------------------------------------------- |
|
75 | #----------------------------------------------------------------------------- | |
76 |
|
76 | |||
77 | # compiled regexps for autoindent management |
|
77 | # compiled regexps for autoindent management | |
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
79 |
|
79 | |||
80 | #----------------------------------------------------------------------------- |
|
80 | #----------------------------------------------------------------------------- | |
81 | # Utilities |
|
81 | # Utilities | |
82 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
83 |
|
83 | |||
84 | # store the builtin raw_input globally, and use this always, in case user code |
|
84 | # store the builtin raw_input globally, and use this always, in case user code | |
85 | # overwrites it (like wx.py.PyShell does) |
|
85 | # overwrites it (like wx.py.PyShell does) | |
86 | raw_input_original = raw_input |
|
86 | raw_input_original = raw_input | |
87 |
|
87 | |||
88 | def softspace(file, newvalue): |
|
88 | def softspace(file, newvalue): | |
89 | """Copied from code.py, to remove the dependency""" |
|
89 | """Copied from code.py, to remove the dependency""" | |
90 |
|
90 | |||
91 | oldvalue = 0 |
|
91 | oldvalue = 0 | |
92 | try: |
|
92 | try: | |
93 | oldvalue = file.softspace |
|
93 | oldvalue = file.softspace | |
94 | except AttributeError: |
|
94 | except AttributeError: | |
95 | pass |
|
95 | pass | |
96 | try: |
|
96 | try: | |
97 | file.softspace = newvalue |
|
97 | file.softspace = newvalue | |
98 | except (AttributeError, TypeError): |
|
98 | except (AttributeError, TypeError): | |
99 | # "attribute-less object" or "read-only attributes" |
|
99 | # "attribute-less object" or "read-only attributes" | |
100 | pass |
|
100 | pass | |
101 | return oldvalue |
|
101 | return oldvalue | |
102 |
|
102 | |||
103 |
|
103 | |||
104 | def no_op(*a, **kw): pass |
|
104 | def no_op(*a, **kw): pass | |
105 |
|
105 | |||
106 | class SpaceInInput(Exception): pass |
|
106 | class SpaceInInput(Exception): pass | |
107 |
|
107 | |||
108 | class Bunch: pass |
|
108 | class Bunch: pass | |
109 |
|
109 | |||
110 |
|
110 | |||
111 | def get_default_colors(): |
|
111 | def get_default_colors(): | |
112 | if sys.platform=='darwin': |
|
112 | if sys.platform=='darwin': | |
113 | return "LightBG" |
|
113 | return "LightBG" | |
114 | elif os.name=='nt': |
|
114 | elif os.name=='nt': | |
115 | return 'Linux' |
|
115 | return 'Linux' | |
116 | else: |
|
116 | else: | |
117 | return 'Linux' |
|
117 | return 'Linux' | |
118 |
|
118 | |||
119 |
|
119 | |||
120 | class SeparateStr(Str): |
|
120 | class SeparateStr(Str): | |
121 | """A Str subclass to validate separate_in, separate_out, etc. |
|
121 | """A Str subclass to validate separate_in, separate_out, etc. | |
122 |
|
122 | |||
123 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
123 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
124 | """ |
|
124 | """ | |
125 |
|
125 | |||
126 | def validate(self, obj, value): |
|
126 | def validate(self, obj, value): | |
127 | if value == '0': value = '' |
|
127 | if value == '0': value = '' | |
128 | value = value.replace('\\n','\n') |
|
128 | value = value.replace('\\n','\n') | |
129 | return super(SeparateStr, self).validate(obj, value) |
|
129 | return super(SeparateStr, self).validate(obj, value) | |
130 |
|
130 | |||
131 | class MultipleInstanceError(Exception): |
|
131 | class MultipleInstanceError(Exception): | |
132 | pass |
|
132 | pass | |
133 |
|
133 | |||
134 |
|
134 | |||
135 | #----------------------------------------------------------------------------- |
|
135 | #----------------------------------------------------------------------------- | |
136 | # Main IPython class |
|
136 | # Main IPython class | |
137 | #----------------------------------------------------------------------------- |
|
137 | #----------------------------------------------------------------------------- | |
138 |
|
138 | |||
139 | class InteractiveShell(Configurable, Magic): |
|
139 | class InteractiveShell(Configurable, Magic): | |
140 | """An enhanced, interactive shell for Python.""" |
|
140 | """An enhanced, interactive shell for Python.""" | |
141 |
|
141 | |||
142 | _instance = None |
|
142 | _instance = None | |
143 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
143 | autocall = Enum((0,1,2), default_value=1, config=True) | |
144 | # TODO: remove all autoindent logic and put into frontends. |
|
144 | # TODO: remove all autoindent logic and put into frontends. | |
145 | # We can't do this yet because even runlines uses the autoindent. |
|
145 | # We can't do this yet because even runlines uses the autoindent. | |
146 | autoindent = CBool(True, config=True) |
|
146 | autoindent = CBool(True, config=True) | |
147 | automagic = CBool(True, config=True) |
|
147 | automagic = CBool(True, config=True) | |
148 | cache_size = Int(1000, config=True) |
|
148 | cache_size = Int(1000, config=True) | |
149 | color_info = CBool(True, config=True) |
|
149 | color_info = CBool(True, config=True) | |
150 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
150 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
151 | default_value=get_default_colors(), config=True) |
|
151 | default_value=get_default_colors(), config=True) | |
152 | debug = CBool(False, config=True) |
|
152 | debug = CBool(False, config=True) | |
153 | deep_reload = CBool(False, config=True) |
|
153 | deep_reload = CBool(False, config=True) | |
154 | display_formatter = Instance(DisplayFormatter) |
|
154 | display_formatter = Instance(DisplayFormatter) | |
155 | displayhook_class = Type(DisplayHook) |
|
155 | displayhook_class = Type(DisplayHook) | |
156 | display_pub_class = Type(DisplayPublisher) |
|
156 | display_pub_class = Type(DisplayPublisher) | |
157 |
|
157 | |||
158 | exit_now = CBool(False) |
|
158 | exit_now = CBool(False) | |
159 | # Monotonically increasing execution counter |
|
159 | # Monotonically increasing execution counter | |
160 | execution_count = Int(1) |
|
160 | execution_count = Int(1) | |
161 | filename = Str("<ipython console>") |
|
161 | filename = Str("<ipython console>") | |
162 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
162 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
163 |
|
163 | |||
164 | # Input splitter, to split entire cells of input into either individual |
|
164 | # Input splitter, to split entire cells of input into either individual | |
165 | # interactive statements or whole blocks. |
|
165 | # interactive statements or whole blocks. | |
166 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
166 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
167 | (), {}) |
|
167 | (), {}) | |
168 | logstart = CBool(False, config=True) |
|
168 | logstart = CBool(False, config=True) | |
169 | logfile = Str('', config=True) |
|
169 | logfile = Str('', config=True) | |
170 | logappend = Str('', config=True) |
|
170 | logappend = Str('', config=True) | |
171 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
171 | object_info_string_level = Enum((0,1,2), default_value=0, | |
172 | config=True) |
|
172 | config=True) | |
173 | pdb = CBool(False, config=True) |
|
173 | pdb = CBool(False, config=True) | |
174 |
|
174 | |||
175 | profile = Str('', config=True) |
|
175 | profile = Str('', config=True) | |
176 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
176 | prompt_in1 = Str('In [\\#]: ', config=True) | |
177 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
177 | prompt_in2 = Str(' .\\D.: ', config=True) | |
178 | prompt_out = Str('Out[\\#]: ', config=True) |
|
178 | prompt_out = Str('Out[\\#]: ', config=True) | |
179 | prompts_pad_left = CBool(True, config=True) |
|
179 | prompts_pad_left = CBool(True, config=True) | |
180 | quiet = CBool(False, config=True) |
|
180 | quiet = CBool(False, config=True) | |
181 |
|
181 | |||
182 | history_length = Int(10000, config=True) |
|
182 | history_length = Int(10000, config=True) | |
183 |
|
183 | |||
184 | # The readline stuff will eventually be moved to the terminal subclass |
|
184 | # The readline stuff will eventually be moved to the terminal subclass | |
185 | # but for now, we can't do that as readline is welded in everywhere. |
|
185 | # but for now, we can't do that as readline is welded in everywhere. | |
186 | readline_use = CBool(True, config=True) |
|
186 | readline_use = CBool(True, config=True) | |
187 | readline_merge_completions = CBool(True, config=True) |
|
187 | readline_merge_completions = CBool(True, config=True) | |
188 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) |
|
188 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) | |
189 | readline_remove_delims = Str('-/~', config=True) |
|
189 | readline_remove_delims = Str('-/~', config=True) | |
190 | readline_parse_and_bind = List([ |
|
190 | readline_parse_and_bind = List([ | |
191 | 'tab: complete', |
|
191 | 'tab: complete', | |
192 | '"\C-l": clear-screen', |
|
192 | '"\C-l": clear-screen', | |
193 | 'set show-all-if-ambiguous on', |
|
193 | 'set show-all-if-ambiguous on', | |
194 | '"\C-o": tab-insert', |
|
194 | '"\C-o": tab-insert', | |
195 | '"\M-i": " "', |
|
195 | '"\M-i": " "', | |
196 | '"\M-o": "\d\d\d\d"', |
|
196 | '"\M-o": "\d\d\d\d"', | |
197 | '"\M-I": "\d\d\d\d"', |
|
197 | '"\M-I": "\d\d\d\d"', | |
198 | '"\C-r": reverse-search-history', |
|
198 | '"\C-r": reverse-search-history', | |
199 | '"\C-s": forward-search-history', |
|
199 | '"\C-s": forward-search-history', | |
200 | '"\C-p": history-search-backward', |
|
200 | '"\C-p": history-search-backward', | |
201 | '"\C-n": history-search-forward', |
|
201 | '"\C-n": history-search-forward', | |
202 | '"\e[A": history-search-backward', |
|
202 | '"\e[A": history-search-backward', | |
203 | '"\e[B": history-search-forward', |
|
203 | '"\e[B": history-search-forward', | |
204 | '"\C-k": kill-line', |
|
204 | '"\C-k": kill-line', | |
205 | '"\C-u": unix-line-discard', |
|
205 | '"\C-u": unix-line-discard', | |
206 | ], allow_none=False, config=True) |
|
206 | ], allow_none=False, config=True) | |
207 |
|
207 | |||
208 | # TODO: this part of prompt management should be moved to the frontends. |
|
208 | # TODO: this part of prompt management should be moved to the frontends. | |
209 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
209 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
210 | separate_in = SeparateStr('\n', config=True) |
|
210 | separate_in = SeparateStr('\n', config=True) | |
211 | separate_out = SeparateStr('', config=True) |
|
211 | separate_out = SeparateStr('', config=True) | |
212 | separate_out2 = SeparateStr('', config=True) |
|
212 | separate_out2 = SeparateStr('', config=True) | |
213 | wildcards_case_sensitive = CBool(True, config=True) |
|
213 | wildcards_case_sensitive = CBool(True, config=True) | |
214 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
214 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
215 | default_value='Context', config=True) |
|
215 | default_value='Context', config=True) | |
216 |
|
216 | |||
217 | # Subcomponents of InteractiveShell |
|
217 | # Subcomponents of InteractiveShell | |
218 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
218 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
219 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
219 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
220 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
220 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
221 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
221 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
222 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
222 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
223 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
223 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
224 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
224 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
225 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
225 | history_manager = Instance('IPython.core.history.HistoryManager') | |
226 |
|
226 | |||
227 | # Private interface |
|
227 | # Private interface | |
228 | _post_execute = set() |
|
228 | _post_execute = set() | |
229 |
|
229 | |||
230 | def __init__(self, config=None, ipython_dir=None, |
|
230 | def __init__(self, config=None, ipython_dir=None, | |
231 | user_ns=None, user_global_ns=None, |
|
231 | user_ns=None, user_global_ns=None, | |
232 | custom_exceptions=((), None)): |
|
232 | custom_exceptions=((), None)): | |
233 |
|
233 | |||
234 | # This is where traits with a config_key argument are updated |
|
234 | # This is where traits with a config_key argument are updated | |
235 | # from the values on config. |
|
235 | # from the values on config. | |
236 | super(InteractiveShell, self).__init__(config=config) |
|
236 | super(InteractiveShell, self).__init__(config=config) | |
237 |
|
237 | |||
238 | # These are relatively independent and stateless |
|
238 | # These are relatively independent and stateless | |
239 | self.init_ipython_dir(ipython_dir) |
|
239 | self.init_ipython_dir(ipython_dir) | |
240 | self.init_instance_attrs() |
|
240 | self.init_instance_attrs() | |
241 | self.init_environment() |
|
241 | self.init_environment() | |
242 |
|
242 | |||
243 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
243 | # Create namespaces (user_ns, user_global_ns, etc.) | |
244 | self.init_create_namespaces(user_ns, user_global_ns) |
|
244 | self.init_create_namespaces(user_ns, user_global_ns) | |
245 | # This has to be done after init_create_namespaces because it uses |
|
245 | # This has to be done after init_create_namespaces because it uses | |
246 | # something in self.user_ns, but before init_sys_modules, which |
|
246 | # something in self.user_ns, but before init_sys_modules, which | |
247 | # is the first thing to modify sys. |
|
247 | # is the first thing to modify sys. | |
248 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
248 | # TODO: When we override sys.stdout and sys.stderr before this class | |
249 | # is created, we are saving the overridden ones here. Not sure if this |
|
249 | # is created, we are saving the overridden ones here. Not sure if this | |
250 | # is what we want to do. |
|
250 | # is what we want to do. | |
251 | self.save_sys_module_state() |
|
251 | self.save_sys_module_state() | |
252 | self.init_sys_modules() |
|
252 | self.init_sys_modules() | |
253 |
|
253 | |||
254 | self.init_history() |
|
254 | self.init_history() | |
255 | self.init_encoding() |
|
255 | self.init_encoding() | |
256 | self.init_prefilter() |
|
256 | self.init_prefilter() | |
257 |
|
257 | |||
258 | Magic.__init__(self, self) |
|
258 | Magic.__init__(self, self) | |
259 |
|
259 | |||
260 | self.init_syntax_highlighting() |
|
260 | self.init_syntax_highlighting() | |
261 | self.init_hooks() |
|
261 | self.init_hooks() | |
262 | self.init_pushd_popd_magic() |
|
262 | self.init_pushd_popd_magic() | |
263 | # self.init_traceback_handlers use to be here, but we moved it below |
|
263 | # self.init_traceback_handlers use to be here, but we moved it below | |
264 | # because it and init_io have to come after init_readline. |
|
264 | # because it and init_io have to come after init_readline. | |
265 | self.init_user_ns() |
|
265 | self.init_user_ns() | |
266 | self.init_logger() |
|
266 | self.init_logger() | |
267 | self.init_alias() |
|
267 | self.init_alias() | |
268 | self.init_builtins() |
|
268 | self.init_builtins() | |
269 |
|
269 | |||
270 | # pre_config_initialization |
|
270 | # pre_config_initialization | |
271 |
|
271 | |||
272 | # The next section should contain everything that was in ipmaker. |
|
272 | # The next section should contain everything that was in ipmaker. | |
273 | self.init_logstart() |
|
273 | self.init_logstart() | |
274 |
|
274 | |||
275 | # The following was in post_config_initialization |
|
275 | # The following was in post_config_initialization | |
276 | self.init_inspector() |
|
276 | self.init_inspector() | |
277 | # init_readline() must come before init_io(), because init_io uses |
|
277 | # init_readline() must come before init_io(), because init_io uses | |
278 | # readline related things. |
|
278 | # readline related things. | |
279 | self.init_readline() |
|
279 | self.init_readline() | |
280 | # init_completer must come after init_readline, because it needs to |
|
280 | # init_completer must come after init_readline, because it needs to | |
281 | # know whether readline is present or not system-wide to configure the |
|
281 | # know whether readline is present or not system-wide to configure the | |
282 | # completers, since the completion machinery can now operate |
|
282 | # completers, since the completion machinery can now operate | |
283 | # independently of readline (e.g. over the network) |
|
283 | # independently of readline (e.g. over the network) | |
284 | self.init_completer() |
|
284 | self.init_completer() | |
285 | # TODO: init_io() needs to happen before init_traceback handlers |
|
285 | # TODO: init_io() needs to happen before init_traceback handlers | |
286 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
286 | # because the traceback handlers hardcode the stdout/stderr streams. | |
287 | # This logic in in debugger.Pdb and should eventually be changed. |
|
287 | # This logic in in debugger.Pdb and should eventually be changed. | |
288 | self.init_io() |
|
288 | self.init_io() | |
289 | self.init_traceback_handlers(custom_exceptions) |
|
289 | self.init_traceback_handlers(custom_exceptions) | |
290 | self.init_prompts() |
|
290 | self.init_prompts() | |
291 | self.init_display_formatter() |
|
291 | self.init_display_formatter() | |
292 | self.init_display_pub() |
|
292 | self.init_display_pub() | |
293 | self.init_displayhook() |
|
293 | self.init_displayhook() | |
294 | self.init_reload_doctest() |
|
294 | self.init_reload_doctest() | |
295 | self.init_magics() |
|
295 | self.init_magics() | |
296 | self.init_pdb() |
|
296 | self.init_pdb() | |
297 | self.init_extension_manager() |
|
297 | self.init_extension_manager() | |
298 | self.init_plugin_manager() |
|
298 | self.init_plugin_manager() | |
299 | self.init_payload() |
|
299 | self.init_payload() | |
300 | self.hooks.late_startup_hook() |
|
300 | self.hooks.late_startup_hook() | |
301 | atexit.register(self.atexit_operations) |
|
301 | atexit.register(self.atexit_operations) | |
302 |
|
302 | |||
303 | # While we're trying to have each part of the code directly access what it |
|
303 | # While we're trying to have each part of the code directly access what it | |
304 | # needs without keeping redundant references to objects, we have too much |
|
304 | # needs without keeping redundant references to objects, we have too much | |
305 | # legacy code that expects ip.db to exist, so let's make it a property that |
|
305 | # legacy code that expects ip.db to exist, so let's make it a property that | |
306 | # retrieves the underlying object from our new history manager. |
|
306 | # retrieves the underlying object from our new history manager. | |
307 | @property |
|
307 | @property | |
308 | def db(self): |
|
308 | def db(self): | |
309 | return self.history_manager.shadow_db |
|
309 | return self.history_manager.shadow_db | |
310 |
|
310 | |||
311 | @classmethod |
|
311 | @classmethod | |
312 | def instance(cls, *args, **kwargs): |
|
312 | def instance(cls, *args, **kwargs): | |
313 | """Returns a global InteractiveShell instance.""" |
|
313 | """Returns a global InteractiveShell instance.""" | |
314 | if cls._instance is None: |
|
314 | if cls._instance is None: | |
315 | inst = cls(*args, **kwargs) |
|
315 | inst = cls(*args, **kwargs) | |
316 | # Now make sure that the instance will also be returned by |
|
316 | # Now make sure that the instance will also be returned by | |
317 | # the subclasses instance attribute. |
|
317 | # the subclasses instance attribute. | |
318 | for subclass in cls.mro(): |
|
318 | for subclass in cls.mro(): | |
319 | if issubclass(cls, subclass) and \ |
|
319 | if issubclass(cls, subclass) and \ | |
320 | issubclass(subclass, InteractiveShell): |
|
320 | issubclass(subclass, InteractiveShell): | |
321 | subclass._instance = inst |
|
321 | subclass._instance = inst | |
322 | else: |
|
322 | else: | |
323 | break |
|
323 | break | |
324 | if isinstance(cls._instance, cls): |
|
324 | if isinstance(cls._instance, cls): | |
325 | return cls._instance |
|
325 | return cls._instance | |
326 | else: |
|
326 | else: | |
327 | raise MultipleInstanceError( |
|
327 | raise MultipleInstanceError( | |
328 | 'Multiple incompatible subclass instances of ' |
|
328 | 'Multiple incompatible subclass instances of ' | |
329 | 'InteractiveShell are being created.' |
|
329 | 'InteractiveShell are being created.' | |
330 | ) |
|
330 | ) | |
331 |
|
331 | |||
332 | @classmethod |
|
332 | @classmethod | |
333 | def initialized(cls): |
|
333 | def initialized(cls): | |
334 | return hasattr(cls, "_instance") |
|
334 | return hasattr(cls, "_instance") | |
335 |
|
335 | |||
336 | def get_ipython(self): |
|
336 | def get_ipython(self): | |
337 | """Return the currently running IPython instance.""" |
|
337 | """Return the currently running IPython instance.""" | |
338 | return self |
|
338 | return self | |
339 |
|
339 | |||
340 | #------------------------------------------------------------------------- |
|
340 | #------------------------------------------------------------------------- | |
341 | # Trait changed handlers |
|
341 | # Trait changed handlers | |
342 | #------------------------------------------------------------------------- |
|
342 | #------------------------------------------------------------------------- | |
343 |
|
343 | |||
344 | def _ipython_dir_changed(self, name, new): |
|
344 | def _ipython_dir_changed(self, name, new): | |
345 | if not os.path.isdir(new): |
|
345 | if not os.path.isdir(new): | |
346 | os.makedirs(new, mode = 0777) |
|
346 | os.makedirs(new, mode = 0777) | |
347 |
|
347 | |||
348 | def set_autoindent(self,value=None): |
|
348 | def set_autoindent(self,value=None): | |
349 | """Set the autoindent flag, checking for readline support. |
|
349 | """Set the autoindent flag, checking for readline support. | |
350 |
|
350 | |||
351 | If called with no arguments, it acts as a toggle.""" |
|
351 | If called with no arguments, it acts as a toggle.""" | |
352 |
|
352 | |||
353 | if not self.has_readline: |
|
353 | if not self.has_readline: | |
354 | if os.name == 'posix': |
|
354 | if os.name == 'posix': | |
355 | warn("The auto-indent feature requires the readline library") |
|
355 | warn("The auto-indent feature requires the readline library") | |
356 | self.autoindent = 0 |
|
356 | self.autoindent = 0 | |
357 | return |
|
357 | return | |
358 | if value is None: |
|
358 | if value is None: | |
359 | self.autoindent = not self.autoindent |
|
359 | self.autoindent = not self.autoindent | |
360 | else: |
|
360 | else: | |
361 | self.autoindent = value |
|
361 | self.autoindent = value | |
362 |
|
362 | |||
363 | #------------------------------------------------------------------------- |
|
363 | #------------------------------------------------------------------------- | |
364 | # init_* methods called by __init__ |
|
364 | # init_* methods called by __init__ | |
365 | #------------------------------------------------------------------------- |
|
365 | #------------------------------------------------------------------------- | |
366 |
|
366 | |||
367 | def init_ipython_dir(self, ipython_dir): |
|
367 | def init_ipython_dir(self, ipython_dir): | |
368 | if ipython_dir is not None: |
|
368 | if ipython_dir is not None: | |
369 | self.ipython_dir = ipython_dir |
|
369 | self.ipython_dir = ipython_dir | |
370 | self.config.Global.ipython_dir = self.ipython_dir |
|
370 | self.config.Global.ipython_dir = self.ipython_dir | |
371 | return |
|
371 | return | |
372 |
|
372 | |||
373 | if hasattr(self.config.Global, 'ipython_dir'): |
|
373 | if hasattr(self.config.Global, 'ipython_dir'): | |
374 | self.ipython_dir = self.config.Global.ipython_dir |
|
374 | self.ipython_dir = self.config.Global.ipython_dir | |
375 | else: |
|
375 | else: | |
376 | self.ipython_dir = get_ipython_dir() |
|
376 | self.ipython_dir = get_ipython_dir() | |
377 |
|
377 | |||
378 | # All children can just read this |
|
378 | # All children can just read this | |
379 | self.config.Global.ipython_dir = self.ipython_dir |
|
379 | self.config.Global.ipython_dir = self.ipython_dir | |
380 |
|
380 | |||
381 | def init_instance_attrs(self): |
|
381 | def init_instance_attrs(self): | |
382 | self.more = False |
|
382 | self.more = False | |
383 |
|
383 | |||
384 | # command compiler |
|
384 | # command compiler | |
385 | self.compile = CachingCompiler() |
|
385 | self.compile = CachingCompiler() | |
386 |
|
386 | |||
387 | # User input buffers |
|
387 | # User input buffers | |
388 | # NOTE: these variables are slated for full removal, once we are 100% |
|
388 | # NOTE: these variables are slated for full removal, once we are 100% | |
389 | # sure that the new execution logic is solid. We will delte runlines, |
|
389 | # sure that the new execution logic is solid. We will delte runlines, | |
390 | # push_line and these buffers, as all input will be managed by the |
|
390 | # push_line and these buffers, as all input will be managed by the | |
391 | # frontends via an inputsplitter instance. |
|
391 | # frontends via an inputsplitter instance. | |
392 | self.buffer = [] |
|
392 | self.buffer = [] | |
393 | self.buffer_raw = [] |
|
393 | self.buffer_raw = [] | |
394 |
|
394 | |||
395 | # Make an empty namespace, which extension writers can rely on both |
|
395 | # Make an empty namespace, which extension writers can rely on both | |
396 | # existing and NEVER being used by ipython itself. This gives them a |
|
396 | # existing and NEVER being used by ipython itself. This gives them a | |
397 | # convenient location for storing additional information and state |
|
397 | # convenient location for storing additional information and state | |
398 | # their extensions may require, without fear of collisions with other |
|
398 | # their extensions may require, without fear of collisions with other | |
399 | # ipython names that may develop later. |
|
399 | # ipython names that may develop later. | |
400 | self.meta = Struct() |
|
400 | self.meta = Struct() | |
401 |
|
401 | |||
402 | # Object variable to store code object waiting execution. This is |
|
402 | # Object variable to store code object waiting execution. This is | |
403 | # used mainly by the multithreaded shells, but it can come in handy in |
|
403 | # used mainly by the multithreaded shells, but it can come in handy in | |
404 | # other situations. No need to use a Queue here, since it's a single |
|
404 | # other situations. No need to use a Queue here, since it's a single | |
405 | # item which gets cleared once run. |
|
405 | # item which gets cleared once run. | |
406 | self.code_to_run = None |
|
406 | self.code_to_run = None | |
407 |
|
407 | |||
408 | # Temporary files used for various purposes. Deleted at exit. |
|
408 | # Temporary files used for various purposes. Deleted at exit. | |
409 | self.tempfiles = [] |
|
409 | self.tempfiles = [] | |
410 |
|
410 | |||
411 | # Keep track of readline usage (later set by init_readline) |
|
411 | # Keep track of readline usage (later set by init_readline) | |
412 | self.has_readline = False |
|
412 | self.has_readline = False | |
413 |
|
413 | |||
414 | # keep track of where we started running (mainly for crash post-mortem) |
|
414 | # keep track of where we started running (mainly for crash post-mortem) | |
415 | # This is not being used anywhere currently. |
|
415 | # This is not being used anywhere currently. | |
416 | self.starting_dir = os.getcwd() |
|
416 | self.starting_dir = os.getcwd() | |
417 |
|
417 | |||
418 | # Indentation management |
|
418 | # Indentation management | |
419 | self.indent_current_nsp = 0 |
|
419 | self.indent_current_nsp = 0 | |
420 |
|
420 | |||
421 | def init_environment(self): |
|
421 | def init_environment(self): | |
422 | """Any changes we need to make to the user's environment.""" |
|
422 | """Any changes we need to make to the user's environment.""" | |
423 | pass |
|
423 | pass | |
424 |
|
424 | |||
425 | def init_encoding(self): |
|
425 | def init_encoding(self): | |
426 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
426 | # Get system encoding at startup time. Certain terminals (like Emacs | |
427 | # under Win32 have it set to None, and we need to have a known valid |
|
427 | # under Win32 have it set to None, and we need to have a known valid | |
428 | # encoding to use in the raw_input() method |
|
428 | # encoding to use in the raw_input() method | |
429 | try: |
|
429 | try: | |
430 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
430 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
431 | except AttributeError: |
|
431 | except AttributeError: | |
432 | self.stdin_encoding = 'ascii' |
|
432 | self.stdin_encoding = 'ascii' | |
433 |
|
433 | |||
434 | def init_syntax_highlighting(self): |
|
434 | def init_syntax_highlighting(self): | |
435 | # Python source parser/formatter for syntax highlighting |
|
435 | # Python source parser/formatter for syntax highlighting | |
436 | pyformat = PyColorize.Parser().format |
|
436 | pyformat = PyColorize.Parser().format | |
437 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
437 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
438 |
|
438 | |||
439 | def init_pushd_popd_magic(self): |
|
439 | def init_pushd_popd_magic(self): | |
440 | # for pushd/popd management |
|
440 | # for pushd/popd management | |
441 | try: |
|
441 | try: | |
442 | self.home_dir = get_home_dir() |
|
442 | self.home_dir = get_home_dir() | |
443 | except HomeDirError, msg: |
|
443 | except HomeDirError, msg: | |
444 | fatal(msg) |
|
444 | fatal(msg) | |
445 |
|
445 | |||
446 | self.dir_stack = [] |
|
446 | self.dir_stack = [] | |
447 |
|
447 | |||
448 | def init_logger(self): |
|
448 | def init_logger(self): | |
449 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
449 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
450 | logmode='rotate') |
|
450 | logmode='rotate') | |
451 |
|
451 | |||
452 | def init_logstart(self): |
|
452 | def init_logstart(self): | |
453 | """Initialize logging in case it was requested at the command line. |
|
453 | """Initialize logging in case it was requested at the command line. | |
454 | """ |
|
454 | """ | |
455 | if self.logappend: |
|
455 | if self.logappend: | |
456 | self.magic_logstart(self.logappend + ' append') |
|
456 | self.magic_logstart(self.logappend + ' append') | |
457 | elif self.logfile: |
|
457 | elif self.logfile: | |
458 | self.magic_logstart(self.logfile) |
|
458 | self.magic_logstart(self.logfile) | |
459 | elif self.logstart: |
|
459 | elif self.logstart: | |
460 | self.magic_logstart() |
|
460 | self.magic_logstart() | |
461 |
|
461 | |||
462 | def init_builtins(self): |
|
462 | def init_builtins(self): | |
463 | self.builtin_trap = BuiltinTrap(shell=self) |
|
463 | self.builtin_trap = BuiltinTrap(shell=self) | |
464 |
|
464 | |||
465 | def init_inspector(self): |
|
465 | def init_inspector(self): | |
466 | # Object inspector |
|
466 | # Object inspector | |
467 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
467 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
468 | PyColorize.ANSICodeColors, |
|
468 | PyColorize.ANSICodeColors, | |
469 | 'NoColor', |
|
469 | 'NoColor', | |
470 | self.object_info_string_level) |
|
470 | self.object_info_string_level) | |
471 |
|
471 | |||
472 | def init_io(self): |
|
472 | def init_io(self): | |
473 | # This will just use sys.stdout and sys.stderr. If you want to |
|
473 | # This will just use sys.stdout and sys.stderr. If you want to | |
474 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
474 | # override sys.stdout and sys.stderr themselves, you need to do that | |
475 | # *before* instantiating this class, because Term holds onto |
|
475 | # *before* instantiating this class, because Term holds onto | |
476 | # references to the underlying streams. |
|
476 | # references to the underlying streams. | |
477 | if sys.platform == 'win32' and self.has_readline: |
|
477 | if sys.platform == 'win32' and self.has_readline: | |
478 | Term = io.IOTerm(cout=self.readline._outputfile, |
|
478 | Term = io.IOTerm(cout=self.readline._outputfile, | |
479 | cerr=self.readline._outputfile) |
|
479 | cerr=self.readline._outputfile) | |
480 | else: |
|
480 | else: | |
481 | Term = io.IOTerm() |
|
481 | Term = io.IOTerm() | |
482 | io.Term = Term |
|
482 | io.Term = Term | |
483 |
|
483 | |||
484 | def init_prompts(self): |
|
484 | def init_prompts(self): | |
485 | # TODO: This is a pass for now because the prompts are managed inside |
|
485 | # TODO: This is a pass for now because the prompts are managed inside | |
486 | # the DisplayHook. Once there is a separate prompt manager, this |
|
486 | # the DisplayHook. Once there is a separate prompt manager, this | |
487 | # will initialize that object and all prompt related information. |
|
487 | # will initialize that object and all prompt related information. | |
488 | pass |
|
488 | pass | |
489 |
|
489 | |||
490 | def init_display_formatter(self): |
|
490 | def init_display_formatter(self): | |
491 | self.display_formatter = DisplayFormatter(config=self.config) |
|
491 | self.display_formatter = DisplayFormatter(config=self.config) | |
492 |
|
492 | |||
493 | def init_display_pub(self): |
|
493 | def init_display_pub(self): | |
494 | self.display_pub = self.display_pub_class(config=self.config) |
|
494 | self.display_pub = self.display_pub_class(config=self.config) | |
495 |
|
495 | |||
496 | def init_displayhook(self): |
|
496 | def init_displayhook(self): | |
497 | # Initialize displayhook, set in/out prompts and printing system |
|
497 | # Initialize displayhook, set in/out prompts and printing system | |
498 | self.displayhook = self.displayhook_class( |
|
498 | self.displayhook = self.displayhook_class( | |
499 | config=self.config, |
|
499 | config=self.config, | |
500 | shell=self, |
|
500 | shell=self, | |
501 | cache_size=self.cache_size, |
|
501 | cache_size=self.cache_size, | |
502 | input_sep = self.separate_in, |
|
502 | input_sep = self.separate_in, | |
503 | output_sep = self.separate_out, |
|
503 | output_sep = self.separate_out, | |
504 | output_sep2 = self.separate_out2, |
|
504 | output_sep2 = self.separate_out2, | |
505 | ps1 = self.prompt_in1, |
|
505 | ps1 = self.prompt_in1, | |
506 | ps2 = self.prompt_in2, |
|
506 | ps2 = self.prompt_in2, | |
507 | ps_out = self.prompt_out, |
|
507 | ps_out = self.prompt_out, | |
508 | pad_left = self.prompts_pad_left |
|
508 | pad_left = self.prompts_pad_left | |
509 | ) |
|
509 | ) | |
510 | # This is a context manager that installs/revmoes the displayhook at |
|
510 | # This is a context manager that installs/revmoes the displayhook at | |
511 | # the appropriate time. |
|
511 | # the appropriate time. | |
512 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
512 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
513 |
|
513 | |||
514 | def init_reload_doctest(self): |
|
514 | def init_reload_doctest(self): | |
515 | # Do a proper resetting of doctest, including the necessary displayhook |
|
515 | # Do a proper resetting of doctest, including the necessary displayhook | |
516 | # monkeypatching |
|
516 | # monkeypatching | |
517 | try: |
|
517 | try: | |
518 | doctest_reload() |
|
518 | doctest_reload() | |
519 | except ImportError: |
|
519 | except ImportError: | |
520 | warn("doctest module does not exist.") |
|
520 | warn("doctest module does not exist.") | |
521 |
|
521 | |||
522 | #------------------------------------------------------------------------- |
|
522 | #------------------------------------------------------------------------- | |
523 | # Things related to injections into the sys module |
|
523 | # Things related to injections into the sys module | |
524 | #------------------------------------------------------------------------- |
|
524 | #------------------------------------------------------------------------- | |
525 |
|
525 | |||
526 | def save_sys_module_state(self): |
|
526 | def save_sys_module_state(self): | |
527 | """Save the state of hooks in the sys module. |
|
527 | """Save the state of hooks in the sys module. | |
528 |
|
528 | |||
529 | This has to be called after self.user_ns is created. |
|
529 | This has to be called after self.user_ns is created. | |
530 | """ |
|
530 | """ | |
531 | self._orig_sys_module_state = {} |
|
531 | self._orig_sys_module_state = {} | |
532 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
532 | self._orig_sys_module_state['stdin'] = sys.stdin | |
533 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
533 | self._orig_sys_module_state['stdout'] = sys.stdout | |
534 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
534 | self._orig_sys_module_state['stderr'] = sys.stderr | |
535 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
535 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
536 | try: |
|
536 | try: | |
537 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
537 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
538 | except KeyError: |
|
538 | except KeyError: | |
539 | pass |
|
539 | pass | |
540 |
|
540 | |||
541 | def restore_sys_module_state(self): |
|
541 | def restore_sys_module_state(self): | |
542 | """Restore the state of the sys module.""" |
|
542 | """Restore the state of the sys module.""" | |
543 | try: |
|
543 | try: | |
544 | for k, v in self._orig_sys_module_state.iteritems(): |
|
544 | for k, v in self._orig_sys_module_state.iteritems(): | |
545 | setattr(sys, k, v) |
|
545 | setattr(sys, k, v) | |
546 | except AttributeError: |
|
546 | except AttributeError: | |
547 | pass |
|
547 | pass | |
548 | # Reset what what done in self.init_sys_modules |
|
548 | # Reset what what done in self.init_sys_modules | |
549 | try: |
|
549 | try: | |
550 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
550 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
551 | except (AttributeError, KeyError): |
|
551 | except (AttributeError, KeyError): | |
552 | pass |
|
552 | pass | |
553 |
|
553 | |||
554 | #------------------------------------------------------------------------- |
|
554 | #------------------------------------------------------------------------- | |
555 | # Things related to hooks |
|
555 | # Things related to hooks | |
556 | #------------------------------------------------------------------------- |
|
556 | #------------------------------------------------------------------------- | |
557 |
|
557 | |||
558 | def init_hooks(self): |
|
558 | def init_hooks(self): | |
559 | # hooks holds pointers used for user-side customizations |
|
559 | # hooks holds pointers used for user-side customizations | |
560 | self.hooks = Struct() |
|
560 | self.hooks = Struct() | |
561 |
|
561 | |||
562 | self.strdispatchers = {} |
|
562 | self.strdispatchers = {} | |
563 |
|
563 | |||
564 | # Set all default hooks, defined in the IPython.hooks module. |
|
564 | # Set all default hooks, defined in the IPython.hooks module. | |
565 | hooks = IPython.core.hooks |
|
565 | hooks = IPython.core.hooks | |
566 | for hook_name in hooks.__all__: |
|
566 | for hook_name in hooks.__all__: | |
567 | # default hooks have priority 100, i.e. low; user hooks should have |
|
567 | # default hooks have priority 100, i.e. low; user hooks should have | |
568 | # 0-100 priority |
|
568 | # 0-100 priority | |
569 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
569 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
570 |
|
570 | |||
571 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
571 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
572 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
572 | """set_hook(name,hook) -> sets an internal IPython hook. | |
573 |
|
573 | |||
574 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
574 | IPython exposes some of its internal API as user-modifiable hooks. By | |
575 | adding your function to one of these hooks, you can modify IPython's |
|
575 | adding your function to one of these hooks, you can modify IPython's | |
576 | behavior to call at runtime your own routines.""" |
|
576 | behavior to call at runtime your own routines.""" | |
577 |
|
577 | |||
578 | # At some point in the future, this should validate the hook before it |
|
578 | # At some point in the future, this should validate the hook before it | |
579 | # accepts it. Probably at least check that the hook takes the number |
|
579 | # accepts it. Probably at least check that the hook takes the number | |
580 | # of args it's supposed to. |
|
580 | # of args it's supposed to. | |
581 |
|
581 | |||
582 | f = types.MethodType(hook,self) |
|
582 | f = types.MethodType(hook,self) | |
583 |
|
583 | |||
584 | # check if the hook is for strdispatcher first |
|
584 | # check if the hook is for strdispatcher first | |
585 | if str_key is not None: |
|
585 | if str_key is not None: | |
586 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
586 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
587 | sdp.add_s(str_key, f, priority ) |
|
587 | sdp.add_s(str_key, f, priority ) | |
588 | self.strdispatchers[name] = sdp |
|
588 | self.strdispatchers[name] = sdp | |
589 | return |
|
589 | return | |
590 | if re_key is not None: |
|
590 | if re_key is not None: | |
591 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
591 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
592 | sdp.add_re(re.compile(re_key), f, priority ) |
|
592 | sdp.add_re(re.compile(re_key), f, priority ) | |
593 | self.strdispatchers[name] = sdp |
|
593 | self.strdispatchers[name] = sdp | |
594 | return |
|
594 | return | |
595 |
|
595 | |||
596 | dp = getattr(self.hooks, name, None) |
|
596 | dp = getattr(self.hooks, name, None) | |
597 | if name not in IPython.core.hooks.__all__: |
|
597 | if name not in IPython.core.hooks.__all__: | |
598 | print "Warning! Hook '%s' is not one of %s" % \ |
|
598 | print "Warning! Hook '%s' is not one of %s" % \ | |
599 | (name, IPython.core.hooks.__all__ ) |
|
599 | (name, IPython.core.hooks.__all__ ) | |
600 | if not dp: |
|
600 | if not dp: | |
601 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
601 | dp = IPython.core.hooks.CommandChainDispatcher() | |
602 |
|
602 | |||
603 | try: |
|
603 | try: | |
604 | dp.add(f,priority) |
|
604 | dp.add(f,priority) | |
605 | except AttributeError: |
|
605 | except AttributeError: | |
606 | # it was not commandchain, plain old func - replace |
|
606 | # it was not commandchain, plain old func - replace | |
607 | dp = f |
|
607 | dp = f | |
608 |
|
608 | |||
609 | setattr(self.hooks,name, dp) |
|
609 | setattr(self.hooks,name, dp) | |
610 |
|
610 | |||
611 | def register_post_execute(self, func): |
|
611 | def register_post_execute(self, func): | |
612 | """Register a function for calling after code execution. |
|
612 | """Register a function for calling after code execution. | |
613 | """ |
|
613 | """ | |
614 | if not callable(func): |
|
614 | if not callable(func): | |
615 | raise ValueError('argument %s must be callable' % func) |
|
615 | raise ValueError('argument %s must be callable' % func) | |
616 | self._post_execute.add(func) |
|
616 | self._post_execute.add(func) | |
617 |
|
617 | |||
618 | #------------------------------------------------------------------------- |
|
618 | #------------------------------------------------------------------------- | |
619 | # Things related to the "main" module |
|
619 | # Things related to the "main" module | |
620 | #------------------------------------------------------------------------- |
|
620 | #------------------------------------------------------------------------- | |
621 |
|
621 | |||
622 | def new_main_mod(self,ns=None): |
|
622 | def new_main_mod(self,ns=None): | |
623 | """Return a new 'main' module object for user code execution. |
|
623 | """Return a new 'main' module object for user code execution. | |
624 | """ |
|
624 | """ | |
625 | main_mod = self._user_main_module |
|
625 | main_mod = self._user_main_module | |
626 | init_fakemod_dict(main_mod,ns) |
|
626 | init_fakemod_dict(main_mod,ns) | |
627 | return main_mod |
|
627 | return main_mod | |
628 |
|
628 | |||
629 | def cache_main_mod(self,ns,fname): |
|
629 | def cache_main_mod(self,ns,fname): | |
630 | """Cache a main module's namespace. |
|
630 | """Cache a main module's namespace. | |
631 |
|
631 | |||
632 | When scripts are executed via %run, we must keep a reference to the |
|
632 | When scripts are executed via %run, we must keep a reference to the | |
633 | namespace of their __main__ module (a FakeModule instance) around so |
|
633 | namespace of their __main__ module (a FakeModule instance) around so | |
634 | that Python doesn't clear it, rendering objects defined therein |
|
634 | that Python doesn't clear it, rendering objects defined therein | |
635 | useless. |
|
635 | useless. | |
636 |
|
636 | |||
637 | This method keeps said reference in a private dict, keyed by the |
|
637 | This method keeps said reference in a private dict, keyed by the | |
638 | absolute path of the module object (which corresponds to the script |
|
638 | absolute path of the module object (which corresponds to the script | |
639 | path). This way, for multiple executions of the same script we only |
|
639 | path). This way, for multiple executions of the same script we only | |
640 | keep one copy of the namespace (the last one), thus preventing memory |
|
640 | keep one copy of the namespace (the last one), thus preventing memory | |
641 | leaks from old references while allowing the objects from the last |
|
641 | leaks from old references while allowing the objects from the last | |
642 | execution to be accessible. |
|
642 | execution to be accessible. | |
643 |
|
643 | |||
644 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
644 | Note: we can not allow the actual FakeModule instances to be deleted, | |
645 | because of how Python tears down modules (it hard-sets all their |
|
645 | because of how Python tears down modules (it hard-sets all their | |
646 | references to None without regard for reference counts). This method |
|
646 | references to None without regard for reference counts). This method | |
647 | must therefore make a *copy* of the given namespace, to allow the |
|
647 | must therefore make a *copy* of the given namespace, to allow the | |
648 | original module's __dict__ to be cleared and reused. |
|
648 | original module's __dict__ to be cleared and reused. | |
649 |
|
649 | |||
650 |
|
650 | |||
651 | Parameters |
|
651 | Parameters | |
652 | ---------- |
|
652 | ---------- | |
653 | ns : a namespace (a dict, typically) |
|
653 | ns : a namespace (a dict, typically) | |
654 |
|
654 | |||
655 | fname : str |
|
655 | fname : str | |
656 | Filename associated with the namespace. |
|
656 | Filename associated with the namespace. | |
657 |
|
657 | |||
658 | Examples |
|
658 | Examples | |
659 | -------- |
|
659 | -------- | |
660 |
|
660 | |||
661 | In [10]: import IPython |
|
661 | In [10]: import IPython | |
662 |
|
662 | |||
663 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
663 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
664 |
|
664 | |||
665 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
665 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
666 | Out[12]: True |
|
666 | Out[12]: True | |
667 | """ |
|
667 | """ | |
668 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
668 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
669 |
|
669 | |||
670 | def clear_main_mod_cache(self): |
|
670 | def clear_main_mod_cache(self): | |
671 | """Clear the cache of main modules. |
|
671 | """Clear the cache of main modules. | |
672 |
|
672 | |||
673 | Mainly for use by utilities like %reset. |
|
673 | Mainly for use by utilities like %reset. | |
674 |
|
674 | |||
675 | Examples |
|
675 | Examples | |
676 | -------- |
|
676 | -------- | |
677 |
|
677 | |||
678 | In [15]: import IPython |
|
678 | In [15]: import IPython | |
679 |
|
679 | |||
680 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
680 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
681 |
|
681 | |||
682 | In [17]: len(_ip._main_ns_cache) > 0 |
|
682 | In [17]: len(_ip._main_ns_cache) > 0 | |
683 | Out[17]: True |
|
683 | Out[17]: True | |
684 |
|
684 | |||
685 | In [18]: _ip.clear_main_mod_cache() |
|
685 | In [18]: _ip.clear_main_mod_cache() | |
686 |
|
686 | |||
687 | In [19]: len(_ip._main_ns_cache) == 0 |
|
687 | In [19]: len(_ip._main_ns_cache) == 0 | |
688 | Out[19]: True |
|
688 | Out[19]: True | |
689 | """ |
|
689 | """ | |
690 | self._main_ns_cache.clear() |
|
690 | self._main_ns_cache.clear() | |
691 |
|
691 | |||
692 | #------------------------------------------------------------------------- |
|
692 | #------------------------------------------------------------------------- | |
693 | # Things related to debugging |
|
693 | # Things related to debugging | |
694 | #------------------------------------------------------------------------- |
|
694 | #------------------------------------------------------------------------- | |
695 |
|
695 | |||
696 | def init_pdb(self): |
|
696 | def init_pdb(self): | |
697 | # Set calling of pdb on exceptions |
|
697 | # Set calling of pdb on exceptions | |
698 | # self.call_pdb is a property |
|
698 | # self.call_pdb is a property | |
699 | self.call_pdb = self.pdb |
|
699 | self.call_pdb = self.pdb | |
700 |
|
700 | |||
701 | def _get_call_pdb(self): |
|
701 | def _get_call_pdb(self): | |
702 | return self._call_pdb |
|
702 | return self._call_pdb | |
703 |
|
703 | |||
704 | def _set_call_pdb(self,val): |
|
704 | def _set_call_pdb(self,val): | |
705 |
|
705 | |||
706 | if val not in (0,1,False,True): |
|
706 | if val not in (0,1,False,True): | |
707 | raise ValueError,'new call_pdb value must be boolean' |
|
707 | raise ValueError,'new call_pdb value must be boolean' | |
708 |
|
708 | |||
709 | # store value in instance |
|
709 | # store value in instance | |
710 | self._call_pdb = val |
|
710 | self._call_pdb = val | |
711 |
|
711 | |||
712 | # notify the actual exception handlers |
|
712 | # notify the actual exception handlers | |
713 | self.InteractiveTB.call_pdb = val |
|
713 | self.InteractiveTB.call_pdb = val | |
714 |
|
714 | |||
715 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
715 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
716 | 'Control auto-activation of pdb at exceptions') |
|
716 | 'Control auto-activation of pdb at exceptions') | |
717 |
|
717 | |||
718 | def debugger(self,force=False): |
|
718 | def debugger(self,force=False): | |
719 | """Call the pydb/pdb debugger. |
|
719 | """Call the pydb/pdb debugger. | |
720 |
|
720 | |||
721 | Keywords: |
|
721 | Keywords: | |
722 |
|
722 | |||
723 | - force(False): by default, this routine checks the instance call_pdb |
|
723 | - force(False): by default, this routine checks the instance call_pdb | |
724 | flag and does not actually invoke the debugger if the flag is false. |
|
724 | flag and does not actually invoke the debugger if the flag is false. | |
725 | The 'force' option forces the debugger to activate even if the flag |
|
725 | The 'force' option forces the debugger to activate even if the flag | |
726 | is false. |
|
726 | is false. | |
727 | """ |
|
727 | """ | |
728 |
|
728 | |||
729 | if not (force or self.call_pdb): |
|
729 | if not (force or self.call_pdb): | |
730 | return |
|
730 | return | |
731 |
|
731 | |||
732 | if not hasattr(sys,'last_traceback'): |
|
732 | if not hasattr(sys,'last_traceback'): | |
733 | error('No traceback has been produced, nothing to debug.') |
|
733 | error('No traceback has been produced, nothing to debug.') | |
734 | return |
|
734 | return | |
735 |
|
735 | |||
736 | # use pydb if available |
|
736 | # use pydb if available | |
737 | if debugger.has_pydb: |
|
737 | if debugger.has_pydb: | |
738 | from pydb import pm |
|
738 | from pydb import pm | |
739 | else: |
|
739 | else: | |
740 | # fallback to our internal debugger |
|
740 | # fallback to our internal debugger | |
741 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
741 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
742 | self.history_saving_wrapper(pm)() |
|
742 | self.history_saving_wrapper(pm)() | |
743 |
|
743 | |||
744 | #------------------------------------------------------------------------- |
|
744 | #------------------------------------------------------------------------- | |
745 | # Things related to IPython's various namespaces |
|
745 | # Things related to IPython's various namespaces | |
746 | #------------------------------------------------------------------------- |
|
746 | #------------------------------------------------------------------------- | |
747 |
|
747 | |||
748 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
748 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
749 | # Create the namespace where the user will operate. user_ns is |
|
749 | # Create the namespace where the user will operate. user_ns is | |
750 | # normally the only one used, and it is passed to the exec calls as |
|
750 | # normally the only one used, and it is passed to the exec calls as | |
751 | # the locals argument. But we do carry a user_global_ns namespace |
|
751 | # the locals argument. But we do carry a user_global_ns namespace | |
752 | # given as the exec 'globals' argument, This is useful in embedding |
|
752 | # given as the exec 'globals' argument, This is useful in embedding | |
753 | # situations where the ipython shell opens in a context where the |
|
753 | # situations where the ipython shell opens in a context where the | |
754 | # distinction between locals and globals is meaningful. For |
|
754 | # distinction between locals and globals is meaningful. For | |
755 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
755 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
756 |
|
756 | |||
757 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
757 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
758 | # level as a dict instead of a module. This is a manual fix, but I |
|
758 | # level as a dict instead of a module. This is a manual fix, but I | |
759 | # should really track down where the problem is coming from. Alex |
|
759 | # should really track down where the problem is coming from. Alex | |
760 | # Schmolck reported this problem first. |
|
760 | # Schmolck reported this problem first. | |
761 |
|
761 | |||
762 | # A useful post by Alex Martelli on this topic: |
|
762 | # A useful post by Alex Martelli on this topic: | |
763 | # Re: inconsistent value from __builtins__ |
|
763 | # Re: inconsistent value from __builtins__ | |
764 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
764 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
765 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
765 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
766 | # Gruppen: comp.lang.python |
|
766 | # Gruppen: comp.lang.python | |
767 |
|
767 | |||
768 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
768 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
769 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
769 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
770 | # > <type 'dict'> |
|
770 | # > <type 'dict'> | |
771 | # > >>> print type(__builtins__) |
|
771 | # > >>> print type(__builtins__) | |
772 | # > <type 'module'> |
|
772 | # > <type 'module'> | |
773 | # > Is this difference in return value intentional? |
|
773 | # > Is this difference in return value intentional? | |
774 |
|
774 | |||
775 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
775 | # Well, it's documented that '__builtins__' can be either a dictionary | |
776 | # or a module, and it's been that way for a long time. Whether it's |
|
776 | # or a module, and it's been that way for a long time. Whether it's | |
777 | # intentional (or sensible), I don't know. In any case, the idea is |
|
777 | # intentional (or sensible), I don't know. In any case, the idea is | |
778 | # that if you need to access the built-in namespace directly, you |
|
778 | # that if you need to access the built-in namespace directly, you | |
779 | # should start with "import __builtin__" (note, no 's') which will |
|
779 | # should start with "import __builtin__" (note, no 's') which will | |
780 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
780 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
781 |
|
781 | |||
782 | # These routines return properly built dicts as needed by the rest of |
|
782 | # These routines return properly built dicts as needed by the rest of | |
783 | # the code, and can also be used by extension writers to generate |
|
783 | # the code, and can also be used by extension writers to generate | |
784 | # properly initialized namespaces. |
|
784 | # properly initialized namespaces. | |
785 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
785 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
786 | user_global_ns) |
|
786 | user_global_ns) | |
787 |
|
787 | |||
788 | # Assign namespaces |
|
788 | # Assign namespaces | |
789 | # This is the namespace where all normal user variables live |
|
789 | # This is the namespace where all normal user variables live | |
790 | self.user_ns = user_ns |
|
790 | self.user_ns = user_ns | |
791 | self.user_global_ns = user_global_ns |
|
791 | self.user_global_ns = user_global_ns | |
792 |
|
792 | |||
793 | # An auxiliary namespace that checks what parts of the user_ns were |
|
793 | # An auxiliary namespace that checks what parts of the user_ns were | |
794 | # loaded at startup, so we can list later only variables defined in |
|
794 | # loaded at startup, so we can list later only variables defined in | |
795 | # actual interactive use. Since it is always a subset of user_ns, it |
|
795 | # actual interactive use. Since it is always a subset of user_ns, it | |
796 | # doesn't need to be separately tracked in the ns_table. |
|
796 | # doesn't need to be separately tracked in the ns_table. | |
797 | self.user_ns_hidden = {} |
|
797 | self.user_ns_hidden = {} | |
798 |
|
798 | |||
799 | # A namespace to keep track of internal data structures to prevent |
|
799 | # A namespace to keep track of internal data structures to prevent | |
800 | # them from cluttering user-visible stuff. Will be updated later |
|
800 | # them from cluttering user-visible stuff. Will be updated later | |
801 | self.internal_ns = {} |
|
801 | self.internal_ns = {} | |
802 |
|
802 | |||
803 | # Now that FakeModule produces a real module, we've run into a nasty |
|
803 | # Now that FakeModule produces a real module, we've run into a nasty | |
804 | # problem: after script execution (via %run), the module where the user |
|
804 | # problem: after script execution (via %run), the module where the user | |
805 | # code ran is deleted. Now that this object is a true module (needed |
|
805 | # code ran is deleted. Now that this object is a true module (needed | |
806 | # so docetst and other tools work correctly), the Python module |
|
806 | # so docetst and other tools work correctly), the Python module | |
807 | # teardown mechanism runs over it, and sets to None every variable |
|
807 | # teardown mechanism runs over it, and sets to None every variable | |
808 | # present in that module. Top-level references to objects from the |
|
808 | # present in that module. Top-level references to objects from the | |
809 | # script survive, because the user_ns is updated with them. However, |
|
809 | # script survive, because the user_ns is updated with them. However, | |
810 | # calling functions defined in the script that use other things from |
|
810 | # calling functions defined in the script that use other things from | |
811 | # the script will fail, because the function's closure had references |
|
811 | # the script will fail, because the function's closure had references | |
812 | # to the original objects, which are now all None. So we must protect |
|
812 | # to the original objects, which are now all None. So we must protect | |
813 | # these modules from deletion by keeping a cache. |
|
813 | # these modules from deletion by keeping a cache. | |
814 | # |
|
814 | # | |
815 | # To avoid keeping stale modules around (we only need the one from the |
|
815 | # To avoid keeping stale modules around (we only need the one from the | |
816 | # last run), we use a dict keyed with the full path to the script, so |
|
816 | # last run), we use a dict keyed with the full path to the script, so | |
817 | # only the last version of the module is held in the cache. Note, |
|
817 | # only the last version of the module is held in the cache. Note, | |
818 | # however, that we must cache the module *namespace contents* (their |
|
818 | # however, that we must cache the module *namespace contents* (their | |
819 | # __dict__). Because if we try to cache the actual modules, old ones |
|
819 | # __dict__). Because if we try to cache the actual modules, old ones | |
820 | # (uncached) could be destroyed while still holding references (such as |
|
820 | # (uncached) could be destroyed while still holding references (such as | |
821 | # those held by GUI objects that tend to be long-lived)> |
|
821 | # those held by GUI objects that tend to be long-lived)> | |
822 | # |
|
822 | # | |
823 | # The %reset command will flush this cache. See the cache_main_mod() |
|
823 | # The %reset command will flush this cache. See the cache_main_mod() | |
824 | # and clear_main_mod_cache() methods for details on use. |
|
824 | # and clear_main_mod_cache() methods for details on use. | |
825 |
|
825 | |||
826 | # This is the cache used for 'main' namespaces |
|
826 | # This is the cache used for 'main' namespaces | |
827 | self._main_ns_cache = {} |
|
827 | self._main_ns_cache = {} | |
828 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
828 | # And this is the single instance of FakeModule whose __dict__ we keep | |
829 | # copying and clearing for reuse on each %run |
|
829 | # copying and clearing for reuse on each %run | |
830 | self._user_main_module = FakeModule() |
|
830 | self._user_main_module = FakeModule() | |
831 |
|
831 | |||
832 | # A table holding all the namespaces IPython deals with, so that |
|
832 | # A table holding all the namespaces IPython deals with, so that | |
833 | # introspection facilities can search easily. |
|
833 | # introspection facilities can search easily. | |
834 | self.ns_table = {'user':user_ns, |
|
834 | self.ns_table = {'user':user_ns, | |
835 | 'user_global':user_global_ns, |
|
835 | 'user_global':user_global_ns, | |
836 | 'internal':self.internal_ns, |
|
836 | 'internal':self.internal_ns, | |
837 | 'builtin':__builtin__.__dict__ |
|
837 | 'builtin':__builtin__.__dict__ | |
838 | } |
|
838 | } | |
839 |
|
839 | |||
840 | # Similarly, track all namespaces where references can be held and that |
|
840 | # Similarly, track all namespaces where references can be held and that | |
841 | # we can safely clear (so it can NOT include builtin). This one can be |
|
841 | # we can safely clear (so it can NOT include builtin). This one can be | |
842 | # a simple list. Note that the main execution namespaces, user_ns and |
|
842 | # a simple list. Note that the main execution namespaces, user_ns and | |
843 | # user_global_ns, can NOT be listed here, as clearing them blindly |
|
843 | # user_global_ns, can NOT be listed here, as clearing them blindly | |
844 | # causes errors in object __del__ methods. Instead, the reset() method |
|
844 | # causes errors in object __del__ methods. Instead, the reset() method | |
845 | # clears them manually and carefully. |
|
845 | # clears them manually and carefully. | |
846 | self.ns_refs_table = [ self.user_ns_hidden, |
|
846 | self.ns_refs_table = [ self.user_ns_hidden, | |
847 | self.internal_ns, self._main_ns_cache ] |
|
847 | self.internal_ns, self._main_ns_cache ] | |
848 |
|
848 | |||
849 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
849 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
850 | """Return a valid local and global user interactive namespaces. |
|
850 | """Return a valid local and global user interactive namespaces. | |
851 |
|
851 | |||
852 | This builds a dict with the minimal information needed to operate as a |
|
852 | This builds a dict with the minimal information needed to operate as a | |
853 | valid IPython user namespace, which you can pass to the various |
|
853 | valid IPython user namespace, which you can pass to the various | |
854 | embedding classes in ipython. The default implementation returns the |
|
854 | embedding classes in ipython. The default implementation returns the | |
855 | same dict for both the locals and the globals to allow functions to |
|
855 | same dict for both the locals and the globals to allow functions to | |
856 | refer to variables in the namespace. Customized implementations can |
|
856 | refer to variables in the namespace. Customized implementations can | |
857 | return different dicts. The locals dictionary can actually be anything |
|
857 | return different dicts. The locals dictionary can actually be anything | |
858 | following the basic mapping protocol of a dict, but the globals dict |
|
858 | following the basic mapping protocol of a dict, but the globals dict | |
859 | must be a true dict, not even a subclass. It is recommended that any |
|
859 | must be a true dict, not even a subclass. It is recommended that any | |
860 | custom object for the locals namespace synchronize with the globals |
|
860 | custom object for the locals namespace synchronize with the globals | |
861 | dict somehow. |
|
861 | dict somehow. | |
862 |
|
862 | |||
863 | Raises TypeError if the provided globals namespace is not a true dict. |
|
863 | Raises TypeError if the provided globals namespace is not a true dict. | |
864 |
|
864 | |||
865 | Parameters |
|
865 | Parameters | |
866 | ---------- |
|
866 | ---------- | |
867 | user_ns : dict-like, optional |
|
867 | user_ns : dict-like, optional | |
868 | The current user namespace. The items in this namespace should |
|
868 | The current user namespace. The items in this namespace should | |
869 | be included in the output. If None, an appropriate blank |
|
869 | be included in the output. If None, an appropriate blank | |
870 | namespace should be created. |
|
870 | namespace should be created. | |
871 | user_global_ns : dict, optional |
|
871 | user_global_ns : dict, optional | |
872 | The current user global namespace. The items in this namespace |
|
872 | The current user global namespace. The items in this namespace | |
873 | should be included in the output. If None, an appropriate |
|
873 | should be included in the output. If None, an appropriate | |
874 | blank namespace should be created. |
|
874 | blank namespace should be created. | |
875 |
|
875 | |||
876 | Returns |
|
876 | Returns | |
877 | ------- |
|
877 | ------- | |
878 | A pair of dictionary-like object to be used as the local namespace |
|
878 | A pair of dictionary-like object to be used as the local namespace | |
879 | of the interpreter and a dict to be used as the global namespace. |
|
879 | of the interpreter and a dict to be used as the global namespace. | |
880 | """ |
|
880 | """ | |
881 |
|
881 | |||
882 |
|
882 | |||
883 | # We must ensure that __builtin__ (without the final 's') is always |
|
883 | # We must ensure that __builtin__ (without the final 's') is always | |
884 | # available and pointing to the __builtin__ *module*. For more details: |
|
884 | # available and pointing to the __builtin__ *module*. For more details: | |
885 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
885 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
886 |
|
886 | |||
887 | if user_ns is None: |
|
887 | if user_ns is None: | |
888 | # Set __name__ to __main__ to better match the behavior of the |
|
888 | # Set __name__ to __main__ to better match the behavior of the | |
889 | # normal interpreter. |
|
889 | # normal interpreter. | |
890 | user_ns = {'__name__' :'__main__', |
|
890 | user_ns = {'__name__' :'__main__', | |
891 | '__builtin__' : __builtin__, |
|
891 | '__builtin__' : __builtin__, | |
892 | '__builtins__' : __builtin__, |
|
892 | '__builtins__' : __builtin__, | |
893 | } |
|
893 | } | |
894 | else: |
|
894 | else: | |
895 | user_ns.setdefault('__name__','__main__') |
|
895 | user_ns.setdefault('__name__','__main__') | |
896 | user_ns.setdefault('__builtin__',__builtin__) |
|
896 | user_ns.setdefault('__builtin__',__builtin__) | |
897 | user_ns.setdefault('__builtins__',__builtin__) |
|
897 | user_ns.setdefault('__builtins__',__builtin__) | |
898 |
|
898 | |||
899 | if user_global_ns is None: |
|
899 | if user_global_ns is None: | |
900 | user_global_ns = user_ns |
|
900 | user_global_ns = user_ns | |
901 | if type(user_global_ns) is not dict: |
|
901 | if type(user_global_ns) is not dict: | |
902 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
902 | raise TypeError("user_global_ns must be a true dict; got %r" | |
903 | % type(user_global_ns)) |
|
903 | % type(user_global_ns)) | |
904 |
|
904 | |||
905 | return user_ns, user_global_ns |
|
905 | return user_ns, user_global_ns | |
906 |
|
906 | |||
907 | def init_sys_modules(self): |
|
907 | def init_sys_modules(self): | |
908 | # We need to insert into sys.modules something that looks like a |
|
908 | # We need to insert into sys.modules something that looks like a | |
909 | # module but which accesses the IPython namespace, for shelve and |
|
909 | # module but which accesses the IPython namespace, for shelve and | |
910 | # pickle to work interactively. Normally they rely on getting |
|
910 | # pickle to work interactively. Normally they rely on getting | |
911 | # everything out of __main__, but for embedding purposes each IPython |
|
911 | # everything out of __main__, but for embedding purposes each IPython | |
912 | # instance has its own private namespace, so we can't go shoving |
|
912 | # instance has its own private namespace, so we can't go shoving | |
913 | # everything into __main__. |
|
913 | # everything into __main__. | |
914 |
|
914 | |||
915 | # note, however, that we should only do this for non-embedded |
|
915 | # note, however, that we should only do this for non-embedded | |
916 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
916 | # ipythons, which really mimic the __main__.__dict__ with their own | |
917 | # namespace. Embedded instances, on the other hand, should not do |
|
917 | # namespace. Embedded instances, on the other hand, should not do | |
918 | # this because they need to manage the user local/global namespaces |
|
918 | # this because they need to manage the user local/global namespaces | |
919 | # only, but they live within a 'normal' __main__ (meaning, they |
|
919 | # only, but they live within a 'normal' __main__ (meaning, they | |
920 | # shouldn't overtake the execution environment of the script they're |
|
920 | # shouldn't overtake the execution environment of the script they're | |
921 | # embedded in). |
|
921 | # embedded in). | |
922 |
|
922 | |||
923 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
923 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
924 |
|
924 | |||
925 | try: |
|
925 | try: | |
926 | main_name = self.user_ns['__name__'] |
|
926 | main_name = self.user_ns['__name__'] | |
927 | except KeyError: |
|
927 | except KeyError: | |
928 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
928 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
929 | else: |
|
929 | else: | |
930 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
930 | sys.modules[main_name] = FakeModule(self.user_ns) | |
931 |
|
931 | |||
932 | def init_user_ns(self): |
|
932 | def init_user_ns(self): | |
933 | """Initialize all user-visible namespaces to their minimum defaults. |
|
933 | """Initialize all user-visible namespaces to their minimum defaults. | |
934 |
|
934 | |||
935 | Certain history lists are also initialized here, as they effectively |
|
935 | Certain history lists are also initialized here, as they effectively | |
936 | act as user namespaces. |
|
936 | act as user namespaces. | |
937 |
|
937 | |||
938 | Notes |
|
938 | Notes | |
939 | ----- |
|
939 | ----- | |
940 | All data structures here are only filled in, they are NOT reset by this |
|
940 | All data structures here are only filled in, they are NOT reset by this | |
941 | method. If they were not empty before, data will simply be added to |
|
941 | method. If they were not empty before, data will simply be added to | |
942 | therm. |
|
942 | therm. | |
943 | """ |
|
943 | """ | |
944 | # This function works in two parts: first we put a few things in |
|
944 | # This function works in two parts: first we put a few things in | |
945 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
945 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
946 | # initial variables aren't shown by %who. After the sync, we add the |
|
946 | # initial variables aren't shown by %who. After the sync, we add the | |
947 | # rest of what we *do* want the user to see with %who even on a new |
|
947 | # rest of what we *do* want the user to see with %who even on a new | |
948 | # session (probably nothing, so theye really only see their own stuff) |
|
948 | # session (probably nothing, so theye really only see their own stuff) | |
949 |
|
949 | |||
950 | # The user dict must *always* have a __builtin__ reference to the |
|
950 | # The user dict must *always* have a __builtin__ reference to the | |
951 | # Python standard __builtin__ namespace, which must be imported. |
|
951 | # Python standard __builtin__ namespace, which must be imported. | |
952 | # This is so that certain operations in prompt evaluation can be |
|
952 | # This is so that certain operations in prompt evaluation can be | |
953 | # reliably executed with builtins. Note that we can NOT use |
|
953 | # reliably executed with builtins. Note that we can NOT use | |
954 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
954 | # __builtins__ (note the 's'), because that can either be a dict or a | |
955 | # module, and can even mutate at runtime, depending on the context |
|
955 | # module, and can even mutate at runtime, depending on the context | |
956 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
956 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
957 | # always a module object, though it must be explicitly imported. |
|
957 | # always a module object, though it must be explicitly imported. | |
958 |
|
958 | |||
959 | # For more details: |
|
959 | # For more details: | |
960 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
960 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
961 | ns = dict(__builtin__ = __builtin__) |
|
961 | ns = dict(__builtin__ = __builtin__) | |
962 |
|
962 | |||
963 | # Put 'help' in the user namespace |
|
963 | # Put 'help' in the user namespace | |
964 | try: |
|
964 | try: | |
965 | from site import _Helper |
|
965 | from site import _Helper | |
966 | ns['help'] = _Helper() |
|
966 | ns['help'] = _Helper() | |
967 | except ImportError: |
|
967 | except ImportError: | |
968 | warn('help() not available - check site.py') |
|
968 | warn('help() not available - check site.py') | |
969 |
|
969 | |||
970 | # make global variables for user access to the histories |
|
970 | # make global variables for user access to the histories | |
971 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
971 | ns['_ih'] = self.history_manager.input_hist_parsed | |
972 | ns['_oh'] = self.history_manager.output_hist |
|
972 | ns['_oh'] = self.history_manager.output_hist | |
973 | ns['_dh'] = self.history_manager.dir_hist |
|
973 | ns['_dh'] = self.history_manager.dir_hist | |
974 |
|
974 | |||
975 | ns['_sh'] = shadowns |
|
975 | ns['_sh'] = shadowns | |
976 |
|
976 | |||
977 | # user aliases to input and output histories. These shouldn't show up |
|
977 | # user aliases to input and output histories. These shouldn't show up | |
978 | # in %who, as they can have very large reprs. |
|
978 | # in %who, as they can have very large reprs. | |
979 | ns['In'] = self.history_manager.input_hist_parsed |
|
979 | ns['In'] = self.history_manager.input_hist_parsed | |
980 | ns['Out'] = self.history_manager.output_hist |
|
980 | ns['Out'] = self.history_manager.output_hist | |
981 |
|
981 | |||
982 | # Store myself as the public api!!! |
|
982 | # Store myself as the public api!!! | |
983 | ns['get_ipython'] = self.get_ipython |
|
983 | ns['get_ipython'] = self.get_ipython | |
984 |
|
984 | |||
985 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
985 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
986 | # by %who |
|
986 | # by %who | |
987 | self.user_ns_hidden.update(ns) |
|
987 | self.user_ns_hidden.update(ns) | |
988 |
|
988 | |||
989 | # Anything put into ns now would show up in %who. Think twice before |
|
989 | # Anything put into ns now would show up in %who. Think twice before | |
990 | # putting anything here, as we really want %who to show the user their |
|
990 | # putting anything here, as we really want %who to show the user their | |
991 | # stuff, not our variables. |
|
991 | # stuff, not our variables. | |
992 |
|
992 | |||
993 | # Finally, update the real user's namespace |
|
993 | # Finally, update the real user's namespace | |
994 | self.user_ns.update(ns) |
|
994 | self.user_ns.update(ns) | |
995 |
|
995 | |||
996 | def reset(self): |
|
996 | def reset(self): | |
997 | """Clear all internal namespaces. |
|
997 | """Clear all internal namespaces. | |
998 |
|
998 | |||
999 | Note that this is much more aggressive than %reset, since it clears |
|
999 | Note that this is much more aggressive than %reset, since it clears | |
1000 | fully all namespaces, as well as all input/output lists. |
|
1000 | fully all namespaces, as well as all input/output lists. | |
1001 | """ |
|
1001 | """ | |
1002 | # Clear histories |
|
1002 | # Clear histories | |
1003 | self.history_manager.reset() |
|
1003 | self.history_manager.reset() | |
1004 |
|
1004 | |||
1005 | # Reset counter used to index all histories |
|
1005 | # Reset counter used to index all histories | |
1006 | self.execution_count = 0 |
|
1006 | self.execution_count = 0 | |
1007 |
|
1007 | |||
1008 | # Restore the user namespaces to minimal usability |
|
1008 | # Restore the user namespaces to minimal usability | |
1009 | for ns in self.ns_refs_table: |
|
1009 | for ns in self.ns_refs_table: | |
1010 | ns.clear() |
|
1010 | ns.clear() | |
1011 |
|
1011 | |||
1012 | # The main execution namespaces must be cleared very carefully, |
|
1012 | # The main execution namespaces must be cleared very carefully, | |
1013 | # skipping the deletion of the builtin-related keys, because doing so |
|
1013 | # skipping the deletion of the builtin-related keys, because doing so | |
1014 | # would cause errors in many object's __del__ methods. |
|
1014 | # would cause errors in many object's __del__ methods. | |
1015 | for ns in [self.user_ns, self.user_global_ns]: |
|
1015 | for ns in [self.user_ns, self.user_global_ns]: | |
1016 | drop_keys = set(ns.keys()) |
|
1016 | drop_keys = set(ns.keys()) | |
1017 | drop_keys.discard('__builtin__') |
|
1017 | drop_keys.discard('__builtin__') | |
1018 | drop_keys.discard('__builtins__') |
|
1018 | drop_keys.discard('__builtins__') | |
1019 | for k in drop_keys: |
|
1019 | for k in drop_keys: | |
1020 | del ns[k] |
|
1020 | del ns[k] | |
1021 |
|
1021 | |||
1022 | # Restore the user namespaces to minimal usability |
|
1022 | # Restore the user namespaces to minimal usability | |
1023 | self.init_user_ns() |
|
1023 | self.init_user_ns() | |
1024 |
|
1024 | |||
1025 | # Restore the default and user aliases |
|
1025 | # Restore the default and user aliases | |
1026 | self.alias_manager.clear_aliases() |
|
1026 | self.alias_manager.clear_aliases() | |
1027 | self.alias_manager.init_aliases() |
|
1027 | self.alias_manager.init_aliases() | |
1028 |
|
1028 | |||
1029 | def reset_selective(self, regex=None): |
|
1029 | def reset_selective(self, regex=None): | |
1030 | """Clear selective variables from internal namespaces based on a |
|
1030 | """Clear selective variables from internal namespaces based on a | |
1031 | specified regular expression. |
|
1031 | specified regular expression. | |
1032 |
|
1032 | |||
1033 | Parameters |
|
1033 | Parameters | |
1034 | ---------- |
|
1034 | ---------- | |
1035 | regex : string or compiled pattern, optional |
|
1035 | regex : string or compiled pattern, optional | |
1036 | A regular expression pattern that will be used in searching |
|
1036 | A regular expression pattern that will be used in searching | |
1037 | variable names in the users namespaces. |
|
1037 | variable names in the users namespaces. | |
1038 | """ |
|
1038 | """ | |
1039 | if regex is not None: |
|
1039 | if regex is not None: | |
1040 | try: |
|
1040 | try: | |
1041 | m = re.compile(regex) |
|
1041 | m = re.compile(regex) | |
1042 | except TypeError: |
|
1042 | except TypeError: | |
1043 | raise TypeError('regex must be a string or compiled pattern') |
|
1043 | raise TypeError('regex must be a string or compiled pattern') | |
1044 | # Search for keys in each namespace that match the given regex |
|
1044 | # Search for keys in each namespace that match the given regex | |
1045 | # If a match is found, delete the key/value pair. |
|
1045 | # If a match is found, delete the key/value pair. | |
1046 | for ns in self.ns_refs_table: |
|
1046 | for ns in self.ns_refs_table: | |
1047 | for var in ns: |
|
1047 | for var in ns: | |
1048 | if m.search(var): |
|
1048 | if m.search(var): | |
1049 | del ns[var] |
|
1049 | del ns[var] | |
1050 |
|
1050 | |||
1051 | def push(self, variables, interactive=True): |
|
1051 | def push(self, variables, interactive=True): | |
1052 | """Inject a group of variables into the IPython user namespace. |
|
1052 | """Inject a group of variables into the IPython user namespace. | |
1053 |
|
1053 | |||
1054 | Parameters |
|
1054 | Parameters | |
1055 | ---------- |
|
1055 | ---------- | |
1056 | variables : dict, str or list/tuple of str |
|
1056 | variables : dict, str or list/tuple of str | |
1057 | The variables to inject into the user's namespace. If a dict, a |
|
1057 | The variables to inject into the user's namespace. If a dict, a | |
1058 | simple update is done. If a str, the string is assumed to have |
|
1058 | simple update is done. If a str, the string is assumed to have | |
1059 | variable names separated by spaces. A list/tuple of str can also |
|
1059 | variable names separated by spaces. A list/tuple of str can also | |
1060 | be used to give the variable names. If just the variable names are |
|
1060 | be used to give the variable names. If just the variable names are | |
1061 | give (list/tuple/str) then the variable values looked up in the |
|
1061 | give (list/tuple/str) then the variable values looked up in the | |
1062 | callers frame. |
|
1062 | callers frame. | |
1063 | interactive : bool |
|
1063 | interactive : bool | |
1064 | If True (default), the variables will be listed with the ``who`` |
|
1064 | If True (default), the variables will be listed with the ``who`` | |
1065 | magic. |
|
1065 | magic. | |
1066 | """ |
|
1066 | """ | |
1067 | vdict = None |
|
1067 | vdict = None | |
1068 |
|
1068 | |||
1069 | # We need a dict of name/value pairs to do namespace updates. |
|
1069 | # We need a dict of name/value pairs to do namespace updates. | |
1070 | if isinstance(variables, dict): |
|
1070 | if isinstance(variables, dict): | |
1071 | vdict = variables |
|
1071 | vdict = variables | |
1072 | elif isinstance(variables, (basestring, list, tuple)): |
|
1072 | elif isinstance(variables, (basestring, list, tuple)): | |
1073 | if isinstance(variables, basestring): |
|
1073 | if isinstance(variables, basestring): | |
1074 | vlist = variables.split() |
|
1074 | vlist = variables.split() | |
1075 | else: |
|
1075 | else: | |
1076 | vlist = variables |
|
1076 | vlist = variables | |
1077 | vdict = {} |
|
1077 | vdict = {} | |
1078 | cf = sys._getframe(1) |
|
1078 | cf = sys._getframe(1) | |
1079 | for name in vlist: |
|
1079 | for name in vlist: | |
1080 | try: |
|
1080 | try: | |
1081 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1081 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1082 | except: |
|
1082 | except: | |
1083 | print ('Could not get variable %s from %s' % |
|
1083 | print ('Could not get variable %s from %s' % | |
1084 | (name,cf.f_code.co_name)) |
|
1084 | (name,cf.f_code.co_name)) | |
1085 | else: |
|
1085 | else: | |
1086 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1086 | raise ValueError('variables must be a dict/str/list/tuple') | |
1087 |
|
1087 | |||
1088 | # Propagate variables to user namespace |
|
1088 | # Propagate variables to user namespace | |
1089 | self.user_ns.update(vdict) |
|
1089 | self.user_ns.update(vdict) | |
1090 |
|
1090 | |||
1091 | # And configure interactive visibility |
|
1091 | # And configure interactive visibility | |
1092 | config_ns = self.user_ns_hidden |
|
1092 | config_ns = self.user_ns_hidden | |
1093 | if interactive: |
|
1093 | if interactive: | |
1094 | for name, val in vdict.iteritems(): |
|
1094 | for name, val in vdict.iteritems(): | |
1095 | config_ns.pop(name, None) |
|
1095 | config_ns.pop(name, None) | |
1096 | else: |
|
1096 | else: | |
1097 | for name,val in vdict.iteritems(): |
|
1097 | for name,val in vdict.iteritems(): | |
1098 | config_ns[name] = val |
|
1098 | config_ns[name] = val | |
1099 |
|
1099 | |||
1100 | #------------------------------------------------------------------------- |
|
1100 | #------------------------------------------------------------------------- | |
1101 | # Things related to object introspection |
|
1101 | # Things related to object introspection | |
1102 | #------------------------------------------------------------------------- |
|
1102 | #------------------------------------------------------------------------- | |
1103 |
|
1103 | |||
1104 | def _ofind(self, oname, namespaces=None): |
|
1104 | def _ofind(self, oname, namespaces=None): | |
1105 | """Find an object in the available namespaces. |
|
1105 | """Find an object in the available namespaces. | |
1106 |
|
1106 | |||
1107 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1107 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1108 |
|
1108 | |||
1109 | Has special code to detect magic functions. |
|
1109 | Has special code to detect magic functions. | |
1110 | """ |
|
1110 | """ | |
1111 | #oname = oname.strip() |
|
1111 | #oname = oname.strip() | |
1112 | #print '1- oname: <%r>' % oname # dbg |
|
1112 | #print '1- oname: <%r>' % oname # dbg | |
1113 | try: |
|
1113 | try: | |
1114 | oname = oname.strip().encode('ascii') |
|
1114 | oname = oname.strip().encode('ascii') | |
1115 | #print '2- oname: <%r>' % oname # dbg |
|
1115 | #print '2- oname: <%r>' % oname # dbg | |
1116 | except UnicodeEncodeError: |
|
1116 | except UnicodeEncodeError: | |
1117 | print 'Python identifiers can only contain ascii characters.' |
|
1117 | print 'Python identifiers can only contain ascii characters.' | |
1118 | return dict(found=False) |
|
1118 | return dict(found=False) | |
1119 |
|
1119 | |||
1120 | alias_ns = None |
|
1120 | alias_ns = None | |
1121 | if namespaces is None: |
|
1121 | if namespaces is None: | |
1122 | # Namespaces to search in: |
|
1122 | # Namespaces to search in: | |
1123 | # Put them in a list. The order is important so that we |
|
1123 | # Put them in a list. The order is important so that we | |
1124 | # find things in the same order that Python finds them. |
|
1124 | # find things in the same order that Python finds them. | |
1125 | namespaces = [ ('Interactive', self.user_ns), |
|
1125 | namespaces = [ ('Interactive', self.user_ns), | |
1126 | ('IPython internal', self.internal_ns), |
|
1126 | ('IPython internal', self.internal_ns), | |
1127 | ('Python builtin', __builtin__.__dict__), |
|
1127 | ('Python builtin', __builtin__.__dict__), | |
1128 | ('Alias', self.alias_manager.alias_table), |
|
1128 | ('Alias', self.alias_manager.alias_table), | |
1129 | ] |
|
1129 | ] | |
1130 | alias_ns = self.alias_manager.alias_table |
|
1130 | alias_ns = self.alias_manager.alias_table | |
1131 |
|
1131 | |||
1132 | # initialize results to 'null' |
|
1132 | # initialize results to 'null' | |
1133 | found = False; obj = None; ospace = None; ds = None; |
|
1133 | found = False; obj = None; ospace = None; ds = None; | |
1134 | ismagic = False; isalias = False; parent = None |
|
1134 | ismagic = False; isalias = False; parent = None | |
1135 |
|
1135 | |||
1136 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1136 | # We need to special-case 'print', which as of python2.6 registers as a | |
1137 | # function but should only be treated as one if print_function was |
|
1137 | # function but should only be treated as one if print_function was | |
1138 | # loaded with a future import. In this case, just bail. |
|
1138 | # loaded with a future import. In this case, just bail. | |
1139 | if (oname == 'print' and not (self.compile.compiler_flags & |
|
1139 | if (oname == 'print' and not (self.compile.compiler_flags & | |
1140 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1140 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1141 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1141 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1142 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1142 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1143 |
|
1143 | |||
1144 | # Look for the given name by splitting it in parts. If the head is |
|
1144 | # Look for the given name by splitting it in parts. If the head is | |
1145 | # found, then we look for all the remaining parts as members, and only |
|
1145 | # found, then we look for all the remaining parts as members, and only | |
1146 | # declare success if we can find them all. |
|
1146 | # declare success if we can find them all. | |
1147 | oname_parts = oname.split('.') |
|
1147 | oname_parts = oname.split('.') | |
1148 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1148 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1149 | for nsname,ns in namespaces: |
|
1149 | for nsname,ns in namespaces: | |
1150 | try: |
|
1150 | try: | |
1151 | obj = ns[oname_head] |
|
1151 | obj = ns[oname_head] | |
1152 | except KeyError: |
|
1152 | except KeyError: | |
1153 | continue |
|
1153 | continue | |
1154 | else: |
|
1154 | else: | |
1155 | #print 'oname_rest:', oname_rest # dbg |
|
1155 | #print 'oname_rest:', oname_rest # dbg | |
1156 | for part in oname_rest: |
|
1156 | for part in oname_rest: | |
1157 | try: |
|
1157 | try: | |
1158 | parent = obj |
|
1158 | parent = obj | |
1159 | obj = getattr(obj,part) |
|
1159 | obj = getattr(obj,part) | |
1160 | except: |
|
1160 | except: | |
1161 | # Blanket except b/c some badly implemented objects |
|
1161 | # Blanket except b/c some badly implemented objects | |
1162 | # allow __getattr__ to raise exceptions other than |
|
1162 | # allow __getattr__ to raise exceptions other than | |
1163 | # AttributeError, which then crashes IPython. |
|
1163 | # AttributeError, which then crashes IPython. | |
1164 | break |
|
1164 | break | |
1165 | else: |
|
1165 | else: | |
1166 | # If we finish the for loop (no break), we got all members |
|
1166 | # If we finish the for loop (no break), we got all members | |
1167 | found = True |
|
1167 | found = True | |
1168 | ospace = nsname |
|
1168 | ospace = nsname | |
1169 | if ns == alias_ns: |
|
1169 | if ns == alias_ns: | |
1170 | isalias = True |
|
1170 | isalias = True | |
1171 | break # namespace loop |
|
1171 | break # namespace loop | |
1172 |
|
1172 | |||
1173 | # Try to see if it's magic |
|
1173 | # Try to see if it's magic | |
1174 | if not found: |
|
1174 | if not found: | |
1175 | if oname.startswith(ESC_MAGIC): |
|
1175 | if oname.startswith(ESC_MAGIC): | |
1176 | oname = oname[1:] |
|
1176 | oname = oname[1:] | |
1177 | obj = getattr(self,'magic_'+oname,None) |
|
1177 | obj = getattr(self,'magic_'+oname,None) | |
1178 | if obj is not None: |
|
1178 | if obj is not None: | |
1179 | found = True |
|
1179 | found = True | |
1180 | ospace = 'IPython internal' |
|
1180 | ospace = 'IPython internal' | |
1181 | ismagic = True |
|
1181 | ismagic = True | |
1182 |
|
1182 | |||
1183 | # Last try: special-case some literals like '', [], {}, etc: |
|
1183 | # Last try: special-case some literals like '', [], {}, etc: | |
1184 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1184 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1185 | obj = eval(oname_head) |
|
1185 | obj = eval(oname_head) | |
1186 | found = True |
|
1186 | found = True | |
1187 | ospace = 'Interactive' |
|
1187 | ospace = 'Interactive' | |
1188 |
|
1188 | |||
1189 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1189 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1190 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1190 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1191 |
|
1191 | |||
1192 | def _ofind_property(self, oname, info): |
|
1192 | def _ofind_property(self, oname, info): | |
1193 | """Second part of object finding, to look for property details.""" |
|
1193 | """Second part of object finding, to look for property details.""" | |
1194 | if info.found: |
|
1194 | if info.found: | |
1195 | # Get the docstring of the class property if it exists. |
|
1195 | # Get the docstring of the class property if it exists. | |
1196 | path = oname.split('.') |
|
1196 | path = oname.split('.') | |
1197 | root = '.'.join(path[:-1]) |
|
1197 | root = '.'.join(path[:-1]) | |
1198 | if info.parent is not None: |
|
1198 | if info.parent is not None: | |
1199 | try: |
|
1199 | try: | |
1200 | target = getattr(info.parent, '__class__') |
|
1200 | target = getattr(info.parent, '__class__') | |
1201 | # The object belongs to a class instance. |
|
1201 | # The object belongs to a class instance. | |
1202 | try: |
|
1202 | try: | |
1203 | target = getattr(target, path[-1]) |
|
1203 | target = getattr(target, path[-1]) | |
1204 | # The class defines the object. |
|
1204 | # The class defines the object. | |
1205 | if isinstance(target, property): |
|
1205 | if isinstance(target, property): | |
1206 | oname = root + '.__class__.' + path[-1] |
|
1206 | oname = root + '.__class__.' + path[-1] | |
1207 | info = Struct(self._ofind(oname)) |
|
1207 | info = Struct(self._ofind(oname)) | |
1208 | except AttributeError: pass |
|
1208 | except AttributeError: pass | |
1209 | except AttributeError: pass |
|
1209 | except AttributeError: pass | |
1210 |
|
1210 | |||
1211 | # We return either the new info or the unmodified input if the object |
|
1211 | # We return either the new info or the unmodified input if the object | |
1212 | # hadn't been found |
|
1212 | # hadn't been found | |
1213 | return info |
|
1213 | return info | |
1214 |
|
1214 | |||
1215 | def _object_find(self, oname, namespaces=None): |
|
1215 | def _object_find(self, oname, namespaces=None): | |
1216 | """Find an object and return a struct with info about it.""" |
|
1216 | """Find an object and return a struct with info about it.""" | |
1217 | inf = Struct(self._ofind(oname, namespaces)) |
|
1217 | inf = Struct(self._ofind(oname, namespaces)) | |
1218 | return Struct(self._ofind_property(oname, inf)) |
|
1218 | return Struct(self._ofind_property(oname, inf)) | |
1219 |
|
1219 | |||
1220 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1220 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1221 | """Generic interface to the inspector system. |
|
1221 | """Generic interface to the inspector system. | |
1222 |
|
1222 | |||
1223 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1223 | This function is meant to be called by pdef, pdoc & friends.""" | |
1224 | info = self._object_find(oname) |
|
1224 | info = self._object_find(oname) | |
1225 | if info.found: |
|
1225 | if info.found: | |
1226 | pmethod = getattr(self.inspector, meth) |
|
1226 | pmethod = getattr(self.inspector, meth) | |
1227 | formatter = format_screen if info.ismagic else None |
|
1227 | formatter = format_screen if info.ismagic else None | |
1228 | if meth == 'pdoc': |
|
1228 | if meth == 'pdoc': | |
1229 | pmethod(info.obj, oname, formatter) |
|
1229 | pmethod(info.obj, oname, formatter) | |
1230 | elif meth == 'pinfo': |
|
1230 | elif meth == 'pinfo': | |
1231 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1231 | pmethod(info.obj, oname, formatter, info, **kw) | |
1232 | else: |
|
1232 | else: | |
1233 | pmethod(info.obj, oname) |
|
1233 | pmethod(info.obj, oname) | |
1234 | else: |
|
1234 | else: | |
1235 | print 'Object `%s` not found.' % oname |
|
1235 | print 'Object `%s` not found.' % oname | |
1236 | return 'not found' # so callers can take other action |
|
1236 | return 'not found' # so callers can take other action | |
1237 |
|
1237 | |||
1238 | def object_inspect(self, oname): |
|
1238 | def object_inspect(self, oname): | |
1239 | info = self._object_find(oname) |
|
1239 | info = self._object_find(oname) | |
1240 | if info.found: |
|
1240 | if info.found: | |
1241 | return self.inspector.info(info.obj, oname, info=info) |
|
1241 | return self.inspector.info(info.obj, oname, info=info) | |
1242 | else: |
|
1242 | else: | |
1243 | return oinspect.object_info(name=oname, found=False) |
|
1243 | return oinspect.object_info(name=oname, found=False) | |
1244 |
|
1244 | |||
1245 | #------------------------------------------------------------------------- |
|
1245 | #------------------------------------------------------------------------- | |
1246 | # Things related to history management |
|
1246 | # Things related to history management | |
1247 | #------------------------------------------------------------------------- |
|
1247 | #------------------------------------------------------------------------- | |
1248 |
|
1248 | |||
1249 | def init_history(self): |
|
1249 | def init_history(self): | |
1250 | """Sets up the command history, and starts regular autosaves.""" |
|
1250 | """Sets up the command history, and starts regular autosaves.""" | |
1251 | self.history_manager = HistoryManager(shell=self, load_history=True) |
|
1251 | self.history_manager = HistoryManager(shell=self, load_history=True) | |
1252 |
|
1252 | |||
1253 | def save_history(self): |
|
1253 | def save_history(self): | |
1254 | """Save input history to a file (via readline library).""" |
|
1254 | """Save input history to a file (via readline library).""" | |
1255 | self.history_manager.save_history() |
|
1255 | self.history_manager.save_history() | |
1256 |
|
1256 | |||
1257 | def reload_history(self): |
|
1257 | def reload_history(self): | |
1258 | """Reload the input history from disk file.""" |
|
1258 | """Reload the input history from disk file.""" | |
1259 | self.history_manager.reload_history() |
|
1259 | self.history_manager.reload_history() | |
1260 |
|
1260 | |||
1261 | def history_saving_wrapper(self, func): |
|
1261 | def history_saving_wrapper(self, func): | |
1262 | """ Wrap func for readline history saving |
|
1262 | """ Wrap func for readline history saving | |
1263 |
|
1263 | |||
1264 | Convert func into callable that saves & restores |
|
1264 | Convert func into callable that saves & restores | |
1265 | history around the call """ |
|
1265 | history around the call """ | |
1266 |
|
1266 | |||
1267 | if self.has_readline: |
|
1267 | if self.has_readline: | |
1268 | from IPython.utils import rlineimpl as readline |
|
1268 | from IPython.utils import rlineimpl as readline | |
1269 | else: |
|
1269 | else: | |
1270 | return func |
|
1270 | return func | |
1271 |
|
1271 | |||
1272 | def wrapper(): |
|
1272 | def wrapper(): | |
1273 | self.save_history() |
|
1273 | self.save_history() | |
1274 | try: |
|
1274 | try: | |
1275 | func() |
|
1275 | func() | |
1276 | finally: |
|
1276 | finally: | |
1277 | self.reload_history() |
|
1277 | self.reload_history() | |
1278 | return wrapper |
|
1278 | return wrapper | |
1279 |
|
1279 | |||
1280 | def get_history(self, index=None, raw=False, output=True): |
|
1280 | def get_history(self, index=None, raw=False, output=True,this_session=True): | |
1281 | return self.history_manager.get_history(index, raw, output) |
|
1281 | return self.history_manager.get_history(index, raw, output,this_session) | |
1282 |
|
1282 | |||
1283 |
|
1283 | |||
1284 | #------------------------------------------------------------------------- |
|
1284 | #------------------------------------------------------------------------- | |
1285 | # Things related to exception handling and tracebacks (not debugging) |
|
1285 | # Things related to exception handling and tracebacks (not debugging) | |
1286 | #------------------------------------------------------------------------- |
|
1286 | #------------------------------------------------------------------------- | |
1287 |
|
1287 | |||
1288 | def init_traceback_handlers(self, custom_exceptions): |
|
1288 | def init_traceback_handlers(self, custom_exceptions): | |
1289 | # Syntax error handler. |
|
1289 | # Syntax error handler. | |
1290 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1290 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1291 |
|
1291 | |||
1292 | # The interactive one is initialized with an offset, meaning we always |
|
1292 | # The interactive one is initialized with an offset, meaning we always | |
1293 | # want to remove the topmost item in the traceback, which is our own |
|
1293 | # want to remove the topmost item in the traceback, which is our own | |
1294 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1294 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1295 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1295 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1296 | color_scheme='NoColor', |
|
1296 | color_scheme='NoColor', | |
1297 | tb_offset = 1, |
|
1297 | tb_offset = 1, | |
1298 | check_cache=self.compile.check_cache) |
|
1298 | check_cache=self.compile.check_cache) | |
1299 |
|
1299 | |||
1300 | # The instance will store a pointer to the system-wide exception hook, |
|
1300 | # The instance will store a pointer to the system-wide exception hook, | |
1301 | # so that runtime code (such as magics) can access it. This is because |
|
1301 | # so that runtime code (such as magics) can access it. This is because | |
1302 | # during the read-eval loop, it may get temporarily overwritten. |
|
1302 | # during the read-eval loop, it may get temporarily overwritten. | |
1303 | self.sys_excepthook = sys.excepthook |
|
1303 | self.sys_excepthook = sys.excepthook | |
1304 |
|
1304 | |||
1305 | # and add any custom exception handlers the user may have specified |
|
1305 | # and add any custom exception handlers the user may have specified | |
1306 | self.set_custom_exc(*custom_exceptions) |
|
1306 | self.set_custom_exc(*custom_exceptions) | |
1307 |
|
1307 | |||
1308 | # Set the exception mode |
|
1308 | # Set the exception mode | |
1309 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1309 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1310 |
|
1310 | |||
1311 | def set_custom_exc(self, exc_tuple, handler): |
|
1311 | def set_custom_exc(self, exc_tuple, handler): | |
1312 | """set_custom_exc(exc_tuple,handler) |
|
1312 | """set_custom_exc(exc_tuple,handler) | |
1313 |
|
1313 | |||
1314 | Set a custom exception handler, which will be called if any of the |
|
1314 | Set a custom exception handler, which will be called if any of the | |
1315 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1315 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1316 | run_code() method. |
|
1316 | run_code() method. | |
1317 |
|
1317 | |||
1318 | Inputs: |
|
1318 | Inputs: | |
1319 |
|
1319 | |||
1320 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1320 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1321 | handler for. It is very important that you use a tuple, and NOT A |
|
1321 | handler for. It is very important that you use a tuple, and NOT A | |
1322 | LIST here, because of the way Python's except statement works. If |
|
1322 | LIST here, because of the way Python's except statement works. If | |
1323 | you only want to trap a single exception, use a singleton tuple: |
|
1323 | you only want to trap a single exception, use a singleton tuple: | |
1324 |
|
1324 | |||
1325 | exc_tuple == (MyCustomException,) |
|
1325 | exc_tuple == (MyCustomException,) | |
1326 |
|
1326 | |||
1327 | - handler: this must be defined as a function with the following |
|
1327 | - handler: this must be defined as a function with the following | |
1328 | basic interface:: |
|
1328 | basic interface:: | |
1329 |
|
1329 | |||
1330 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1330 | def my_handler(self, etype, value, tb, tb_offset=None) | |
1331 | ... |
|
1331 | ... | |
1332 | # The return value must be |
|
1332 | # The return value must be | |
1333 | return structured_traceback |
|
1333 | return structured_traceback | |
1334 |
|
1334 | |||
1335 | This will be made into an instance method (via types.MethodType) |
|
1335 | This will be made into an instance method (via types.MethodType) | |
1336 | of IPython itself, and it will be called if any of the exceptions |
|
1336 | of IPython itself, and it will be called if any of the exceptions | |
1337 | listed in the exc_tuple are caught. If the handler is None, an |
|
1337 | listed in the exc_tuple are caught. If the handler is None, an | |
1338 | internal basic one is used, which just prints basic info. |
|
1338 | internal basic one is used, which just prints basic info. | |
1339 |
|
1339 | |||
1340 | WARNING: by putting in your own exception handler into IPython's main |
|
1340 | WARNING: by putting in your own exception handler into IPython's main | |
1341 | execution loop, you run a very good chance of nasty crashes. This |
|
1341 | execution loop, you run a very good chance of nasty crashes. This | |
1342 | facility should only be used if you really know what you are doing.""" |
|
1342 | facility should only be used if you really know what you are doing.""" | |
1343 |
|
1343 | |||
1344 | assert type(exc_tuple)==type(()) , \ |
|
1344 | assert type(exc_tuple)==type(()) , \ | |
1345 | "The custom exceptions must be given AS A TUPLE." |
|
1345 | "The custom exceptions must be given AS A TUPLE." | |
1346 |
|
1346 | |||
1347 | def dummy_handler(self,etype,value,tb): |
|
1347 | def dummy_handler(self,etype,value,tb): | |
1348 | print '*** Simple custom exception handler ***' |
|
1348 | print '*** Simple custom exception handler ***' | |
1349 | print 'Exception type :',etype |
|
1349 | print 'Exception type :',etype | |
1350 | print 'Exception value:',value |
|
1350 | print 'Exception value:',value | |
1351 | print 'Traceback :',tb |
|
1351 | print 'Traceback :',tb | |
1352 | print 'Source code :','\n'.join(self.buffer) |
|
1352 | print 'Source code :','\n'.join(self.buffer) | |
1353 |
|
1353 | |||
1354 | if handler is None: handler = dummy_handler |
|
1354 | if handler is None: handler = dummy_handler | |
1355 |
|
1355 | |||
1356 | self.CustomTB = types.MethodType(handler,self) |
|
1356 | self.CustomTB = types.MethodType(handler,self) | |
1357 | self.custom_exceptions = exc_tuple |
|
1357 | self.custom_exceptions = exc_tuple | |
1358 |
|
1358 | |||
1359 | def excepthook(self, etype, value, tb): |
|
1359 | def excepthook(self, etype, value, tb): | |
1360 | """One more defense for GUI apps that call sys.excepthook. |
|
1360 | """One more defense for GUI apps that call sys.excepthook. | |
1361 |
|
1361 | |||
1362 | GUI frameworks like wxPython trap exceptions and call |
|
1362 | GUI frameworks like wxPython trap exceptions and call | |
1363 | sys.excepthook themselves. I guess this is a feature that |
|
1363 | sys.excepthook themselves. I guess this is a feature that | |
1364 | enables them to keep running after exceptions that would |
|
1364 | enables them to keep running after exceptions that would | |
1365 | otherwise kill their mainloop. This is a bother for IPython |
|
1365 | otherwise kill their mainloop. This is a bother for IPython | |
1366 | which excepts to catch all of the program exceptions with a try: |
|
1366 | which excepts to catch all of the program exceptions with a try: | |
1367 | except: statement. |
|
1367 | except: statement. | |
1368 |
|
1368 | |||
1369 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1369 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1370 | any app directly invokes sys.excepthook, it will look to the user like |
|
1370 | any app directly invokes sys.excepthook, it will look to the user like | |
1371 | IPython crashed. In order to work around this, we can disable the |
|
1371 | IPython crashed. In order to work around this, we can disable the | |
1372 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1372 | CrashHandler and replace it with this excepthook instead, which prints a | |
1373 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1373 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1374 | call sys.excepthook will generate a regular-looking exception from |
|
1374 | call sys.excepthook will generate a regular-looking exception from | |
1375 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1375 | IPython, and the CrashHandler will only be triggered by real IPython | |
1376 | crashes. |
|
1376 | crashes. | |
1377 |
|
1377 | |||
1378 | This hook should be used sparingly, only in places which are not likely |
|
1378 | This hook should be used sparingly, only in places which are not likely | |
1379 | to be true IPython errors. |
|
1379 | to be true IPython errors. | |
1380 | """ |
|
1380 | """ | |
1381 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1381 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1382 |
|
1382 | |||
1383 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1383 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1384 | exception_only=False): |
|
1384 | exception_only=False): | |
1385 | """Display the exception that just occurred. |
|
1385 | """Display the exception that just occurred. | |
1386 |
|
1386 | |||
1387 | If nothing is known about the exception, this is the method which |
|
1387 | If nothing is known about the exception, this is the method which | |
1388 | should be used throughout the code for presenting user tracebacks, |
|
1388 | should be used throughout the code for presenting user tracebacks, | |
1389 | rather than directly invoking the InteractiveTB object. |
|
1389 | rather than directly invoking the InteractiveTB object. | |
1390 |
|
1390 | |||
1391 | A specific showsyntaxerror() also exists, but this method can take |
|
1391 | A specific showsyntaxerror() also exists, but this method can take | |
1392 | care of calling it if needed, so unless you are explicitly catching a |
|
1392 | care of calling it if needed, so unless you are explicitly catching a | |
1393 | SyntaxError exception, don't try to analyze the stack manually and |
|
1393 | SyntaxError exception, don't try to analyze the stack manually and | |
1394 | simply call this method.""" |
|
1394 | simply call this method.""" | |
1395 |
|
1395 | |||
1396 | try: |
|
1396 | try: | |
1397 | if exc_tuple is None: |
|
1397 | if exc_tuple is None: | |
1398 | etype, value, tb = sys.exc_info() |
|
1398 | etype, value, tb = sys.exc_info() | |
1399 | else: |
|
1399 | else: | |
1400 | etype, value, tb = exc_tuple |
|
1400 | etype, value, tb = exc_tuple | |
1401 |
|
1401 | |||
1402 | if etype is None: |
|
1402 | if etype is None: | |
1403 | if hasattr(sys, 'last_type'): |
|
1403 | if hasattr(sys, 'last_type'): | |
1404 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1404 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1405 | sys.last_traceback |
|
1405 | sys.last_traceback | |
1406 | else: |
|
1406 | else: | |
1407 | self.write_err('No traceback available to show.\n') |
|
1407 | self.write_err('No traceback available to show.\n') | |
1408 | return |
|
1408 | return | |
1409 |
|
1409 | |||
1410 | if etype is SyntaxError: |
|
1410 | if etype is SyntaxError: | |
1411 | # Though this won't be called by syntax errors in the input |
|
1411 | # Though this won't be called by syntax errors in the input | |
1412 | # line, there may be SyntaxError cases whith imported code. |
|
1412 | # line, there may be SyntaxError cases whith imported code. | |
1413 | self.showsyntaxerror(filename) |
|
1413 | self.showsyntaxerror(filename) | |
1414 | elif etype is UsageError: |
|
1414 | elif etype is UsageError: | |
1415 | print "UsageError:", value |
|
1415 | print "UsageError:", value | |
1416 | else: |
|
1416 | else: | |
1417 | # WARNING: these variables are somewhat deprecated and not |
|
1417 | # WARNING: these variables are somewhat deprecated and not | |
1418 | # necessarily safe to use in a threaded environment, but tools |
|
1418 | # necessarily safe to use in a threaded environment, but tools | |
1419 | # like pdb depend on their existence, so let's set them. If we |
|
1419 | # like pdb depend on their existence, so let's set them. If we | |
1420 | # find problems in the field, we'll need to revisit their use. |
|
1420 | # find problems in the field, we'll need to revisit their use. | |
1421 | sys.last_type = etype |
|
1421 | sys.last_type = etype | |
1422 | sys.last_value = value |
|
1422 | sys.last_value = value | |
1423 | sys.last_traceback = tb |
|
1423 | sys.last_traceback = tb | |
1424 |
|
1424 | |||
1425 | if etype in self.custom_exceptions: |
|
1425 | if etype in self.custom_exceptions: | |
1426 | # FIXME: Old custom traceback objects may just return a |
|
1426 | # FIXME: Old custom traceback objects may just return a | |
1427 | # string, in that case we just put it into a list |
|
1427 | # string, in that case we just put it into a list | |
1428 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1428 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1429 | if isinstance(ctb, basestring): |
|
1429 | if isinstance(ctb, basestring): | |
1430 | stb = [stb] |
|
1430 | stb = [stb] | |
1431 | else: |
|
1431 | else: | |
1432 | if exception_only: |
|
1432 | if exception_only: | |
1433 | stb = ['An exception has occurred, use %tb to see ' |
|
1433 | stb = ['An exception has occurred, use %tb to see ' | |
1434 | 'the full traceback.\n'] |
|
1434 | 'the full traceback.\n'] | |
1435 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1435 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1436 | value)) |
|
1436 | value)) | |
1437 | else: |
|
1437 | else: | |
1438 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1438 | stb = self.InteractiveTB.structured_traceback(etype, | |
1439 | value, tb, tb_offset=tb_offset) |
|
1439 | value, tb, tb_offset=tb_offset) | |
1440 | # FIXME: the pdb calling should be done by us, not by |
|
1440 | # FIXME: the pdb calling should be done by us, not by | |
1441 | # the code computing the traceback. |
|
1441 | # the code computing the traceback. | |
1442 | if self.InteractiveTB.call_pdb: |
|
1442 | if self.InteractiveTB.call_pdb: | |
1443 | # pdb mucks up readline, fix it back |
|
1443 | # pdb mucks up readline, fix it back | |
1444 | self.set_readline_completer() |
|
1444 | self.set_readline_completer() | |
1445 |
|
1445 | |||
1446 | # Actually show the traceback |
|
1446 | # Actually show the traceback | |
1447 | self._showtraceback(etype, value, stb) |
|
1447 | self._showtraceback(etype, value, stb) | |
1448 |
|
1448 | |||
1449 | except KeyboardInterrupt: |
|
1449 | except KeyboardInterrupt: | |
1450 | self.write_err("\nKeyboardInterrupt\n") |
|
1450 | self.write_err("\nKeyboardInterrupt\n") | |
1451 |
|
1451 | |||
1452 | def _showtraceback(self, etype, evalue, stb): |
|
1452 | def _showtraceback(self, etype, evalue, stb): | |
1453 | """Actually show a traceback. |
|
1453 | """Actually show a traceback. | |
1454 |
|
1454 | |||
1455 | Subclasses may override this method to put the traceback on a different |
|
1455 | Subclasses may override this method to put the traceback on a different | |
1456 | place, like a side channel. |
|
1456 | place, like a side channel. | |
1457 | """ |
|
1457 | """ | |
1458 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) |
|
1458 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) | |
1459 |
|
1459 | |||
1460 | def showsyntaxerror(self, filename=None): |
|
1460 | def showsyntaxerror(self, filename=None): | |
1461 | """Display the syntax error that just occurred. |
|
1461 | """Display the syntax error that just occurred. | |
1462 |
|
1462 | |||
1463 | This doesn't display a stack trace because there isn't one. |
|
1463 | This doesn't display a stack trace because there isn't one. | |
1464 |
|
1464 | |||
1465 | If a filename is given, it is stuffed in the exception instead |
|
1465 | If a filename is given, it is stuffed in the exception instead | |
1466 | of what was there before (because Python's parser always uses |
|
1466 | of what was there before (because Python's parser always uses | |
1467 | "<string>" when reading from a string). |
|
1467 | "<string>" when reading from a string). | |
1468 | """ |
|
1468 | """ | |
1469 | etype, value, last_traceback = sys.exc_info() |
|
1469 | etype, value, last_traceback = sys.exc_info() | |
1470 |
|
1470 | |||
1471 | # See note about these variables in showtraceback() above |
|
1471 | # See note about these variables in showtraceback() above | |
1472 | sys.last_type = etype |
|
1472 | sys.last_type = etype | |
1473 | sys.last_value = value |
|
1473 | sys.last_value = value | |
1474 | sys.last_traceback = last_traceback |
|
1474 | sys.last_traceback = last_traceback | |
1475 |
|
1475 | |||
1476 | if filename and etype is SyntaxError: |
|
1476 | if filename and etype is SyntaxError: | |
1477 | # Work hard to stuff the correct filename in the exception |
|
1477 | # Work hard to stuff the correct filename in the exception | |
1478 | try: |
|
1478 | try: | |
1479 | msg, (dummy_filename, lineno, offset, line) = value |
|
1479 | msg, (dummy_filename, lineno, offset, line) = value | |
1480 | except: |
|
1480 | except: | |
1481 | # Not the format we expect; leave it alone |
|
1481 | # Not the format we expect; leave it alone | |
1482 | pass |
|
1482 | pass | |
1483 | else: |
|
1483 | else: | |
1484 | # Stuff in the right filename |
|
1484 | # Stuff in the right filename | |
1485 | try: |
|
1485 | try: | |
1486 | # Assume SyntaxError is a class exception |
|
1486 | # Assume SyntaxError is a class exception | |
1487 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1487 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1488 | except: |
|
1488 | except: | |
1489 | # If that failed, assume SyntaxError is a string |
|
1489 | # If that failed, assume SyntaxError is a string | |
1490 | value = msg, (filename, lineno, offset, line) |
|
1490 | value = msg, (filename, lineno, offset, line) | |
1491 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1491 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1492 | self._showtraceback(etype, value, stb) |
|
1492 | self._showtraceback(etype, value, stb) | |
1493 |
|
1493 | |||
1494 | #------------------------------------------------------------------------- |
|
1494 | #------------------------------------------------------------------------- | |
1495 | # Things related to readline |
|
1495 | # Things related to readline | |
1496 | #------------------------------------------------------------------------- |
|
1496 | #------------------------------------------------------------------------- | |
1497 |
|
1497 | |||
1498 | def init_readline(self): |
|
1498 | def init_readline(self): | |
1499 | """Command history completion/saving/reloading.""" |
|
1499 | """Command history completion/saving/reloading.""" | |
1500 |
|
1500 | |||
1501 | if self.readline_use: |
|
1501 | if self.readline_use: | |
1502 | import IPython.utils.rlineimpl as readline |
|
1502 | import IPython.utils.rlineimpl as readline | |
1503 |
|
1503 | |||
1504 | self.rl_next_input = None |
|
1504 | self.rl_next_input = None | |
1505 | self.rl_do_indent = False |
|
1505 | self.rl_do_indent = False | |
1506 |
|
1506 | |||
1507 | if not self.readline_use or not readline.have_readline: |
|
1507 | if not self.readline_use or not readline.have_readline: | |
1508 | self.has_readline = False |
|
1508 | self.has_readline = False | |
1509 | self.readline = None |
|
1509 | self.readline = None | |
1510 | # Set a number of methods that depend on readline to be no-op |
|
1510 | # Set a number of methods that depend on readline to be no-op | |
1511 | self.set_readline_completer = no_op |
|
1511 | self.set_readline_completer = no_op | |
1512 | self.set_custom_completer = no_op |
|
1512 | self.set_custom_completer = no_op | |
1513 | self.set_completer_frame = no_op |
|
1513 | self.set_completer_frame = no_op | |
1514 | warn('Readline services not available or not loaded.') |
|
1514 | warn('Readline services not available or not loaded.') | |
1515 | else: |
|
1515 | else: | |
1516 | self.has_readline = True |
|
1516 | self.has_readline = True | |
1517 | self.readline = readline |
|
1517 | self.readline = readline | |
1518 | sys.modules['readline'] = readline |
|
1518 | sys.modules['readline'] = readline | |
1519 |
|
1519 | |||
1520 | # Platform-specific configuration |
|
1520 | # Platform-specific configuration | |
1521 | if os.name == 'nt': |
|
1521 | if os.name == 'nt': | |
1522 | # FIXME - check with Frederick to see if we can harmonize |
|
1522 | # FIXME - check with Frederick to see if we can harmonize | |
1523 | # naming conventions with pyreadline to avoid this |
|
1523 | # naming conventions with pyreadline to avoid this | |
1524 | # platform-dependent check |
|
1524 | # platform-dependent check | |
1525 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1525 | self.readline_startup_hook = readline.set_pre_input_hook | |
1526 | else: |
|
1526 | else: | |
1527 | self.readline_startup_hook = readline.set_startup_hook |
|
1527 | self.readline_startup_hook = readline.set_startup_hook | |
1528 |
|
1528 | |||
1529 | # Load user's initrc file (readline config) |
|
1529 | # Load user's initrc file (readline config) | |
1530 | # Or if libedit is used, load editrc. |
|
1530 | # Or if libedit is used, load editrc. | |
1531 | inputrc_name = os.environ.get('INPUTRC') |
|
1531 | inputrc_name = os.environ.get('INPUTRC') | |
1532 | if inputrc_name is None: |
|
1532 | if inputrc_name is None: | |
1533 | home_dir = get_home_dir() |
|
1533 | home_dir = get_home_dir() | |
1534 | if home_dir is not None: |
|
1534 | if home_dir is not None: | |
1535 | inputrc_name = '.inputrc' |
|
1535 | inputrc_name = '.inputrc' | |
1536 | if readline.uses_libedit: |
|
1536 | if readline.uses_libedit: | |
1537 | inputrc_name = '.editrc' |
|
1537 | inputrc_name = '.editrc' | |
1538 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1538 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1539 | if os.path.isfile(inputrc_name): |
|
1539 | if os.path.isfile(inputrc_name): | |
1540 | try: |
|
1540 | try: | |
1541 | readline.read_init_file(inputrc_name) |
|
1541 | readline.read_init_file(inputrc_name) | |
1542 | except: |
|
1542 | except: | |
1543 | warn('Problems reading readline initialization file <%s>' |
|
1543 | warn('Problems reading readline initialization file <%s>' | |
1544 | % inputrc_name) |
|
1544 | % inputrc_name) | |
1545 |
|
1545 | |||
1546 | # Configure readline according to user's prefs |
|
1546 | # Configure readline according to user's prefs | |
1547 | # This is only done if GNU readline is being used. If libedit |
|
1547 | # This is only done if GNU readline is being used. If libedit | |
1548 | # is being used (as on Leopard) the readline config is |
|
1548 | # is being used (as on Leopard) the readline config is | |
1549 | # not run as the syntax for libedit is different. |
|
1549 | # not run as the syntax for libedit is different. | |
1550 | if not readline.uses_libedit: |
|
1550 | if not readline.uses_libedit: | |
1551 | for rlcommand in self.readline_parse_and_bind: |
|
1551 | for rlcommand in self.readline_parse_and_bind: | |
1552 | #print "loading rl:",rlcommand # dbg |
|
1552 | #print "loading rl:",rlcommand # dbg | |
1553 | readline.parse_and_bind(rlcommand) |
|
1553 | readline.parse_and_bind(rlcommand) | |
1554 |
|
1554 | |||
1555 | # Remove some chars from the delimiters list. If we encounter |
|
1555 | # Remove some chars from the delimiters list. If we encounter | |
1556 | # unicode chars, discard them. |
|
1556 | # unicode chars, discard them. | |
1557 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1557 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1558 | delims = delims.translate(None, self.readline_remove_delims) |
|
1558 | delims = delims.translate(None, self.readline_remove_delims) | |
1559 | delims = delims.replace(ESC_MAGIC, '') |
|
1559 | delims = delims.replace(ESC_MAGIC, '') | |
1560 | readline.set_completer_delims(delims) |
|
1560 | readline.set_completer_delims(delims) | |
1561 | # otherwise we end up with a monster history after a while: |
|
1561 | # otherwise we end up with a monster history after a while: | |
1562 | readline.set_history_length(self.history_length) |
|
1562 | readline.set_history_length(self.history_length) | |
1563 |
|
1563 | |||
1564 | self.history_manager.populate_readline_history() |
|
1564 | self.history_manager.populate_readline_history() | |
1565 |
|
1565 | |||
1566 | # Configure auto-indent for all platforms |
|
1566 | # Configure auto-indent for all platforms | |
1567 | self.set_autoindent(self.autoindent) |
|
1567 | self.set_autoindent(self.autoindent) | |
1568 |
|
1568 | |||
1569 | def set_next_input(self, s): |
|
1569 | def set_next_input(self, s): | |
1570 | """ Sets the 'default' input string for the next command line. |
|
1570 | """ Sets the 'default' input string for the next command line. | |
1571 |
|
1571 | |||
1572 | Requires readline. |
|
1572 | Requires readline. | |
1573 |
|
1573 | |||
1574 | Example: |
|
1574 | Example: | |
1575 |
|
1575 | |||
1576 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1576 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1577 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1577 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1578 | """ |
|
1578 | """ | |
1579 |
|
1579 | |||
1580 | self.rl_next_input = s |
|
1580 | self.rl_next_input = s | |
1581 |
|
1581 | |||
1582 | # Maybe move this to the terminal subclass? |
|
1582 | # Maybe move this to the terminal subclass? | |
1583 | def pre_readline(self): |
|
1583 | def pre_readline(self): | |
1584 | """readline hook to be used at the start of each line. |
|
1584 | """readline hook to be used at the start of each line. | |
1585 |
|
1585 | |||
1586 | Currently it handles auto-indent only.""" |
|
1586 | Currently it handles auto-indent only.""" | |
1587 |
|
1587 | |||
1588 | if self.rl_do_indent: |
|
1588 | if self.rl_do_indent: | |
1589 | self.readline.insert_text(self._indent_current_str()) |
|
1589 | self.readline.insert_text(self._indent_current_str()) | |
1590 | if self.rl_next_input is not None: |
|
1590 | if self.rl_next_input is not None: | |
1591 | self.readline.insert_text(self.rl_next_input) |
|
1591 | self.readline.insert_text(self.rl_next_input) | |
1592 | self.rl_next_input = None |
|
1592 | self.rl_next_input = None | |
1593 |
|
1593 | |||
1594 | def _indent_current_str(self): |
|
1594 | def _indent_current_str(self): | |
1595 | """return the current level of indentation as a string""" |
|
1595 | """return the current level of indentation as a string""" | |
1596 | return self.input_splitter.indent_spaces * ' ' |
|
1596 | return self.input_splitter.indent_spaces * ' ' | |
1597 |
|
1597 | |||
1598 | #------------------------------------------------------------------------- |
|
1598 | #------------------------------------------------------------------------- | |
1599 | # Things related to text completion |
|
1599 | # Things related to text completion | |
1600 | #------------------------------------------------------------------------- |
|
1600 | #------------------------------------------------------------------------- | |
1601 |
|
1601 | |||
1602 | def init_completer(self): |
|
1602 | def init_completer(self): | |
1603 | """Initialize the completion machinery. |
|
1603 | """Initialize the completion machinery. | |
1604 |
|
1604 | |||
1605 | This creates completion machinery that can be used by client code, |
|
1605 | This creates completion machinery that can be used by client code, | |
1606 | either interactively in-process (typically triggered by the readline |
|
1606 | either interactively in-process (typically triggered by the readline | |
1607 | library), programatically (such as in test suites) or out-of-prcess |
|
1607 | library), programatically (such as in test suites) or out-of-prcess | |
1608 | (typically over the network by remote frontends). |
|
1608 | (typically over the network by remote frontends). | |
1609 | """ |
|
1609 | """ | |
1610 | from IPython.core.completer import IPCompleter |
|
1610 | from IPython.core.completer import IPCompleter | |
1611 | from IPython.core.completerlib import (module_completer, |
|
1611 | from IPython.core.completerlib import (module_completer, | |
1612 | magic_run_completer, cd_completer) |
|
1612 | magic_run_completer, cd_completer) | |
1613 |
|
1613 | |||
1614 | self.Completer = IPCompleter(self, |
|
1614 | self.Completer = IPCompleter(self, | |
1615 | self.user_ns, |
|
1615 | self.user_ns, | |
1616 | self.user_global_ns, |
|
1616 | self.user_global_ns, | |
1617 | self.readline_omit__names, |
|
1617 | self.readline_omit__names, | |
1618 | self.alias_manager.alias_table, |
|
1618 | self.alias_manager.alias_table, | |
1619 | self.has_readline) |
|
1619 | self.has_readline) | |
1620 |
|
1620 | |||
1621 | # Add custom completers to the basic ones built into IPCompleter |
|
1621 | # Add custom completers to the basic ones built into IPCompleter | |
1622 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1622 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1623 | self.strdispatchers['complete_command'] = sdisp |
|
1623 | self.strdispatchers['complete_command'] = sdisp | |
1624 | self.Completer.custom_completers = sdisp |
|
1624 | self.Completer.custom_completers = sdisp | |
1625 |
|
1625 | |||
1626 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1626 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1627 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1627 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1628 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1628 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1629 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1629 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1630 |
|
1630 | |||
1631 | # Only configure readline if we truly are using readline. IPython can |
|
1631 | # Only configure readline if we truly are using readline. IPython can | |
1632 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1632 | # do tab-completion over the network, in GUIs, etc, where readline | |
1633 | # itself may be absent |
|
1633 | # itself may be absent | |
1634 | if self.has_readline: |
|
1634 | if self.has_readline: | |
1635 | self.set_readline_completer() |
|
1635 | self.set_readline_completer() | |
1636 |
|
1636 | |||
1637 | def complete(self, text, line=None, cursor_pos=None): |
|
1637 | def complete(self, text, line=None, cursor_pos=None): | |
1638 | """Return the completed text and a list of completions. |
|
1638 | """Return the completed text and a list of completions. | |
1639 |
|
1639 | |||
1640 | Parameters |
|
1640 | Parameters | |
1641 | ---------- |
|
1641 | ---------- | |
1642 |
|
1642 | |||
1643 | text : string |
|
1643 | text : string | |
1644 | A string of text to be completed on. It can be given as empty and |
|
1644 | A string of text to be completed on. It can be given as empty and | |
1645 | instead a line/position pair are given. In this case, the |
|
1645 | instead a line/position pair are given. In this case, the | |
1646 | completer itself will split the line like readline does. |
|
1646 | completer itself will split the line like readline does. | |
1647 |
|
1647 | |||
1648 | line : string, optional |
|
1648 | line : string, optional | |
1649 | The complete line that text is part of. |
|
1649 | The complete line that text is part of. | |
1650 |
|
1650 | |||
1651 | cursor_pos : int, optional |
|
1651 | cursor_pos : int, optional | |
1652 | The position of the cursor on the input line. |
|
1652 | The position of the cursor on the input line. | |
1653 |
|
1653 | |||
1654 | Returns |
|
1654 | Returns | |
1655 | ------- |
|
1655 | ------- | |
1656 | text : string |
|
1656 | text : string | |
1657 | The actual text that was completed. |
|
1657 | The actual text that was completed. | |
1658 |
|
1658 | |||
1659 | matches : list |
|
1659 | matches : list | |
1660 | A sorted list with all possible completions. |
|
1660 | A sorted list with all possible completions. | |
1661 |
|
1661 | |||
1662 | The optional arguments allow the completion to take more context into |
|
1662 | The optional arguments allow the completion to take more context into | |
1663 | account, and are part of the low-level completion API. |
|
1663 | account, and are part of the low-level completion API. | |
1664 |
|
1664 | |||
1665 | This is a wrapper around the completion mechanism, similar to what |
|
1665 | This is a wrapper around the completion mechanism, similar to what | |
1666 | readline does at the command line when the TAB key is hit. By |
|
1666 | readline does at the command line when the TAB key is hit. By | |
1667 | exposing it as a method, it can be used by other non-readline |
|
1667 | exposing it as a method, it can be used by other non-readline | |
1668 | environments (such as GUIs) for text completion. |
|
1668 | environments (such as GUIs) for text completion. | |
1669 |
|
1669 | |||
1670 | Simple usage example: |
|
1670 | Simple usage example: | |
1671 |
|
1671 | |||
1672 | In [1]: x = 'hello' |
|
1672 | In [1]: x = 'hello' | |
1673 |
|
1673 | |||
1674 | In [2]: _ip.complete('x.l') |
|
1674 | In [2]: _ip.complete('x.l') | |
1675 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1675 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1676 | """ |
|
1676 | """ | |
1677 |
|
1677 | |||
1678 | # Inject names into __builtin__ so we can complete on the added names. |
|
1678 | # Inject names into __builtin__ so we can complete on the added names. | |
1679 | with self.builtin_trap: |
|
1679 | with self.builtin_trap: | |
1680 | return self.Completer.complete(text, line, cursor_pos) |
|
1680 | return self.Completer.complete(text, line, cursor_pos) | |
1681 |
|
1681 | |||
1682 | def set_custom_completer(self, completer, pos=0): |
|
1682 | def set_custom_completer(self, completer, pos=0): | |
1683 | """Adds a new custom completer function. |
|
1683 | """Adds a new custom completer function. | |
1684 |
|
1684 | |||
1685 | The position argument (defaults to 0) is the index in the completers |
|
1685 | The position argument (defaults to 0) is the index in the completers | |
1686 | list where you want the completer to be inserted.""" |
|
1686 | list where you want the completer to be inserted.""" | |
1687 |
|
1687 | |||
1688 | newcomp = types.MethodType(completer,self.Completer) |
|
1688 | newcomp = types.MethodType(completer,self.Completer) | |
1689 | self.Completer.matchers.insert(pos,newcomp) |
|
1689 | self.Completer.matchers.insert(pos,newcomp) | |
1690 |
|
1690 | |||
1691 | def set_readline_completer(self): |
|
1691 | def set_readline_completer(self): | |
1692 | """Reset readline's completer to be our own.""" |
|
1692 | """Reset readline's completer to be our own.""" | |
1693 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1693 | self.readline.set_completer(self.Completer.rlcomplete) | |
1694 |
|
1694 | |||
1695 | def set_completer_frame(self, frame=None): |
|
1695 | def set_completer_frame(self, frame=None): | |
1696 | """Set the frame of the completer.""" |
|
1696 | """Set the frame of the completer.""" | |
1697 | if frame: |
|
1697 | if frame: | |
1698 | self.Completer.namespace = frame.f_locals |
|
1698 | self.Completer.namespace = frame.f_locals | |
1699 | self.Completer.global_namespace = frame.f_globals |
|
1699 | self.Completer.global_namespace = frame.f_globals | |
1700 | else: |
|
1700 | else: | |
1701 | self.Completer.namespace = self.user_ns |
|
1701 | self.Completer.namespace = self.user_ns | |
1702 | self.Completer.global_namespace = self.user_global_ns |
|
1702 | self.Completer.global_namespace = self.user_global_ns | |
1703 |
|
1703 | |||
1704 | #------------------------------------------------------------------------- |
|
1704 | #------------------------------------------------------------------------- | |
1705 | # Things related to magics |
|
1705 | # Things related to magics | |
1706 | #------------------------------------------------------------------------- |
|
1706 | #------------------------------------------------------------------------- | |
1707 |
|
1707 | |||
1708 | def init_magics(self): |
|
1708 | def init_magics(self): | |
1709 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1709 | # FIXME: Move the color initialization to the DisplayHook, which | |
1710 | # should be split into a prompt manager and displayhook. We probably |
|
1710 | # should be split into a prompt manager and displayhook. We probably | |
1711 | # even need a centralize colors management object. |
|
1711 | # even need a centralize colors management object. | |
1712 | self.magic_colors(self.colors) |
|
1712 | self.magic_colors(self.colors) | |
1713 | # History was moved to a separate module |
|
1713 | # History was moved to a separate module | |
1714 | from . import history |
|
1714 | from . import history | |
1715 | history.init_ipython(self) |
|
1715 | history.init_ipython(self) | |
1716 |
|
1716 | |||
1717 | def magic(self,arg_s): |
|
1717 | def magic(self,arg_s): | |
1718 | """Call a magic function by name. |
|
1718 | """Call a magic function by name. | |
1719 |
|
1719 | |||
1720 | Input: a string containing the name of the magic function to call and |
|
1720 | Input: a string containing the name of the magic function to call and | |
1721 | any additional arguments to be passed to the magic. |
|
1721 | any additional arguments to be passed to the magic. | |
1722 |
|
1722 | |||
1723 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1723 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1724 | prompt: |
|
1724 | prompt: | |
1725 |
|
1725 | |||
1726 | In[1]: %name -opt foo bar |
|
1726 | In[1]: %name -opt foo bar | |
1727 |
|
1727 | |||
1728 | To call a magic without arguments, simply use magic('name'). |
|
1728 | To call a magic without arguments, simply use magic('name'). | |
1729 |
|
1729 | |||
1730 | This provides a proper Python function to call IPython's magics in any |
|
1730 | This provides a proper Python function to call IPython's magics in any | |
1731 | valid Python code you can type at the interpreter, including loops and |
|
1731 | valid Python code you can type at the interpreter, including loops and | |
1732 | compound statements. |
|
1732 | compound statements. | |
1733 | """ |
|
1733 | """ | |
1734 | args = arg_s.split(' ',1) |
|
1734 | args = arg_s.split(' ',1) | |
1735 | magic_name = args[0] |
|
1735 | magic_name = args[0] | |
1736 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1736 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1737 |
|
1737 | |||
1738 | try: |
|
1738 | try: | |
1739 | magic_args = args[1] |
|
1739 | magic_args = args[1] | |
1740 | except IndexError: |
|
1740 | except IndexError: | |
1741 | magic_args = '' |
|
1741 | magic_args = '' | |
1742 | fn = getattr(self,'magic_'+magic_name,None) |
|
1742 | fn = getattr(self,'magic_'+magic_name,None) | |
1743 | if fn is None: |
|
1743 | if fn is None: | |
1744 | error("Magic function `%s` not found." % magic_name) |
|
1744 | error("Magic function `%s` not found." % magic_name) | |
1745 | else: |
|
1745 | else: | |
1746 | magic_args = self.var_expand(magic_args,1) |
|
1746 | magic_args = self.var_expand(magic_args,1) | |
1747 | with nested(self.builtin_trap,): |
|
1747 | with nested(self.builtin_trap,): | |
1748 | result = fn(magic_args) |
|
1748 | result = fn(magic_args) | |
1749 | return result |
|
1749 | return result | |
1750 |
|
1750 | |||
1751 | def define_magic(self, magicname, func): |
|
1751 | def define_magic(self, magicname, func): | |
1752 | """Expose own function as magic function for ipython |
|
1752 | """Expose own function as magic function for ipython | |
1753 |
|
1753 | |||
1754 | def foo_impl(self,parameter_s=''): |
|
1754 | def foo_impl(self,parameter_s=''): | |
1755 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1755 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1756 | print 'Magic function. Passed parameter is between < >:' |
|
1756 | print 'Magic function. Passed parameter is between < >:' | |
1757 | print '<%s>' % parameter_s |
|
1757 | print '<%s>' % parameter_s | |
1758 | print 'The self object is:',self |
|
1758 | print 'The self object is:',self | |
1759 |
|
1759 | |||
1760 | self.define_magic('foo',foo_impl) |
|
1760 | self.define_magic('foo',foo_impl) | |
1761 | """ |
|
1761 | """ | |
1762 |
|
1762 | |||
1763 | import new |
|
1763 | import new | |
1764 | im = types.MethodType(func,self) |
|
1764 | im = types.MethodType(func,self) | |
1765 | old = getattr(self, "magic_" + magicname, None) |
|
1765 | old = getattr(self, "magic_" + magicname, None) | |
1766 | setattr(self, "magic_" + magicname, im) |
|
1766 | setattr(self, "magic_" + magicname, im) | |
1767 | return old |
|
1767 | return old | |
1768 |
|
1768 | |||
1769 | #------------------------------------------------------------------------- |
|
1769 | #------------------------------------------------------------------------- | |
1770 | # Things related to macros |
|
1770 | # Things related to macros | |
1771 | #------------------------------------------------------------------------- |
|
1771 | #------------------------------------------------------------------------- | |
1772 |
|
1772 | |||
1773 | def define_macro(self, name, themacro): |
|
1773 | def define_macro(self, name, themacro): | |
1774 | """Define a new macro |
|
1774 | """Define a new macro | |
1775 |
|
1775 | |||
1776 | Parameters |
|
1776 | Parameters | |
1777 | ---------- |
|
1777 | ---------- | |
1778 | name : str |
|
1778 | name : str | |
1779 | The name of the macro. |
|
1779 | The name of the macro. | |
1780 | themacro : str or Macro |
|
1780 | themacro : str or Macro | |
1781 | The action to do upon invoking the macro. If a string, a new |
|
1781 | The action to do upon invoking the macro. If a string, a new | |
1782 | Macro object is created by passing the string to it. |
|
1782 | Macro object is created by passing the string to it. | |
1783 | """ |
|
1783 | """ | |
1784 |
|
1784 | |||
1785 | from IPython.core import macro |
|
1785 | from IPython.core import macro | |
1786 |
|
1786 | |||
1787 | if isinstance(themacro, basestring): |
|
1787 | if isinstance(themacro, basestring): | |
1788 | themacro = macro.Macro(themacro) |
|
1788 | themacro = macro.Macro(themacro) | |
1789 | if not isinstance(themacro, macro.Macro): |
|
1789 | if not isinstance(themacro, macro.Macro): | |
1790 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1790 | raise ValueError('A macro must be a string or a Macro instance.') | |
1791 | self.user_ns[name] = themacro |
|
1791 | self.user_ns[name] = themacro | |
1792 |
|
1792 | |||
1793 | #------------------------------------------------------------------------- |
|
1793 | #------------------------------------------------------------------------- | |
1794 | # Things related to the running of system commands |
|
1794 | # Things related to the running of system commands | |
1795 | #------------------------------------------------------------------------- |
|
1795 | #------------------------------------------------------------------------- | |
1796 |
|
1796 | |||
1797 | def system(self, cmd): |
|
1797 | def system(self, cmd): | |
1798 | """Call the given cmd in a subprocess. |
|
1798 | """Call the given cmd in a subprocess. | |
1799 |
|
1799 | |||
1800 | Parameters |
|
1800 | Parameters | |
1801 | ---------- |
|
1801 | ---------- | |
1802 | cmd : str |
|
1802 | cmd : str | |
1803 | Command to execute (can not end in '&', as bacground processes are |
|
1803 | Command to execute (can not end in '&', as bacground processes are | |
1804 | not supported. |
|
1804 | not supported. | |
1805 | """ |
|
1805 | """ | |
1806 | # We do not support backgrounding processes because we either use |
|
1806 | # We do not support backgrounding processes because we either use | |
1807 | # pexpect or pipes to read from. Users can always just call |
|
1807 | # pexpect or pipes to read from. Users can always just call | |
1808 | # os.system() if they really want a background process. |
|
1808 | # os.system() if they really want a background process. | |
1809 | if cmd.endswith('&'): |
|
1809 | if cmd.endswith('&'): | |
1810 | raise OSError("Background processes not supported.") |
|
1810 | raise OSError("Background processes not supported.") | |
1811 |
|
1811 | |||
1812 | return system(self.var_expand(cmd, depth=2)) |
|
1812 | return system(self.var_expand(cmd, depth=2)) | |
1813 |
|
1813 | |||
1814 | def getoutput(self, cmd, split=True): |
|
1814 | def getoutput(self, cmd, split=True): | |
1815 | """Get output (possibly including stderr) from a subprocess. |
|
1815 | """Get output (possibly including stderr) from a subprocess. | |
1816 |
|
1816 | |||
1817 | Parameters |
|
1817 | Parameters | |
1818 | ---------- |
|
1818 | ---------- | |
1819 | cmd : str |
|
1819 | cmd : str | |
1820 | Command to execute (can not end in '&', as background processes are |
|
1820 | Command to execute (can not end in '&', as background processes are | |
1821 | not supported. |
|
1821 | not supported. | |
1822 | split : bool, optional |
|
1822 | split : bool, optional | |
1823 |
|
1823 | |||
1824 | If True, split the output into an IPython SList. Otherwise, an |
|
1824 | If True, split the output into an IPython SList. Otherwise, an | |
1825 | IPython LSString is returned. These are objects similar to normal |
|
1825 | IPython LSString is returned. These are objects similar to normal | |
1826 | lists and strings, with a few convenience attributes for easier |
|
1826 | lists and strings, with a few convenience attributes for easier | |
1827 | manipulation of line-based output. You can use '?' on them for |
|
1827 | manipulation of line-based output. You can use '?' on them for | |
1828 | details. |
|
1828 | details. | |
1829 | """ |
|
1829 | """ | |
1830 | if cmd.endswith('&'): |
|
1830 | if cmd.endswith('&'): | |
1831 | raise OSError("Background processes not supported.") |
|
1831 | raise OSError("Background processes not supported.") | |
1832 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
1832 | out = getoutput(self.var_expand(cmd, depth=2)) | |
1833 | if split: |
|
1833 | if split: | |
1834 | out = SList(out.splitlines()) |
|
1834 | out = SList(out.splitlines()) | |
1835 | else: |
|
1835 | else: | |
1836 | out = LSString(out) |
|
1836 | out = LSString(out) | |
1837 | return out |
|
1837 | return out | |
1838 |
|
1838 | |||
1839 | #------------------------------------------------------------------------- |
|
1839 | #------------------------------------------------------------------------- | |
1840 | # Things related to aliases |
|
1840 | # Things related to aliases | |
1841 | #------------------------------------------------------------------------- |
|
1841 | #------------------------------------------------------------------------- | |
1842 |
|
1842 | |||
1843 | def init_alias(self): |
|
1843 | def init_alias(self): | |
1844 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1844 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1845 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1845 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1846 |
|
1846 | |||
1847 | #------------------------------------------------------------------------- |
|
1847 | #------------------------------------------------------------------------- | |
1848 | # Things related to extensions and plugins |
|
1848 | # Things related to extensions and plugins | |
1849 | #------------------------------------------------------------------------- |
|
1849 | #------------------------------------------------------------------------- | |
1850 |
|
1850 | |||
1851 | def init_extension_manager(self): |
|
1851 | def init_extension_manager(self): | |
1852 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1852 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1853 |
|
1853 | |||
1854 | def init_plugin_manager(self): |
|
1854 | def init_plugin_manager(self): | |
1855 | self.plugin_manager = PluginManager(config=self.config) |
|
1855 | self.plugin_manager = PluginManager(config=self.config) | |
1856 |
|
1856 | |||
1857 | #------------------------------------------------------------------------- |
|
1857 | #------------------------------------------------------------------------- | |
1858 | # Things related to payloads |
|
1858 | # Things related to payloads | |
1859 | #------------------------------------------------------------------------- |
|
1859 | #------------------------------------------------------------------------- | |
1860 |
|
1860 | |||
1861 | def init_payload(self): |
|
1861 | def init_payload(self): | |
1862 | self.payload_manager = PayloadManager(config=self.config) |
|
1862 | self.payload_manager = PayloadManager(config=self.config) | |
1863 |
|
1863 | |||
1864 | #------------------------------------------------------------------------- |
|
1864 | #------------------------------------------------------------------------- | |
1865 | # Things related to the prefilter |
|
1865 | # Things related to the prefilter | |
1866 | #------------------------------------------------------------------------- |
|
1866 | #------------------------------------------------------------------------- | |
1867 |
|
1867 | |||
1868 | def init_prefilter(self): |
|
1868 | def init_prefilter(self): | |
1869 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1869 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1870 | # Ultimately this will be refactored in the new interpreter code, but |
|
1870 | # Ultimately this will be refactored in the new interpreter code, but | |
1871 | # for now, we should expose the main prefilter method (there's legacy |
|
1871 | # for now, we should expose the main prefilter method (there's legacy | |
1872 | # code out there that may rely on this). |
|
1872 | # code out there that may rely on this). | |
1873 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1873 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1874 |
|
1874 | |||
1875 | def auto_rewrite_input(self, cmd): |
|
1875 | def auto_rewrite_input(self, cmd): | |
1876 | """Print to the screen the rewritten form of the user's command. |
|
1876 | """Print to the screen the rewritten form of the user's command. | |
1877 |
|
1877 | |||
1878 | This shows visual feedback by rewriting input lines that cause |
|
1878 | This shows visual feedback by rewriting input lines that cause | |
1879 | automatic calling to kick in, like:: |
|
1879 | automatic calling to kick in, like:: | |
1880 |
|
1880 | |||
1881 | /f x |
|
1881 | /f x | |
1882 |
|
1882 | |||
1883 | into:: |
|
1883 | into:: | |
1884 |
|
1884 | |||
1885 | ------> f(x) |
|
1885 | ------> f(x) | |
1886 |
|
1886 | |||
1887 | after the user's input prompt. This helps the user understand that the |
|
1887 | after the user's input prompt. This helps the user understand that the | |
1888 | input line was transformed automatically by IPython. |
|
1888 | input line was transformed automatically by IPython. | |
1889 | """ |
|
1889 | """ | |
1890 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1890 | rw = self.displayhook.prompt1.auto_rewrite() + cmd | |
1891 |
|
1891 | |||
1892 | try: |
|
1892 | try: | |
1893 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1893 | # plain ascii works better w/ pyreadline, on some machines, so | |
1894 | # we use it and only print uncolored rewrite if we have unicode |
|
1894 | # we use it and only print uncolored rewrite if we have unicode | |
1895 | rw = str(rw) |
|
1895 | rw = str(rw) | |
1896 | print >> IPython.utils.io.Term.cout, rw |
|
1896 | print >> IPython.utils.io.Term.cout, rw | |
1897 | except UnicodeEncodeError: |
|
1897 | except UnicodeEncodeError: | |
1898 | print "------> " + cmd |
|
1898 | print "------> " + cmd | |
1899 |
|
1899 | |||
1900 | #------------------------------------------------------------------------- |
|
1900 | #------------------------------------------------------------------------- | |
1901 | # Things related to extracting values/expressions from kernel and user_ns |
|
1901 | # Things related to extracting values/expressions from kernel and user_ns | |
1902 | #------------------------------------------------------------------------- |
|
1902 | #------------------------------------------------------------------------- | |
1903 |
|
1903 | |||
1904 | def _simple_error(self): |
|
1904 | def _simple_error(self): | |
1905 | etype, value = sys.exc_info()[:2] |
|
1905 | etype, value = sys.exc_info()[:2] | |
1906 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1906 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
1907 |
|
1907 | |||
1908 | def user_variables(self, names): |
|
1908 | def user_variables(self, names): | |
1909 | """Get a list of variable names from the user's namespace. |
|
1909 | """Get a list of variable names from the user's namespace. | |
1910 |
|
1910 | |||
1911 | Parameters |
|
1911 | Parameters | |
1912 | ---------- |
|
1912 | ---------- | |
1913 | names : list of strings |
|
1913 | names : list of strings | |
1914 | A list of names of variables to be read from the user namespace. |
|
1914 | A list of names of variables to be read from the user namespace. | |
1915 |
|
1915 | |||
1916 | Returns |
|
1916 | Returns | |
1917 | ------- |
|
1917 | ------- | |
1918 | A dict, keyed by the input names and with the repr() of each value. |
|
1918 | A dict, keyed by the input names and with the repr() of each value. | |
1919 | """ |
|
1919 | """ | |
1920 | out = {} |
|
1920 | out = {} | |
1921 | user_ns = self.user_ns |
|
1921 | user_ns = self.user_ns | |
1922 | for varname in names: |
|
1922 | for varname in names: | |
1923 | try: |
|
1923 | try: | |
1924 | value = repr(user_ns[varname]) |
|
1924 | value = repr(user_ns[varname]) | |
1925 | except: |
|
1925 | except: | |
1926 | value = self._simple_error() |
|
1926 | value = self._simple_error() | |
1927 | out[varname] = value |
|
1927 | out[varname] = value | |
1928 | return out |
|
1928 | return out | |
1929 |
|
1929 | |||
1930 | def user_expressions(self, expressions): |
|
1930 | def user_expressions(self, expressions): | |
1931 | """Evaluate a dict of expressions in the user's namespace. |
|
1931 | """Evaluate a dict of expressions in the user's namespace. | |
1932 |
|
1932 | |||
1933 | Parameters |
|
1933 | Parameters | |
1934 | ---------- |
|
1934 | ---------- | |
1935 | expressions : dict |
|
1935 | expressions : dict | |
1936 | A dict with string keys and string values. The expression values |
|
1936 | A dict with string keys and string values. The expression values | |
1937 | should be valid Python expressions, each of which will be evaluated |
|
1937 | should be valid Python expressions, each of which will be evaluated | |
1938 | in the user namespace. |
|
1938 | in the user namespace. | |
1939 |
|
1939 | |||
1940 | Returns |
|
1940 | Returns | |
1941 | ------- |
|
1941 | ------- | |
1942 | A dict, keyed like the input expressions dict, with the repr() of each |
|
1942 | A dict, keyed like the input expressions dict, with the repr() of each | |
1943 | value. |
|
1943 | value. | |
1944 | """ |
|
1944 | """ | |
1945 | out = {} |
|
1945 | out = {} | |
1946 | user_ns = self.user_ns |
|
1946 | user_ns = self.user_ns | |
1947 | global_ns = self.user_global_ns |
|
1947 | global_ns = self.user_global_ns | |
1948 | for key, expr in expressions.iteritems(): |
|
1948 | for key, expr in expressions.iteritems(): | |
1949 | try: |
|
1949 | try: | |
1950 | value = repr(eval(expr, global_ns, user_ns)) |
|
1950 | value = repr(eval(expr, global_ns, user_ns)) | |
1951 | except: |
|
1951 | except: | |
1952 | value = self._simple_error() |
|
1952 | value = self._simple_error() | |
1953 | out[key] = value |
|
1953 | out[key] = value | |
1954 | return out |
|
1954 | return out | |
1955 |
|
1955 | |||
1956 | #------------------------------------------------------------------------- |
|
1956 | #------------------------------------------------------------------------- | |
1957 | # Things related to the running of code |
|
1957 | # Things related to the running of code | |
1958 | #------------------------------------------------------------------------- |
|
1958 | #------------------------------------------------------------------------- | |
1959 |
|
1959 | |||
1960 | def ex(self, cmd): |
|
1960 | def ex(self, cmd): | |
1961 | """Execute a normal python statement in user namespace.""" |
|
1961 | """Execute a normal python statement in user namespace.""" | |
1962 | with nested(self.builtin_trap,): |
|
1962 | with nested(self.builtin_trap,): | |
1963 | exec cmd in self.user_global_ns, self.user_ns |
|
1963 | exec cmd in self.user_global_ns, self.user_ns | |
1964 |
|
1964 | |||
1965 | def ev(self, expr): |
|
1965 | def ev(self, expr): | |
1966 | """Evaluate python expression expr in user namespace. |
|
1966 | """Evaluate python expression expr in user namespace. | |
1967 |
|
1967 | |||
1968 | Returns the result of evaluation |
|
1968 | Returns the result of evaluation | |
1969 | """ |
|
1969 | """ | |
1970 | with nested(self.builtin_trap,): |
|
1970 | with nested(self.builtin_trap,): | |
1971 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1971 | return eval(expr, self.user_global_ns, self.user_ns) | |
1972 |
|
1972 | |||
1973 | def safe_execfile(self, fname, *where, **kw): |
|
1973 | def safe_execfile(self, fname, *where, **kw): | |
1974 | """A safe version of the builtin execfile(). |
|
1974 | """A safe version of the builtin execfile(). | |
1975 |
|
1975 | |||
1976 | This version will never throw an exception, but instead print |
|
1976 | This version will never throw an exception, but instead print | |
1977 | helpful error messages to the screen. This only works on pure |
|
1977 | helpful error messages to the screen. This only works on pure | |
1978 | Python files with the .py extension. |
|
1978 | Python files with the .py extension. | |
1979 |
|
1979 | |||
1980 | Parameters |
|
1980 | Parameters | |
1981 | ---------- |
|
1981 | ---------- | |
1982 | fname : string |
|
1982 | fname : string | |
1983 | The name of the file to be executed. |
|
1983 | The name of the file to be executed. | |
1984 | where : tuple |
|
1984 | where : tuple | |
1985 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1985 | One or two namespaces, passed to execfile() as (globals,locals). | |
1986 | If only one is given, it is passed as both. |
|
1986 | If only one is given, it is passed as both. | |
1987 | exit_ignore : bool (False) |
|
1987 | exit_ignore : bool (False) | |
1988 | If True, then silence SystemExit for non-zero status (it is always |
|
1988 | If True, then silence SystemExit for non-zero status (it is always | |
1989 | silenced for zero status, as it is so common). |
|
1989 | silenced for zero status, as it is so common). | |
1990 | """ |
|
1990 | """ | |
1991 | kw.setdefault('exit_ignore', False) |
|
1991 | kw.setdefault('exit_ignore', False) | |
1992 |
|
1992 | |||
1993 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1993 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1994 |
|
1994 | |||
1995 | # Make sure we have a .py file |
|
1995 | # Make sure we have a .py file | |
1996 | if not fname.endswith('.py'): |
|
1996 | if not fname.endswith('.py'): | |
1997 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1997 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1998 |
|
1998 | |||
1999 | # Make sure we can open the file |
|
1999 | # Make sure we can open the file | |
2000 | try: |
|
2000 | try: | |
2001 | with open(fname) as thefile: |
|
2001 | with open(fname) as thefile: | |
2002 | pass |
|
2002 | pass | |
2003 | except: |
|
2003 | except: | |
2004 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2004 | warn('Could not open file <%s> for safe execution.' % fname) | |
2005 | return |
|
2005 | return | |
2006 |
|
2006 | |||
2007 | # Find things also in current directory. This is needed to mimic the |
|
2007 | # Find things also in current directory. This is needed to mimic the | |
2008 | # behavior of running a script from the system command line, where |
|
2008 | # behavior of running a script from the system command line, where | |
2009 | # Python inserts the script's directory into sys.path |
|
2009 | # Python inserts the script's directory into sys.path | |
2010 | dname = os.path.dirname(fname) |
|
2010 | dname = os.path.dirname(fname) | |
2011 |
|
2011 | |||
2012 | with prepended_to_syspath(dname): |
|
2012 | with prepended_to_syspath(dname): | |
2013 | try: |
|
2013 | try: | |
2014 | execfile(fname,*where) |
|
2014 | execfile(fname,*where) | |
2015 | except SystemExit, status: |
|
2015 | except SystemExit, status: | |
2016 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2016 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2017 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2017 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2018 | # these are considered normal by the OS: |
|
2018 | # these are considered normal by the OS: | |
2019 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2019 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2020 | # 0 |
|
2020 | # 0 | |
2021 | # > python -c'import sys;sys.exit()'; echo $? |
|
2021 | # > python -c'import sys;sys.exit()'; echo $? | |
2022 | # 0 |
|
2022 | # 0 | |
2023 | # For other exit status, we show the exception unless |
|
2023 | # For other exit status, we show the exception unless | |
2024 | # explicitly silenced, but only in short form. |
|
2024 | # explicitly silenced, but only in short form. | |
2025 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2025 | if status.code not in (0, None) and not kw['exit_ignore']: | |
2026 | self.showtraceback(exception_only=True) |
|
2026 | self.showtraceback(exception_only=True) | |
2027 | except: |
|
2027 | except: | |
2028 | self.showtraceback() |
|
2028 | self.showtraceback() | |
2029 |
|
2029 | |||
2030 | def safe_execfile_ipy(self, fname): |
|
2030 | def safe_execfile_ipy(self, fname): | |
2031 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2031 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2032 |
|
2032 | |||
2033 | Parameters |
|
2033 | Parameters | |
2034 | ---------- |
|
2034 | ---------- | |
2035 | fname : str |
|
2035 | fname : str | |
2036 | The name of the file to execute. The filename must have a |
|
2036 | The name of the file to execute. The filename must have a | |
2037 | .ipy extension. |
|
2037 | .ipy extension. | |
2038 | """ |
|
2038 | """ | |
2039 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2039 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2040 |
|
2040 | |||
2041 | # Make sure we have a .py file |
|
2041 | # Make sure we have a .py file | |
2042 | if not fname.endswith('.ipy'): |
|
2042 | if not fname.endswith('.ipy'): | |
2043 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2043 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2044 |
|
2044 | |||
2045 | # Make sure we can open the file |
|
2045 | # Make sure we can open the file | |
2046 | try: |
|
2046 | try: | |
2047 | with open(fname) as thefile: |
|
2047 | with open(fname) as thefile: | |
2048 | pass |
|
2048 | pass | |
2049 | except: |
|
2049 | except: | |
2050 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2050 | warn('Could not open file <%s> for safe execution.' % fname) | |
2051 | return |
|
2051 | return | |
2052 |
|
2052 | |||
2053 | # Find things also in current directory. This is needed to mimic the |
|
2053 | # Find things also in current directory. This is needed to mimic the | |
2054 | # behavior of running a script from the system command line, where |
|
2054 | # behavior of running a script from the system command line, where | |
2055 | # Python inserts the script's directory into sys.path |
|
2055 | # Python inserts the script's directory into sys.path | |
2056 | dname = os.path.dirname(fname) |
|
2056 | dname = os.path.dirname(fname) | |
2057 |
|
2057 | |||
2058 | with prepended_to_syspath(dname): |
|
2058 | with prepended_to_syspath(dname): | |
2059 | try: |
|
2059 | try: | |
2060 | with open(fname) as thefile: |
|
2060 | with open(fname) as thefile: | |
2061 | # self.run_cell currently captures all exceptions |
|
2061 | # self.run_cell currently captures all exceptions | |
2062 | # raised in user code. It would be nice if there were |
|
2062 | # raised in user code. It would be nice if there were | |
2063 | # versions of runlines, execfile that did raise, so |
|
2063 | # versions of runlines, execfile that did raise, so | |
2064 | # we could catch the errors. |
|
2064 | # we could catch the errors. | |
2065 | self.run_cell(thefile.read()) |
|
2065 | self.run_cell(thefile.read()) | |
2066 | except: |
|
2066 | except: | |
2067 | self.showtraceback() |
|
2067 | self.showtraceback() | |
2068 | warn('Unknown failure executing file: <%s>' % fname) |
|
2068 | warn('Unknown failure executing file: <%s>' % fname) | |
2069 |
|
2069 | |||
2070 | def run_cell(self, cell): |
|
2070 | def run_cell(self, cell): | |
2071 | """Run the contents of an entire multiline 'cell' of code. |
|
2071 | """Run the contents of an entire multiline 'cell' of code. | |
2072 |
|
2072 | |||
2073 | The cell is split into separate blocks which can be executed |
|
2073 | The cell is split into separate blocks which can be executed | |
2074 | individually. Then, based on how many blocks there are, they are |
|
2074 | individually. Then, based on how many blocks there are, they are | |
2075 | executed as follows: |
|
2075 | executed as follows: | |
2076 |
|
2076 | |||
2077 | - A single block: 'single' mode. |
|
2077 | - A single block: 'single' mode. | |
2078 |
|
2078 | |||
2079 | If there's more than one block, it depends: |
|
2079 | If there's more than one block, it depends: | |
2080 |
|
2080 | |||
2081 | - if the last one is no more than two lines long, run all but the last |
|
2081 | - if the last one is no more than two lines long, run all but the last | |
2082 | in 'exec' mode and the very last one in 'single' mode. This makes it |
|
2082 | in 'exec' mode and the very last one in 'single' mode. This makes it | |
2083 | easy to type simple expressions at the end to see computed values. - |
|
2083 | easy to type simple expressions at the end to see computed values. - | |
2084 | otherwise (last one is also multiline), run all in 'exec' mode |
|
2084 | otherwise (last one is also multiline), run all in 'exec' mode | |
2085 |
|
2085 | |||
2086 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, |
|
2086 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, | |
2087 | results are displayed and output prompts are computed. In 'exec' mode, |
|
2087 | results are displayed and output prompts are computed. In 'exec' mode, | |
2088 | no results are displayed unless :func:`print` is called explicitly; |
|
2088 | no results are displayed unless :func:`print` is called explicitly; | |
2089 | this mode is more akin to running a script. |
|
2089 | this mode is more akin to running a script. | |
2090 |
|
2090 | |||
2091 | Parameters |
|
2091 | Parameters | |
2092 | ---------- |
|
2092 | ---------- | |
2093 | cell : str |
|
2093 | cell : str | |
2094 | A single or multiline string. |
|
2094 | A single or multiline string. | |
2095 | """ |
|
2095 | """ | |
2096 |
|
2096 | |||
2097 | # We need to break up the input into executable blocks that can be run |
|
2097 | # We need to break up the input into executable blocks that can be run | |
2098 | # in 'single' mode, to provide comfortable user behavior. |
|
2098 | # in 'single' mode, to provide comfortable user behavior. | |
2099 | blocks = self.input_splitter.split_blocks(cell) |
|
2099 | blocks = self.input_splitter.split_blocks(cell) | |
2100 |
|
2100 | |||
2101 | if not blocks: |
|
2101 | if not blocks: | |
2102 | return |
|
2102 | return | |
2103 |
|
2103 | |||
2104 | # Store the 'ipython' version of the cell as well, since that's what |
|
2104 | # Store the 'ipython' version of the cell as well, since that's what | |
2105 | # needs to go into the translated history and get executed (the |
|
2105 | # needs to go into the translated history and get executed (the | |
2106 | # original cell may contain non-python syntax). |
|
2106 | # original cell may contain non-python syntax). | |
2107 | ipy_cell = ''.join(blocks) |
|
2107 | ipy_cell = ''.join(blocks) | |
2108 |
|
2108 | |||
2109 | # Store raw and processed history |
|
2109 | # Store raw and processed history | |
2110 | self.history_manager.store_inputs(ipy_cell, cell) |
|
2110 | self.history_manager.store_inputs(ipy_cell, cell) | |
2111 |
|
2111 | |||
2112 | self.logger.log(ipy_cell, cell) |
|
2112 | self.logger.log(ipy_cell, cell) | |
2113 |
|
2113 | |||
2114 | # All user code execution must happen with our context managers active |
|
2114 | # All user code execution must happen with our context managers active | |
2115 | with nested(self.builtin_trap, self.display_trap): |
|
2115 | with nested(self.builtin_trap, self.display_trap): | |
2116 |
|
2116 | |||
2117 | # Single-block input should behave like an interactive prompt |
|
2117 | # Single-block input should behave like an interactive prompt | |
2118 | if len(blocks) == 1: |
|
2118 | if len(blocks) == 1: | |
2119 | # since we return here, we need to update the execution count |
|
2119 | # since we return here, we need to update the execution count | |
2120 | out = self.run_one_block(blocks[0]) |
|
2120 | out = self.run_one_block(blocks[0]) | |
2121 | self.execution_count += 1 |
|
2121 | self.execution_count += 1 | |
2122 | return out |
|
2122 | return out | |
2123 |
|
2123 | |||
2124 | # In multi-block input, if the last block is a simple (one-two |
|
2124 | # In multi-block input, if the last block is a simple (one-two | |
2125 | # lines) expression, run it in single mode so it produces output. |
|
2125 | # lines) expression, run it in single mode so it produces output. | |
2126 | # Otherwise just feed the whole thing to run_code. This seems like |
|
2126 | # Otherwise just feed the whole thing to run_code. This seems like | |
2127 | # a reasonable usability design. |
|
2127 | # a reasonable usability design. | |
2128 | last = blocks[-1] |
|
2128 | last = blocks[-1] | |
2129 | last_nlines = len(last.splitlines()) |
|
2129 | last_nlines = len(last.splitlines()) | |
2130 |
|
2130 | |||
2131 | # Note: below, whenever we call run_code, we must sync history |
|
2131 | # Note: below, whenever we call run_code, we must sync history | |
2132 | # ourselves, because run_code is NOT meant to manage history at all. |
|
2132 | # ourselves, because run_code is NOT meant to manage history at all. | |
2133 | if last_nlines < 2: |
|
2133 | if last_nlines < 2: | |
2134 | # Here we consider the cell split between 'body' and 'last', |
|
2134 | # Here we consider the cell split between 'body' and 'last', | |
2135 | # store all history and execute 'body', and if successful, then |
|
2135 | # store all history and execute 'body', and if successful, then | |
2136 | # proceed to execute 'last'. |
|
2136 | # proceed to execute 'last'. | |
2137 |
|
2137 | |||
2138 | # Get the main body to run as a cell |
|
2138 | # Get the main body to run as a cell | |
2139 | ipy_body = ''.join(blocks[:-1]) |
|
2139 | ipy_body = ''.join(blocks[:-1]) | |
2140 | retcode = self.run_source(ipy_body, symbol='exec', |
|
2140 | retcode = self.run_source(ipy_body, symbol='exec', | |
2141 | post_execute=False) |
|
2141 | post_execute=False) | |
2142 | if retcode==0: |
|
2142 | if retcode==0: | |
2143 | # And the last expression via runlines so it produces output |
|
2143 | # And the last expression via runlines so it produces output | |
2144 | self.run_one_block(last) |
|
2144 | self.run_one_block(last) | |
2145 | else: |
|
2145 | else: | |
2146 | # Run the whole cell as one entity, storing both raw and |
|
2146 | # Run the whole cell as one entity, storing both raw and | |
2147 | # processed input in history |
|
2147 | # processed input in history | |
2148 | self.run_source(ipy_cell, symbol='exec') |
|
2148 | self.run_source(ipy_cell, symbol='exec') | |
2149 |
|
2149 | |||
2150 | # Each cell is a *single* input, regardless of how many lines it has |
|
2150 | # Each cell is a *single* input, regardless of how many lines it has | |
2151 | self.execution_count += 1 |
|
2151 | self.execution_count += 1 | |
2152 |
|
2152 | |||
2153 | def run_one_block(self, block): |
|
2153 | def run_one_block(self, block): | |
2154 | """Run a single interactive block of source code. |
|
2154 | """Run a single interactive block of source code. | |
2155 |
|
2155 | |||
2156 | If the block is single-line, dynamic transformations are applied to it |
|
2156 | If the block is single-line, dynamic transformations are applied to it | |
2157 | (like automagics, autocall and alias recognition). |
|
2157 | (like automagics, autocall and alias recognition). | |
2158 |
|
2158 | |||
2159 | If the block is multi-line, it must consist of valid Python code only. |
|
2159 | If the block is multi-line, it must consist of valid Python code only. | |
2160 |
|
2160 | |||
2161 | Parameters |
|
2161 | Parameters | |
2162 | ---------- |
|
2162 | ---------- | |
2163 | block : string |
|
2163 | block : string | |
2164 | A (possibly multiline) string of code to be executed. |
|
2164 | A (possibly multiline) string of code to be executed. | |
2165 |
|
2165 | |||
2166 | Returns |
|
2166 | Returns | |
2167 | ------- |
|
2167 | ------- | |
2168 | The output of the underlying execution method used, be it |
|
2168 | The output of the underlying execution method used, be it | |
2169 | :meth:`run_source` or :meth:`run_single_line`. |
|
2169 | :meth:`run_source` or :meth:`run_single_line`. | |
2170 | """ |
|
2170 | """ | |
2171 | if len(block.splitlines()) <= 1: |
|
2171 | if len(block.splitlines()) <= 1: | |
2172 | out = self.run_single_line(block) |
|
2172 | out = self.run_single_line(block) | |
2173 | else: |
|
2173 | else: | |
2174 | # Call run_source, which correctly compiles the input cell. |
|
2174 | # Call run_source, which correctly compiles the input cell. | |
2175 | # run_code must only be called when we know we have a code object, |
|
2175 | # run_code must only be called when we know we have a code object, | |
2176 | # as it does a naked exec and the compilation mode may not be what |
|
2176 | # as it does a naked exec and the compilation mode may not be what | |
2177 | # we wanted. |
|
2177 | # we wanted. | |
2178 | out = self.run_source(block) |
|
2178 | out = self.run_source(block) | |
2179 | return out |
|
2179 | return out | |
2180 |
|
2180 | |||
2181 | def run_single_line(self, line): |
|
2181 | def run_single_line(self, line): | |
2182 | """Run a single-line interactive statement. |
|
2182 | """Run a single-line interactive statement. | |
2183 |
|
2183 | |||
2184 | This assumes the input has been transformed to IPython syntax by |
|
2184 | This assumes the input has been transformed to IPython syntax by | |
2185 | applying all static transformations (those with an explicit prefix like |
|
2185 | applying all static transformations (those with an explicit prefix like | |
2186 | % or !), but it will further try to apply the dynamic ones. |
|
2186 | % or !), but it will further try to apply the dynamic ones. | |
2187 |
|
2187 | |||
2188 | It does not update history. |
|
2188 | It does not update history. | |
2189 | """ |
|
2189 | """ | |
2190 | tline = self.prefilter_manager.prefilter_line(line) |
|
2190 | tline = self.prefilter_manager.prefilter_line(line) | |
2191 | return self.run_source(tline) |
|
2191 | return self.run_source(tline) | |
2192 |
|
2192 | |||
2193 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2193 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2194 | # input logic has been 100% moved to frontends and is stable. |
|
2194 | # input logic has been 100% moved to frontends and is stable. | |
2195 | def runlines(self, lines, clean=False): |
|
2195 | def runlines(self, lines, clean=False): | |
2196 | """Run a string of one or more lines of source. |
|
2196 | """Run a string of one or more lines of source. | |
2197 |
|
2197 | |||
2198 | This method is capable of running a string containing multiple source |
|
2198 | This method is capable of running a string containing multiple source | |
2199 | lines, as if they had been entered at the IPython prompt. Since it |
|
2199 | lines, as if they had been entered at the IPython prompt. Since it | |
2200 | exposes IPython's processing machinery, the given strings can contain |
|
2200 | exposes IPython's processing machinery, the given strings can contain | |
2201 | magic calls (%magic), special shell access (!cmd), etc. |
|
2201 | magic calls (%magic), special shell access (!cmd), etc. | |
2202 | """ |
|
2202 | """ | |
2203 |
|
2203 | |||
2204 | if isinstance(lines, (list, tuple)): |
|
2204 | if isinstance(lines, (list, tuple)): | |
2205 | lines = '\n'.join(lines) |
|
2205 | lines = '\n'.join(lines) | |
2206 |
|
2206 | |||
2207 | if clean: |
|
2207 | if clean: | |
2208 | lines = self._cleanup_ipy_script(lines) |
|
2208 | lines = self._cleanup_ipy_script(lines) | |
2209 |
|
2209 | |||
2210 | # We must start with a clean buffer, in case this is run from an |
|
2210 | # We must start with a clean buffer, in case this is run from an | |
2211 | # interactive IPython session (via a magic, for example). |
|
2211 | # interactive IPython session (via a magic, for example). | |
2212 | self.reset_buffer() |
|
2212 | self.reset_buffer() | |
2213 | lines = lines.splitlines() |
|
2213 | lines = lines.splitlines() | |
2214 |
|
2214 | |||
2215 | # Since we will prefilter all lines, store the user's raw input too |
|
2215 | # Since we will prefilter all lines, store the user's raw input too | |
2216 | # before we apply any transformations |
|
2216 | # before we apply any transformations | |
2217 | self.buffer_raw[:] = [ l+'\n' for l in lines] |
|
2217 | self.buffer_raw[:] = [ l+'\n' for l in lines] | |
2218 |
|
2218 | |||
2219 | more = False |
|
2219 | more = False | |
2220 | prefilter_lines = self.prefilter_manager.prefilter_lines |
|
2220 | prefilter_lines = self.prefilter_manager.prefilter_lines | |
2221 | with nested(self.builtin_trap, self.display_trap): |
|
2221 | with nested(self.builtin_trap, self.display_trap): | |
2222 | for line in lines: |
|
2222 | for line in lines: | |
2223 | # skip blank lines so we don't mess up the prompt counter, but |
|
2223 | # skip blank lines so we don't mess up the prompt counter, but | |
2224 | # do NOT skip even a blank line if we are in a code block (more |
|
2224 | # do NOT skip even a blank line if we are in a code block (more | |
2225 | # is true) |
|
2225 | # is true) | |
2226 |
|
2226 | |||
2227 | if line or more: |
|
2227 | if line or more: | |
2228 | more = self.push_line(prefilter_lines(line, more)) |
|
2228 | more = self.push_line(prefilter_lines(line, more)) | |
2229 | # IPython's run_source returns None if there was an error |
|
2229 | # IPython's run_source returns None if there was an error | |
2230 | # compiling the code. This allows us to stop processing |
|
2230 | # compiling the code. This allows us to stop processing | |
2231 | # right away, so the user gets the error message at the |
|
2231 | # right away, so the user gets the error message at the | |
2232 | # right place. |
|
2232 | # right place. | |
2233 | if more is None: |
|
2233 | if more is None: | |
2234 | break |
|
2234 | break | |
2235 | # final newline in case the input didn't have it, so that the code |
|
2235 | # final newline in case the input didn't have it, so that the code | |
2236 | # actually does get executed |
|
2236 | # actually does get executed | |
2237 | if more: |
|
2237 | if more: | |
2238 | self.push_line('\n') |
|
2238 | self.push_line('\n') | |
2239 |
|
2239 | |||
2240 | def run_source(self, source, filename=None, |
|
2240 | def run_source(self, source, filename=None, | |
2241 | symbol='single', post_execute=True): |
|
2241 | symbol='single', post_execute=True): | |
2242 | """Compile and run some source in the interpreter. |
|
2242 | """Compile and run some source in the interpreter. | |
2243 |
|
2243 | |||
2244 | Arguments are as for compile_command(). |
|
2244 | Arguments are as for compile_command(). | |
2245 |
|
2245 | |||
2246 | One several things can happen: |
|
2246 | One several things can happen: | |
2247 |
|
2247 | |||
2248 | 1) The input is incorrect; compile_command() raised an |
|
2248 | 1) The input is incorrect; compile_command() raised an | |
2249 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2249 | exception (SyntaxError or OverflowError). A syntax traceback | |
2250 | will be printed by calling the showsyntaxerror() method. |
|
2250 | will be printed by calling the showsyntaxerror() method. | |
2251 |
|
2251 | |||
2252 | 2) The input is incomplete, and more input is required; |
|
2252 | 2) The input is incomplete, and more input is required; | |
2253 | compile_command() returned None. Nothing happens. |
|
2253 | compile_command() returned None. Nothing happens. | |
2254 |
|
2254 | |||
2255 | 3) The input is complete; compile_command() returned a code |
|
2255 | 3) The input is complete; compile_command() returned a code | |
2256 | object. The code is executed by calling self.run_code() (which |
|
2256 | object. The code is executed by calling self.run_code() (which | |
2257 | also handles run-time exceptions, except for SystemExit). |
|
2257 | also handles run-time exceptions, except for SystemExit). | |
2258 |
|
2258 | |||
2259 | The return value is: |
|
2259 | The return value is: | |
2260 |
|
2260 | |||
2261 | - True in case 2 |
|
2261 | - True in case 2 | |
2262 |
|
2262 | |||
2263 | - False in the other cases, unless an exception is raised, where |
|
2263 | - False in the other cases, unless an exception is raised, where | |
2264 | None is returned instead. This can be used by external callers to |
|
2264 | None is returned instead. This can be used by external callers to | |
2265 | know whether to continue feeding input or not. |
|
2265 | know whether to continue feeding input or not. | |
2266 |
|
2266 | |||
2267 | The return value can be used to decide whether to use sys.ps1 or |
|
2267 | The return value can be used to decide whether to use sys.ps1 or | |
2268 | sys.ps2 to prompt the next line.""" |
|
2268 | sys.ps2 to prompt the next line.""" | |
2269 |
|
2269 | |||
2270 | # We need to ensure that the source is unicode from here on. |
|
2270 | # We need to ensure that the source is unicode from here on. | |
2271 | if type(source)==str: |
|
2271 | if type(source)==str: | |
2272 | usource = source.decode(self.stdin_encoding) |
|
2272 | usource = source.decode(self.stdin_encoding) | |
2273 | else: |
|
2273 | else: | |
2274 | usource = source |
|
2274 | usource = source | |
2275 |
|
2275 | |||
2276 | if 0: # dbg |
|
2276 | if 0: # dbg | |
2277 | print 'Source:', repr(source) # dbg |
|
2277 | print 'Source:', repr(source) # dbg | |
2278 | print 'USource:', repr(usource) # dbg |
|
2278 | print 'USource:', repr(usource) # dbg | |
2279 | print 'type:', type(source) # dbg |
|
2279 | print 'type:', type(source) # dbg | |
2280 | print 'encoding', self.stdin_encoding # dbg |
|
2280 | print 'encoding', self.stdin_encoding # dbg | |
2281 |
|
2281 | |||
2282 | try: |
|
2282 | try: | |
2283 | code = self.compile(usource, symbol, self.execution_count) |
|
2283 | code = self.compile(usource, symbol, self.execution_count) | |
2284 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2284 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2285 | # Case 1 |
|
2285 | # Case 1 | |
2286 | self.showsyntaxerror(filename) |
|
2286 | self.showsyntaxerror(filename) | |
2287 | return None |
|
2287 | return None | |
2288 |
|
2288 | |||
2289 | if code is None: |
|
2289 | if code is None: | |
2290 | # Case 2 |
|
2290 | # Case 2 | |
2291 | return True |
|
2291 | return True | |
2292 |
|
2292 | |||
2293 | # Case 3 |
|
2293 | # Case 3 | |
2294 | # We store the code object so that threaded shells and |
|
2294 | # We store the code object so that threaded shells and | |
2295 | # custom exception handlers can access all this info if needed. |
|
2295 | # custom exception handlers can access all this info if needed. | |
2296 | # The source corresponding to this can be obtained from the |
|
2296 | # The source corresponding to this can be obtained from the | |
2297 | # buffer attribute as '\n'.join(self.buffer). |
|
2297 | # buffer attribute as '\n'.join(self.buffer). | |
2298 | self.code_to_run = code |
|
2298 | self.code_to_run = code | |
2299 | # now actually execute the code object |
|
2299 | # now actually execute the code object | |
2300 | if self.run_code(code, post_execute) == 0: |
|
2300 | if self.run_code(code, post_execute) == 0: | |
2301 | return False |
|
2301 | return False | |
2302 | else: |
|
2302 | else: | |
2303 | return None |
|
2303 | return None | |
2304 |
|
2304 | |||
2305 | # For backwards compatibility |
|
2305 | # For backwards compatibility | |
2306 | runsource = run_source |
|
2306 | runsource = run_source | |
2307 |
|
2307 | |||
2308 | def run_code(self, code_obj, post_execute=True): |
|
2308 | def run_code(self, code_obj, post_execute=True): | |
2309 | """Execute a code object. |
|
2309 | """Execute a code object. | |
2310 |
|
2310 | |||
2311 | When an exception occurs, self.showtraceback() is called to display a |
|
2311 | When an exception occurs, self.showtraceback() is called to display a | |
2312 | traceback. |
|
2312 | traceback. | |
2313 |
|
2313 | |||
2314 | Return value: a flag indicating whether the code to be run completed |
|
2314 | Return value: a flag indicating whether the code to be run completed | |
2315 | successfully: |
|
2315 | successfully: | |
2316 |
|
2316 | |||
2317 | - 0: successful execution. |
|
2317 | - 0: successful execution. | |
2318 | - 1: an error occurred. |
|
2318 | - 1: an error occurred. | |
2319 | """ |
|
2319 | """ | |
2320 |
|
2320 | |||
2321 | # Set our own excepthook in case the user code tries to call it |
|
2321 | # Set our own excepthook in case the user code tries to call it | |
2322 | # directly, so that the IPython crash handler doesn't get triggered |
|
2322 | # directly, so that the IPython crash handler doesn't get triggered | |
2323 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2323 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2324 |
|
2324 | |||
2325 | # we save the original sys.excepthook in the instance, in case config |
|
2325 | # we save the original sys.excepthook in the instance, in case config | |
2326 | # code (such as magics) needs access to it. |
|
2326 | # code (such as magics) needs access to it. | |
2327 | self.sys_excepthook = old_excepthook |
|
2327 | self.sys_excepthook = old_excepthook | |
2328 | outflag = 1 # happens in more places, so it's easier as default |
|
2328 | outflag = 1 # happens in more places, so it's easier as default | |
2329 | try: |
|
2329 | try: | |
2330 | try: |
|
2330 | try: | |
2331 | self.hooks.pre_run_code_hook() |
|
2331 | self.hooks.pre_run_code_hook() | |
2332 | #rprint('Running code', repr(code_obj)) # dbg |
|
2332 | #rprint('Running code', repr(code_obj)) # dbg | |
2333 | exec code_obj in self.user_global_ns, self.user_ns |
|
2333 | exec code_obj in self.user_global_ns, self.user_ns | |
2334 | finally: |
|
2334 | finally: | |
2335 | # Reset our crash handler in place |
|
2335 | # Reset our crash handler in place | |
2336 | sys.excepthook = old_excepthook |
|
2336 | sys.excepthook = old_excepthook | |
2337 | except SystemExit: |
|
2337 | except SystemExit: | |
2338 | self.reset_buffer() |
|
2338 | self.reset_buffer() | |
2339 | self.showtraceback(exception_only=True) |
|
2339 | self.showtraceback(exception_only=True) | |
2340 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2340 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2341 | except self.custom_exceptions: |
|
2341 | except self.custom_exceptions: | |
2342 | etype,value,tb = sys.exc_info() |
|
2342 | etype,value,tb = sys.exc_info() | |
2343 | self.CustomTB(etype,value,tb) |
|
2343 | self.CustomTB(etype,value,tb) | |
2344 | except: |
|
2344 | except: | |
2345 | self.showtraceback() |
|
2345 | self.showtraceback() | |
2346 | else: |
|
2346 | else: | |
2347 | outflag = 0 |
|
2347 | outflag = 0 | |
2348 | if softspace(sys.stdout, 0): |
|
2348 | if softspace(sys.stdout, 0): | |
2349 |
|
2349 | |||
2350 |
|
2350 | |||
2351 | # Execute any registered post-execution functions. Here, any errors |
|
2351 | # Execute any registered post-execution functions. Here, any errors | |
2352 | # are reported only minimally and just on the terminal, because the |
|
2352 | # are reported only minimally and just on the terminal, because the | |
2353 | # main exception channel may be occupied with a user traceback. |
|
2353 | # main exception channel may be occupied with a user traceback. | |
2354 | # FIXME: we need to think this mechanism a little more carefully. |
|
2354 | # FIXME: we need to think this mechanism a little more carefully. | |
2355 | if post_execute: |
|
2355 | if post_execute: | |
2356 | for func in self._post_execute: |
|
2356 | for func in self._post_execute: | |
2357 | try: |
|
2357 | try: | |
2358 | func() |
|
2358 | func() | |
2359 | except: |
|
2359 | except: | |
2360 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ |
|
2360 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ | |
2361 | func |
|
2361 | func | |
2362 | print >> io.Term.cout, head |
|
2362 | print >> io.Term.cout, head | |
2363 | print >> io.Term.cout, self._simple_error() |
|
2363 | print >> io.Term.cout, self._simple_error() | |
2364 | print >> io.Term.cout, 'Removing from post_execute' |
|
2364 | print >> io.Term.cout, 'Removing from post_execute' | |
2365 | self._post_execute.remove(func) |
|
2365 | self._post_execute.remove(func) | |
2366 |
|
2366 | |||
2367 | # Flush out code object which has been run (and source) |
|
2367 | # Flush out code object which has been run (and source) | |
2368 | self.code_to_run = None |
|
2368 | self.code_to_run = None | |
2369 | return outflag |
|
2369 | return outflag | |
2370 |
|
2370 | |||
2371 | # For backwards compatibility |
|
2371 | # For backwards compatibility | |
2372 | runcode = run_code |
|
2372 | runcode = run_code | |
2373 |
|
2373 | |||
2374 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2374 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2375 | # input logic has been 100% moved to frontends and is stable. |
|
2375 | # input logic has been 100% moved to frontends and is stable. | |
2376 | def push_line(self, line): |
|
2376 | def push_line(self, line): | |
2377 | """Push a line to the interpreter. |
|
2377 | """Push a line to the interpreter. | |
2378 |
|
2378 | |||
2379 | The line should not have a trailing newline; it may have |
|
2379 | The line should not have a trailing newline; it may have | |
2380 | internal newlines. The line is appended to a buffer and the |
|
2380 | internal newlines. The line is appended to a buffer and the | |
2381 | interpreter's run_source() method is called with the |
|
2381 | interpreter's run_source() method is called with the | |
2382 | concatenated contents of the buffer as source. If this |
|
2382 | concatenated contents of the buffer as source. If this | |
2383 | indicates that the command was executed or invalid, the buffer |
|
2383 | indicates that the command was executed or invalid, the buffer | |
2384 | is reset; otherwise, the command is incomplete, and the buffer |
|
2384 | is reset; otherwise, the command is incomplete, and the buffer | |
2385 | is left as it was after the line was appended. The return |
|
2385 | is left as it was after the line was appended. The return | |
2386 | value is 1 if more input is required, 0 if the line was dealt |
|
2386 | value is 1 if more input is required, 0 if the line was dealt | |
2387 | with in some way (this is the same as run_source()). |
|
2387 | with in some way (this is the same as run_source()). | |
2388 | """ |
|
2388 | """ | |
2389 |
|
2389 | |||
2390 | # autoindent management should be done here, and not in the |
|
2390 | # autoindent management should be done here, and not in the | |
2391 | # interactive loop, since that one is only seen by keyboard input. We |
|
2391 | # interactive loop, since that one is only seen by keyboard input. We | |
2392 | # need this done correctly even for code run via runlines (which uses |
|
2392 | # need this done correctly even for code run via runlines (which uses | |
2393 | # push). |
|
2393 | # push). | |
2394 |
|
2394 | |||
2395 | #print 'push line: <%s>' % line # dbg |
|
2395 | #print 'push line: <%s>' % line # dbg | |
2396 | self.buffer.append(line) |
|
2396 | self.buffer.append(line) | |
2397 | full_source = '\n'.join(self.buffer) |
|
2397 | full_source = '\n'.join(self.buffer) | |
2398 | more = self.run_source(full_source, self.filename) |
|
2398 | more = self.run_source(full_source, self.filename) | |
2399 | if not more: |
|
2399 | if not more: | |
2400 | self.history_manager.store_inputs('\n'.join(self.buffer_raw), |
|
2400 | self.history_manager.store_inputs('\n'.join(self.buffer_raw), | |
2401 | full_source) |
|
2401 | full_source) | |
2402 | self.reset_buffer() |
|
2402 | self.reset_buffer() | |
2403 | self.execution_count += 1 |
|
2403 | self.execution_count += 1 | |
2404 | return more |
|
2404 | return more | |
2405 |
|
2405 | |||
2406 | def reset_buffer(self): |
|
2406 | def reset_buffer(self): | |
2407 | """Reset the input buffer.""" |
|
2407 | """Reset the input buffer.""" | |
2408 | self.buffer[:] = [] |
|
2408 | self.buffer[:] = [] | |
2409 | self.buffer_raw[:] = [] |
|
2409 | self.buffer_raw[:] = [] | |
2410 | self.input_splitter.reset() |
|
2410 | self.input_splitter.reset() | |
2411 |
|
2411 | |||
2412 | # For backwards compatibility |
|
2412 | # For backwards compatibility | |
2413 | resetbuffer = reset_buffer |
|
2413 | resetbuffer = reset_buffer | |
2414 |
|
2414 | |||
2415 | def _is_secondary_block_start(self, s): |
|
2415 | def _is_secondary_block_start(self, s): | |
2416 | if not s.endswith(':'): |
|
2416 | if not s.endswith(':'): | |
2417 | return False |
|
2417 | return False | |
2418 | if (s.startswith('elif') or |
|
2418 | if (s.startswith('elif') or | |
2419 | s.startswith('else') or |
|
2419 | s.startswith('else') or | |
2420 | s.startswith('except') or |
|
2420 | s.startswith('except') or | |
2421 | s.startswith('finally')): |
|
2421 | s.startswith('finally')): | |
2422 | return True |
|
2422 | return True | |
2423 |
|
2423 | |||
2424 | def _cleanup_ipy_script(self, script): |
|
2424 | def _cleanup_ipy_script(self, script): | |
2425 | """Make a script safe for self.runlines() |
|
2425 | """Make a script safe for self.runlines() | |
2426 |
|
2426 | |||
2427 | Currently, IPython is lines based, with blocks being detected by |
|
2427 | Currently, IPython is lines based, with blocks being detected by | |
2428 | empty lines. This is a problem for block based scripts that may |
|
2428 | empty lines. This is a problem for block based scripts that may | |
2429 | not have empty lines after blocks. This script adds those empty |
|
2429 | not have empty lines after blocks. This script adds those empty | |
2430 | lines to make scripts safe for running in the current line based |
|
2430 | lines to make scripts safe for running in the current line based | |
2431 | IPython. |
|
2431 | IPython. | |
2432 | """ |
|
2432 | """ | |
2433 | res = [] |
|
2433 | res = [] | |
2434 | lines = script.splitlines() |
|
2434 | lines = script.splitlines() | |
2435 | level = 0 |
|
2435 | level = 0 | |
2436 |
|
2436 | |||
2437 | for l in lines: |
|
2437 | for l in lines: | |
2438 | lstripped = l.lstrip() |
|
2438 | lstripped = l.lstrip() | |
2439 | stripped = l.strip() |
|
2439 | stripped = l.strip() | |
2440 | if not stripped: |
|
2440 | if not stripped: | |
2441 | continue |
|
2441 | continue | |
2442 | newlevel = len(l) - len(lstripped) |
|
2442 | newlevel = len(l) - len(lstripped) | |
2443 | if level > 0 and newlevel == 0 and \ |
|
2443 | if level > 0 and newlevel == 0 and \ | |
2444 | not self._is_secondary_block_start(stripped): |
|
2444 | not self._is_secondary_block_start(stripped): | |
2445 | # add empty line |
|
2445 | # add empty line | |
2446 | res.append('') |
|
2446 | res.append('') | |
2447 | res.append(l) |
|
2447 | res.append(l) | |
2448 | level = newlevel |
|
2448 | level = newlevel | |
2449 |
|
2449 | |||
2450 | return '\n'.join(res) + '\n' |
|
2450 | return '\n'.join(res) + '\n' | |
2451 |
|
2451 | |||
2452 | #------------------------------------------------------------------------- |
|
2452 | #------------------------------------------------------------------------- | |
2453 | # Things related to GUI support and pylab |
|
2453 | # Things related to GUI support and pylab | |
2454 | #------------------------------------------------------------------------- |
|
2454 | #------------------------------------------------------------------------- | |
2455 |
|
2455 | |||
2456 | def enable_pylab(self, gui=None): |
|
2456 | def enable_pylab(self, gui=None): | |
2457 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2457 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2458 |
|
2458 | |||
2459 | #------------------------------------------------------------------------- |
|
2459 | #------------------------------------------------------------------------- | |
2460 | # Utilities |
|
2460 | # Utilities | |
2461 | #------------------------------------------------------------------------- |
|
2461 | #------------------------------------------------------------------------- | |
2462 |
|
2462 | |||
2463 | def var_expand(self,cmd,depth=0): |
|
2463 | def var_expand(self,cmd,depth=0): | |
2464 | """Expand python variables in a string. |
|
2464 | """Expand python variables in a string. | |
2465 |
|
2465 | |||
2466 | The depth argument indicates how many frames above the caller should |
|
2466 | The depth argument indicates how many frames above the caller should | |
2467 | be walked to look for the local namespace where to expand variables. |
|
2467 | be walked to look for the local namespace where to expand variables. | |
2468 |
|
2468 | |||
2469 | The global namespace for expansion is always the user's interactive |
|
2469 | The global namespace for expansion is always the user's interactive | |
2470 | namespace. |
|
2470 | namespace. | |
2471 | """ |
|
2471 | """ | |
2472 |
|
2472 | |||
2473 | return str(ItplNS(cmd, |
|
2473 | return str(ItplNS(cmd, | |
2474 | self.user_ns, # globals |
|
2474 | self.user_ns, # globals | |
2475 | # Skip our own frame in searching for locals: |
|
2475 | # Skip our own frame in searching for locals: | |
2476 | sys._getframe(depth+1).f_locals # locals |
|
2476 | sys._getframe(depth+1).f_locals # locals | |
2477 | )) |
|
2477 | )) | |
2478 |
|
2478 | |||
2479 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2479 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2480 | """Make a new tempfile and return its filename. |
|
2480 | """Make a new tempfile and return its filename. | |
2481 |
|
2481 | |||
2482 | This makes a call to tempfile.mktemp, but it registers the created |
|
2482 | This makes a call to tempfile.mktemp, but it registers the created | |
2483 | filename internally so ipython cleans it up at exit time. |
|
2483 | filename internally so ipython cleans it up at exit time. | |
2484 |
|
2484 | |||
2485 | Optional inputs: |
|
2485 | Optional inputs: | |
2486 |
|
2486 | |||
2487 | - data(None): if data is given, it gets written out to the temp file |
|
2487 | - data(None): if data is given, it gets written out to the temp file | |
2488 | immediately, and the file is closed again.""" |
|
2488 | immediately, and the file is closed again.""" | |
2489 |
|
2489 | |||
2490 | filename = tempfile.mktemp('.py', prefix) |
|
2490 | filename = tempfile.mktemp('.py', prefix) | |
2491 | self.tempfiles.append(filename) |
|
2491 | self.tempfiles.append(filename) | |
2492 |
|
2492 | |||
2493 | if data: |
|
2493 | if data: | |
2494 | tmp_file = open(filename,'w') |
|
2494 | tmp_file = open(filename,'w') | |
2495 | tmp_file.write(data) |
|
2495 | tmp_file.write(data) | |
2496 | tmp_file.close() |
|
2496 | tmp_file.close() | |
2497 | return filename |
|
2497 | return filename | |
2498 |
|
2498 | |||
2499 | # TODO: This should be removed when Term is refactored. |
|
2499 | # TODO: This should be removed when Term is refactored. | |
2500 | def write(self,data): |
|
2500 | def write(self,data): | |
2501 | """Write a string to the default output""" |
|
2501 | """Write a string to the default output""" | |
2502 | io.Term.cout.write(data) |
|
2502 | io.Term.cout.write(data) | |
2503 |
|
2503 | |||
2504 | # TODO: This should be removed when Term is refactored. |
|
2504 | # TODO: This should be removed when Term is refactored. | |
2505 | def write_err(self,data): |
|
2505 | def write_err(self,data): | |
2506 | """Write a string to the default error output""" |
|
2506 | """Write a string to the default error output""" | |
2507 | io.Term.cerr.write(data) |
|
2507 | io.Term.cerr.write(data) | |
2508 |
|
2508 | |||
2509 | def ask_yes_no(self,prompt,default=True): |
|
2509 | def ask_yes_no(self,prompt,default=True): | |
2510 | if self.quiet: |
|
2510 | if self.quiet: | |
2511 | return True |
|
2511 | return True | |
2512 | return ask_yes_no(prompt,default) |
|
2512 | return ask_yes_no(prompt,default) | |
2513 |
|
2513 | |||
2514 | def show_usage(self): |
|
2514 | def show_usage(self): | |
2515 | """Show a usage message""" |
|
2515 | """Show a usage message""" | |
2516 | page.page(IPython.core.usage.interactive_usage) |
|
2516 | page.page(IPython.core.usage.interactive_usage) | |
2517 |
|
2517 | |||
2518 | #------------------------------------------------------------------------- |
|
2518 | #------------------------------------------------------------------------- | |
2519 | # Things related to IPython exiting |
|
2519 | # Things related to IPython exiting | |
2520 | #------------------------------------------------------------------------- |
|
2520 | #------------------------------------------------------------------------- | |
2521 | def atexit_operations(self): |
|
2521 | def atexit_operations(self): | |
2522 | """This will be executed at the time of exit. |
|
2522 | """This will be executed at the time of exit. | |
2523 |
|
2523 | |||
2524 | Cleanup operations and saving of persistent data that is done |
|
2524 | Cleanup operations and saving of persistent data that is done | |
2525 | unconditionally by IPython should be performed here. |
|
2525 | unconditionally by IPython should be performed here. | |
2526 |
|
2526 | |||
2527 | For things that may depend on startup flags or platform specifics (such |
|
2527 | For things that may depend on startup flags or platform specifics (such | |
2528 | as having readline or not), register a separate atexit function in the |
|
2528 | as having readline or not), register a separate atexit function in the | |
2529 | code that has the appropriate information, rather than trying to |
|
2529 | code that has the appropriate information, rather than trying to | |
2530 | clutter |
|
2530 | clutter | |
2531 | """ |
|
2531 | """ | |
2532 | # Cleanup all tempfiles left around |
|
2532 | # Cleanup all tempfiles left around | |
2533 | for tfile in self.tempfiles: |
|
2533 | for tfile in self.tempfiles: | |
2534 | try: |
|
2534 | try: | |
2535 | os.unlink(tfile) |
|
2535 | os.unlink(tfile) | |
2536 | except OSError: |
|
2536 | except OSError: | |
2537 | pass |
|
2537 | pass | |
2538 |
|
2538 | |||
2539 | self.save_history() |
|
2539 | self.save_history() | |
2540 |
|
2540 | |||
2541 | # Clear all user namespaces to release all references cleanly. |
|
2541 | # Clear all user namespaces to release all references cleanly. | |
2542 | self.reset() |
|
2542 | self.reset() | |
2543 |
|
2543 | |||
2544 | # Run user hooks |
|
2544 | # Run user hooks | |
2545 | self.hooks.shutdown_hook() |
|
2545 | self.hooks.shutdown_hook() | |
2546 |
|
2546 | |||
2547 | def cleanup(self): |
|
2547 | def cleanup(self): | |
2548 | self.restore_sys_module_state() |
|
2548 | self.restore_sys_module_state() | |
2549 |
|
2549 | |||
2550 |
|
2550 | |||
2551 | class InteractiveShellABC(object): |
|
2551 | class InteractiveShellABC(object): | |
2552 | """An abstract base class for InteractiveShell.""" |
|
2552 | """An abstract base class for InteractiveShell.""" | |
2553 | __metaclass__ = abc.ABCMeta |
|
2553 | __metaclass__ = abc.ABCMeta | |
2554 |
|
2554 | |||
2555 | InteractiveShellABC.register(InteractiveShell) |
|
2555 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,493 +1,494 b'' | |||||
1 | """ A FrontendWidget that emulates the interface of the console IPython and |
|
1 | """ A FrontendWidget that emulates the interface of the console IPython and | |
2 | supports the additional functionality provided by the IPython kernel. |
|
2 | supports the additional functionality provided by the IPython kernel. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Imports |
|
6 | # Imports | |
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 |
|
8 | |||
9 | # Standard library imports |
|
9 | # Standard library imports | |
10 | from collections import namedtuple |
|
10 | from collections import namedtuple | |
11 | import re |
|
11 | import re | |
12 | from subprocess import Popen |
|
12 | from subprocess import Popen | |
13 | from textwrap import dedent |
|
13 | from textwrap import dedent | |
14 |
|
14 | |||
15 | # System library imports |
|
15 | # System library imports | |
16 | from IPython.external.qt import QtCore, QtGui |
|
16 | from IPython.external.qt import QtCore, QtGui | |
17 |
|
17 | |||
18 | # Local imports |
|
18 | # Local imports | |
19 | from IPython.core.inputsplitter import IPythonInputSplitter, \ |
|
19 | from IPython.core.inputsplitter import IPythonInputSplitter, \ | |
20 | transform_ipy_prompt |
|
20 | transform_ipy_prompt | |
21 | from IPython.core.usage import default_gui_banner |
|
21 | from IPython.core.usage import default_gui_banner | |
22 | from IPython.utils.traitlets import Bool, Str |
|
22 | from IPython.utils.traitlets import Bool, Str | |
23 | from frontend_widget import FrontendWidget |
|
23 | from frontend_widget import FrontendWidget | |
24 | from styles import (default_light_style_sheet, default_light_syntax_style, |
|
24 | from styles import (default_light_style_sheet, default_light_syntax_style, | |
25 | default_dark_style_sheet, default_dark_syntax_style, |
|
25 | default_dark_style_sheet, default_dark_syntax_style, | |
26 | default_bw_style_sheet, default_bw_syntax_style) |
|
26 | default_bw_style_sheet, default_bw_syntax_style) | |
27 |
|
27 | |||
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 | # Constants |
|
29 | # Constants | |
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 |
|
31 | |||
32 | # Default strings to build and display input and output prompts (and separators |
|
32 | # Default strings to build and display input and output prompts (and separators | |
33 | # in between) |
|
33 | # in between) | |
34 | default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' |
|
34 | default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' | |
35 | default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' |
|
35 | default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' | |
36 | default_input_sep = '\n' |
|
36 | default_input_sep = '\n' | |
37 | default_output_sep = '' |
|
37 | default_output_sep = '' | |
38 | default_output_sep2 = '' |
|
38 | default_output_sep2 = '' | |
39 |
|
39 | |||
40 | # Base path for most payload sources. |
|
40 | # Base path for most payload sources. | |
41 | zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell' |
|
41 | zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell' | |
42 |
|
42 | |||
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 | # IPythonWidget class |
|
44 | # IPythonWidget class | |
45 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
46 |
|
46 | |||
47 | class IPythonWidget(FrontendWidget): |
|
47 | class IPythonWidget(FrontendWidget): | |
48 | """ A FrontendWidget for an IPython kernel. |
|
48 | """ A FrontendWidget for an IPython kernel. | |
49 | """ |
|
49 | """ | |
50 |
|
50 | |||
51 | # If set, the 'custom_edit_requested(str, int)' signal will be emitted when |
|
51 | # If set, the 'custom_edit_requested(str, int)' signal will be emitted when | |
52 | # an editor is needed for a file. This overrides 'editor' and 'editor_line' |
|
52 | # an editor is needed for a file. This overrides 'editor' and 'editor_line' | |
53 | # settings. |
|
53 | # settings. | |
54 | custom_edit = Bool(False) |
|
54 | custom_edit = Bool(False) | |
55 | custom_edit_requested = QtCore.Signal(object, object) |
|
55 | custom_edit_requested = QtCore.Signal(object, object) | |
56 |
|
56 | |||
57 | # A command for invoking a system text editor. If the string contains a |
|
57 | # A command for invoking a system text editor. If the string contains a | |
58 | # {filename} format specifier, it will be used. Otherwise, the filename will |
|
58 | # {filename} format specifier, it will be used. Otherwise, the filename will | |
59 | # be appended to the end the command. |
|
59 | # be appended to the end the command. | |
60 | editor = Str('default', config=True) |
|
60 | editor = Str('default', config=True) | |
61 |
|
61 | |||
62 | # The editor command to use when a specific line number is requested. The |
|
62 | # The editor command to use when a specific line number is requested. The | |
63 | # string should contain two format specifiers: {line} and {filename}. If |
|
63 | # string should contain two format specifiers: {line} and {filename}. If | |
64 | # this parameter is not specified, the line number option to the %edit magic |
|
64 | # this parameter is not specified, the line number option to the %edit magic | |
65 | # will be ignored. |
|
65 | # will be ignored. | |
66 | editor_line = Str(config=True) |
|
66 | editor_line = Str(config=True) | |
67 |
|
67 | |||
68 | # A CSS stylesheet. The stylesheet can contain classes for: |
|
68 | # A CSS stylesheet. The stylesheet can contain classes for: | |
69 | # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc |
|
69 | # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc | |
70 | # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter) |
|
70 | # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter) | |
71 | # 3. IPython: .error, .in-prompt, .out-prompt, etc |
|
71 | # 3. IPython: .error, .in-prompt, .out-prompt, etc | |
72 | style_sheet = Str(config=True) |
|
72 | style_sheet = Str(config=True) | |
73 |
|
73 | |||
74 | # If not empty, use this Pygments style for syntax highlighting. Otherwise, |
|
74 | # If not empty, use this Pygments style for syntax highlighting. Otherwise, | |
75 | # the style sheet is queried for Pygments style information. |
|
75 | # the style sheet is queried for Pygments style information. | |
76 | syntax_style = Str(config=True) |
|
76 | syntax_style = Str(config=True) | |
77 |
|
77 | |||
78 | # Prompts. |
|
78 | # Prompts. | |
79 | in_prompt = Str(default_in_prompt, config=True) |
|
79 | in_prompt = Str(default_in_prompt, config=True) | |
80 | out_prompt = Str(default_out_prompt, config=True) |
|
80 | out_prompt = Str(default_out_prompt, config=True) | |
81 | input_sep = Str(default_input_sep, config=True) |
|
81 | input_sep = Str(default_input_sep, config=True) | |
82 | output_sep = Str(default_output_sep, config=True) |
|
82 | output_sep = Str(default_output_sep, config=True) | |
83 | output_sep2 = Str(default_output_sep2, config=True) |
|
83 | output_sep2 = Str(default_output_sep2, config=True) | |
84 |
|
84 | |||
85 | # FrontendWidget protected class variables. |
|
85 | # FrontendWidget protected class variables. | |
86 | _input_splitter_class = IPythonInputSplitter |
|
86 | _input_splitter_class = IPythonInputSplitter | |
87 |
|
87 | |||
88 | # IPythonWidget protected class variables. |
|
88 | # IPythonWidget protected class variables. | |
89 | _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number']) |
|
89 | _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number']) | |
90 | _payload_source_edit = zmq_shell_source + '.edit_magic' |
|
90 | _payload_source_edit = zmq_shell_source + '.edit_magic' | |
91 | _payload_source_exit = zmq_shell_source + '.ask_exit' |
|
91 | _payload_source_exit = zmq_shell_source + '.ask_exit' | |
92 | _payload_source_loadpy = zmq_shell_source + '.magic_loadpy' |
|
92 | _payload_source_loadpy = zmq_shell_source + '.magic_loadpy' | |
93 | _payload_source_page = 'IPython.zmq.page.page' |
|
93 | _payload_source_page = 'IPython.zmq.page.page' | |
94 |
|
94 | |||
95 | #--------------------------------------------------------------------------- |
|
95 | #--------------------------------------------------------------------------- | |
96 | # 'object' interface |
|
96 | # 'object' interface | |
97 | #--------------------------------------------------------------------------- |
|
97 | #--------------------------------------------------------------------------- | |
98 |
|
98 | |||
99 | def __init__(self, *args, **kw): |
|
99 | def __init__(self, *args, **kw): | |
100 | super(IPythonWidget, self).__init__(*args, **kw) |
|
100 | super(IPythonWidget, self).__init__(*args, **kw) | |
101 |
|
101 | |||
102 | # IPythonWidget protected variables. |
|
102 | # IPythonWidget protected variables. | |
103 | self._code_to_load = None |
|
103 | self._code_to_load = None | |
104 | self._payload_handlers = { |
|
104 | self._payload_handlers = { | |
105 | self._payload_source_edit : self._handle_payload_edit, |
|
105 | self._payload_source_edit : self._handle_payload_edit, | |
106 | self._payload_source_exit : self._handle_payload_exit, |
|
106 | self._payload_source_exit : self._handle_payload_exit, | |
107 | self._payload_source_page : self._handle_payload_page, |
|
107 | self._payload_source_page : self._handle_payload_page, | |
108 | self._payload_source_loadpy : self._handle_payload_loadpy } |
|
108 | self._payload_source_loadpy : self._handle_payload_loadpy } | |
109 | self._previous_prompt_obj = None |
|
109 | self._previous_prompt_obj = None | |
110 | self._keep_kernel_on_exit = None |
|
110 | self._keep_kernel_on_exit = None | |
111 |
|
111 | |||
112 | # Initialize widget styling. |
|
112 | # Initialize widget styling. | |
113 | if self.style_sheet: |
|
113 | if self.style_sheet: | |
114 | self._style_sheet_changed() |
|
114 | self._style_sheet_changed() | |
115 | self._syntax_style_changed() |
|
115 | self._syntax_style_changed() | |
116 | else: |
|
116 | else: | |
117 | self.set_default_style() |
|
117 | self.set_default_style() | |
118 |
|
118 | |||
119 | #--------------------------------------------------------------------------- |
|
119 | #--------------------------------------------------------------------------- | |
120 | # 'BaseFrontendMixin' abstract interface |
|
120 | # 'BaseFrontendMixin' abstract interface | |
121 | #--------------------------------------------------------------------------- |
|
121 | #--------------------------------------------------------------------------- | |
122 |
|
122 | |||
123 | def _handle_complete_reply(self, rep): |
|
123 | def _handle_complete_reply(self, rep): | |
124 | """ Reimplemented to support IPython's improved completion machinery. |
|
124 | """ Reimplemented to support IPython's improved completion machinery. | |
125 | """ |
|
125 | """ | |
126 | cursor = self._get_cursor() |
|
126 | cursor = self._get_cursor() | |
127 | info = self._request_info.get('complete') |
|
127 | info = self._request_info.get('complete') | |
128 | if info and info.id == rep['parent_header']['msg_id'] and \ |
|
128 | if info and info.id == rep['parent_header']['msg_id'] and \ | |
129 | info.pos == cursor.position(): |
|
129 | info.pos == cursor.position(): | |
130 | matches = rep['content']['matches'] |
|
130 | matches = rep['content']['matches'] | |
131 | text = rep['content']['matched_text'] |
|
131 | text = rep['content']['matched_text'] | |
132 | offset = len(text) |
|
132 | offset = len(text) | |
133 |
|
133 | |||
134 | # Clean up matches with period and path separators if the matched |
|
134 | # Clean up matches with period and path separators if the matched | |
135 | # text has not been transformed. This is done by truncating all |
|
135 | # text has not been transformed. This is done by truncating all | |
136 | # but the last component and then suitably decreasing the offset |
|
136 | # but the last component and then suitably decreasing the offset | |
137 | # between the current cursor position and the start of completion. |
|
137 | # between the current cursor position and the start of completion. | |
138 | if len(matches) > 1 and matches[0][:offset] == text: |
|
138 | if len(matches) > 1 and matches[0][:offset] == text: | |
139 | parts = re.split(r'[./\\]', text) |
|
139 | parts = re.split(r'[./\\]', text) | |
140 | sep_count = len(parts) - 1 |
|
140 | sep_count = len(parts) - 1 | |
141 | if sep_count: |
|
141 | if sep_count: | |
142 | chop_length = sum(map(len, parts[:sep_count])) + sep_count |
|
142 | chop_length = sum(map(len, parts[:sep_count])) + sep_count | |
143 | matches = [ match[chop_length:] for match in matches ] |
|
143 | matches = [ match[chop_length:] for match in matches ] | |
144 | offset -= chop_length |
|
144 | offset -= chop_length | |
145 |
|
145 | |||
146 | # Move the cursor to the start of the match and complete. |
|
146 | # Move the cursor to the start of the match and complete. | |
147 | cursor.movePosition(QtGui.QTextCursor.Left, n=offset) |
|
147 | cursor.movePosition(QtGui.QTextCursor.Left, n=offset) | |
148 | self._complete_with_items(cursor, matches) |
|
148 | self._complete_with_items(cursor, matches) | |
149 |
|
149 | |||
150 | def _handle_execute_reply(self, msg): |
|
150 | def _handle_execute_reply(self, msg): | |
151 | """ Reimplemented to support prompt requests. |
|
151 | """ Reimplemented to support prompt requests. | |
152 | """ |
|
152 | """ | |
153 | info = self._request_info.get('execute') |
|
153 | info = self._request_info.get('execute') | |
154 | if info and info.id == msg['parent_header']['msg_id']: |
|
154 | if info and info.id == msg['parent_header']['msg_id']: | |
155 | if info.kind == 'prompt': |
|
155 | if info.kind == 'prompt': | |
156 | number = msg['content']['execution_count'] + 1 |
|
156 | number = msg['content']['execution_count'] + 1 | |
157 | self._show_interpreter_prompt(number) |
|
157 | self._show_interpreter_prompt(number) | |
158 | else: |
|
158 | else: | |
159 | super(IPythonWidget, self)._handle_execute_reply(msg) |
|
159 | super(IPythonWidget, self)._handle_execute_reply(msg) | |
160 |
|
160 | |||
161 | def _handle_history_reply(self, msg): |
|
161 | def _handle_history_reply(self, msg): | |
162 | """ Implemented to handle history replies, which are only supported by |
|
162 | """ Implemented to handle history replies, which are only supported by | |
163 | the IPython kernel. |
|
163 | the IPython kernel. | |
164 | """ |
|
164 | """ | |
165 | history_dict = msg['content']['history'] |
|
165 | history_dict = msg['content']['history'] | |
166 | input_history_dict = {} |
|
166 | input_history_dict = {} | |
167 | for key,val in history_dict.items(): |
|
167 | for key,val in history_dict.items(): | |
168 | input_history_dict[int(key)] = val |
|
168 | input_history_dict[int(key)] = val | |
169 | items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ] |
|
169 | items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ] | |
170 | self._set_history(items) |
|
170 | self._set_history(items) | |
171 |
|
171 | |||
172 | def _handle_pyout(self, msg): |
|
172 | def _handle_pyout(self, msg): | |
173 | """ Reimplemented for IPython-style "display hook". |
|
173 | """ Reimplemented for IPython-style "display hook". | |
174 | """ |
|
174 | """ | |
175 | if not self._hidden and self._is_from_this_session(msg): |
|
175 | if not self._hidden and self._is_from_this_session(msg): | |
176 | content = msg['content'] |
|
176 | content = msg['content'] | |
177 | prompt_number = content['execution_count'] |
|
177 | prompt_number = content['execution_count'] | |
178 | data = content['data'] |
|
178 | data = content['data'] | |
179 | if data.has_key('text/html'): |
|
179 | if data.has_key('text/html'): | |
180 | self._append_plain_text(self.output_sep) |
|
180 | self._append_plain_text(self.output_sep) | |
181 | self._append_html(self._make_out_prompt(prompt_number)) |
|
181 | self._append_html(self._make_out_prompt(prompt_number)) | |
182 | html = data['text/html'] |
|
182 | html = data['text/html'] | |
183 | self._append_plain_text('\n') |
|
183 | self._append_plain_text('\n') | |
184 | self._append_html(html + self.output_sep2) |
|
184 | self._append_html(html + self.output_sep2) | |
185 | elif data.has_key('text/plain'): |
|
185 | elif data.has_key('text/plain'): | |
186 | self._append_plain_text(self.output_sep) |
|
186 | self._append_plain_text(self.output_sep) | |
187 | self._append_html(self._make_out_prompt(prompt_number)) |
|
187 | self._append_html(self._make_out_prompt(prompt_number)) | |
188 | text = data['text/plain'] |
|
188 | text = data['text/plain'] | |
189 | self._append_plain_text(text + self.output_sep2) |
|
189 | self._append_plain_text(text + self.output_sep2) | |
190 |
|
190 | |||
191 | def _handle_display_data(self, msg): |
|
191 | def _handle_display_data(self, msg): | |
192 | """ The base handler for the ``display_data`` message. |
|
192 | """ The base handler for the ``display_data`` message. | |
193 | """ |
|
193 | """ | |
194 | # For now, we don't display data from other frontends, but we |
|
194 | # For now, we don't display data from other frontends, but we | |
195 | # eventually will as this allows all frontends to monitor the display |
|
195 | # eventually will as this allows all frontends to monitor the display | |
196 | # data. But we need to figure out how to handle this in the GUI. |
|
196 | # data. But we need to figure out how to handle this in the GUI. | |
197 | if not self._hidden and self._is_from_this_session(msg): |
|
197 | if not self._hidden and self._is_from_this_session(msg): | |
198 | source = msg['content']['source'] |
|
198 | source = msg['content']['source'] | |
199 | data = msg['content']['data'] |
|
199 | data = msg['content']['data'] | |
200 | metadata = msg['content']['metadata'] |
|
200 | metadata = msg['content']['metadata'] | |
201 | # In the regular IPythonWidget, we simply print the plain text |
|
201 | # In the regular IPythonWidget, we simply print the plain text | |
202 | # representation. |
|
202 | # representation. | |
203 | if data.has_key('text/html'): |
|
203 | if data.has_key('text/html'): | |
204 | html = data['text/html'] |
|
204 | html = data['text/html'] | |
205 | self._append_html(html) |
|
205 | self._append_html(html) | |
206 | elif data.has_key('text/plain'): |
|
206 | elif data.has_key('text/plain'): | |
207 | text = data['text/plain'] |
|
207 | text = data['text/plain'] | |
208 | self._append_plain_text(text) |
|
208 | self._append_plain_text(text) | |
209 | # This newline seems to be needed for text and html output. |
|
209 | # This newline seems to be needed for text and html output. | |
210 | self._append_plain_text(u'\n') |
|
210 | self._append_plain_text(u'\n') | |
211 |
|
211 | |||
212 | def _started_channels(self): |
|
212 | def _started_channels(self): | |
213 | """ Reimplemented to make a history request. |
|
213 | """ Reimplemented to make a history request. | |
214 | """ |
|
214 | """ | |
215 | super(IPythonWidget, self)._started_channels() |
|
215 | super(IPythonWidget, self)._started_channels() | |
216 |
self.kernel_manager.xreq_channel.history(raw=True, output=False |
|
216 | self.kernel_manager.xreq_channel.history(raw=True, output=False, | |
|
217 | this_session=False) | |||
217 |
|
218 | |||
218 | #--------------------------------------------------------------------------- |
|
219 | #--------------------------------------------------------------------------- | |
219 | # 'ConsoleWidget' public interface |
|
220 | # 'ConsoleWidget' public interface | |
220 | #--------------------------------------------------------------------------- |
|
221 | #--------------------------------------------------------------------------- | |
221 |
|
222 | |||
222 | def copy(self): |
|
223 | def copy(self): | |
223 | """ Copy the currently selected text to the clipboard, removing prompts |
|
224 | """ Copy the currently selected text to the clipboard, removing prompts | |
224 | if possible. |
|
225 | if possible. | |
225 | """ |
|
226 | """ | |
226 | text = self._control.textCursor().selection().toPlainText() |
|
227 | text = self._control.textCursor().selection().toPlainText() | |
227 | if text: |
|
228 | if text: | |
228 | lines = map(transform_ipy_prompt, text.splitlines()) |
|
229 | lines = map(transform_ipy_prompt, text.splitlines()) | |
229 | text = '\n'.join(lines) |
|
230 | text = '\n'.join(lines) | |
230 | QtGui.QApplication.clipboard().setText(text) |
|
231 | QtGui.QApplication.clipboard().setText(text) | |
231 |
|
232 | |||
232 | #--------------------------------------------------------------------------- |
|
233 | #--------------------------------------------------------------------------- | |
233 | # 'FrontendWidget' public interface |
|
234 | # 'FrontendWidget' public interface | |
234 | #--------------------------------------------------------------------------- |
|
235 | #--------------------------------------------------------------------------- | |
235 |
|
236 | |||
236 | def execute_file(self, path, hidden=False): |
|
237 | def execute_file(self, path, hidden=False): | |
237 | """ Reimplemented to use the 'run' magic. |
|
238 | """ Reimplemented to use the 'run' magic. | |
238 | """ |
|
239 | """ | |
239 | self.execute('%%run %s' % path, hidden=hidden) |
|
240 | self.execute('%%run %s' % path, hidden=hidden) | |
240 |
|
241 | |||
241 | #--------------------------------------------------------------------------- |
|
242 | #--------------------------------------------------------------------------- | |
242 | # 'FrontendWidget' protected interface |
|
243 | # 'FrontendWidget' protected interface | |
243 | #--------------------------------------------------------------------------- |
|
244 | #--------------------------------------------------------------------------- | |
244 |
|
245 | |||
245 | def _complete(self): |
|
246 | def _complete(self): | |
246 | """ Reimplemented to support IPython's improved completion machinery. |
|
247 | """ Reimplemented to support IPython's improved completion machinery. | |
247 | """ |
|
248 | """ | |
248 | # We let the kernel split the input line, so we *always* send an empty |
|
249 | # We let the kernel split the input line, so we *always* send an empty | |
249 | # text field. Readline-based frontends do get a real text field which |
|
250 | # text field. Readline-based frontends do get a real text field which | |
250 | # they can use. |
|
251 | # they can use. | |
251 | text = '' |
|
252 | text = '' | |
252 |
|
253 | |||
253 | # Send the completion request to the kernel |
|
254 | # Send the completion request to the kernel | |
254 | msg_id = self.kernel_manager.xreq_channel.complete( |
|
255 | msg_id = self.kernel_manager.xreq_channel.complete( | |
255 | text, # text |
|
256 | text, # text | |
256 | self._get_input_buffer_cursor_line(), # line |
|
257 | self._get_input_buffer_cursor_line(), # line | |
257 | self._get_input_buffer_cursor_column(), # cursor_pos |
|
258 | self._get_input_buffer_cursor_column(), # cursor_pos | |
258 | self.input_buffer) # block |
|
259 | self.input_buffer) # block | |
259 | pos = self._get_cursor().position() |
|
260 | pos = self._get_cursor().position() | |
260 | info = self._CompletionRequest(msg_id, pos) |
|
261 | info = self._CompletionRequest(msg_id, pos) | |
261 | self._request_info['complete'] = info |
|
262 | self._request_info['complete'] = info | |
262 |
|
263 | |||
263 | def _get_banner(self): |
|
264 | def _get_banner(self): | |
264 | """ Reimplemented to return IPython's default banner. |
|
265 | """ Reimplemented to return IPython's default banner. | |
265 | """ |
|
266 | """ | |
266 | return default_gui_banner |
|
267 | return default_gui_banner | |
267 |
|
268 | |||
268 | def _process_execute_error(self, msg): |
|
269 | def _process_execute_error(self, msg): | |
269 | """ Reimplemented for IPython-style traceback formatting. |
|
270 | """ Reimplemented for IPython-style traceback formatting. | |
270 | """ |
|
271 | """ | |
271 | content = msg['content'] |
|
272 | content = msg['content'] | |
272 | traceback = '\n'.join(content['traceback']) + '\n' |
|
273 | traceback = '\n'.join(content['traceback']) + '\n' | |
273 | if False: |
|
274 | if False: | |
274 | # FIXME: For now, tracebacks come as plain text, so we can't use |
|
275 | # FIXME: For now, tracebacks come as plain text, so we can't use | |
275 | # the html renderer yet. Once we refactor ultratb to produce |
|
276 | # the html renderer yet. Once we refactor ultratb to produce | |
276 | # properly styled tracebacks, this branch should be the default |
|
277 | # properly styled tracebacks, this branch should be the default | |
277 | traceback = traceback.replace(' ', ' ') |
|
278 | traceback = traceback.replace(' ', ' ') | |
278 | traceback = traceback.replace('\n', '<br/>') |
|
279 | traceback = traceback.replace('\n', '<br/>') | |
279 |
|
280 | |||
280 | ename = content['ename'] |
|
281 | ename = content['ename'] | |
281 | ename_styled = '<span class="error">%s</span>' % ename |
|
282 | ename_styled = '<span class="error">%s</span>' % ename | |
282 | traceback = traceback.replace(ename, ename_styled) |
|
283 | traceback = traceback.replace(ename, ename_styled) | |
283 |
|
284 | |||
284 | self._append_html(traceback) |
|
285 | self._append_html(traceback) | |
285 | else: |
|
286 | else: | |
286 | # This is the fallback for now, using plain text with ansi escapes |
|
287 | # This is the fallback for now, using plain text with ansi escapes | |
287 | self._append_plain_text(traceback) |
|
288 | self._append_plain_text(traceback) | |
288 |
|
289 | |||
289 | def _process_execute_payload(self, item): |
|
290 | def _process_execute_payload(self, item): | |
290 | """ Reimplemented to dispatch payloads to handler methods. |
|
291 | """ Reimplemented to dispatch payloads to handler methods. | |
291 | """ |
|
292 | """ | |
292 | handler = self._payload_handlers.get(item['source']) |
|
293 | handler = self._payload_handlers.get(item['source']) | |
293 | if handler is None: |
|
294 | if handler is None: | |
294 | # We have no handler for this type of payload, simply ignore it |
|
295 | # We have no handler for this type of payload, simply ignore it | |
295 | return False |
|
296 | return False | |
296 | else: |
|
297 | else: | |
297 | handler(item) |
|
298 | handler(item) | |
298 | return True |
|
299 | return True | |
299 |
|
300 | |||
300 | def _show_interpreter_prompt(self, number=None): |
|
301 | def _show_interpreter_prompt(self, number=None): | |
301 | """ Reimplemented for IPython-style prompts. |
|
302 | """ Reimplemented for IPython-style prompts. | |
302 | """ |
|
303 | """ | |
303 | # If a number was not specified, make a prompt number request. |
|
304 | # If a number was not specified, make a prompt number request. | |
304 | if number is None: |
|
305 | if number is None: | |
305 | msg_id = self.kernel_manager.xreq_channel.execute('', silent=True) |
|
306 | msg_id = self.kernel_manager.xreq_channel.execute('', silent=True) | |
306 | info = self._ExecutionRequest(msg_id, 'prompt') |
|
307 | info = self._ExecutionRequest(msg_id, 'prompt') | |
307 | self._request_info['execute'] = info |
|
308 | self._request_info['execute'] = info | |
308 | return |
|
309 | return | |
309 |
|
310 | |||
310 | # Show a new prompt and save information about it so that it can be |
|
311 | # Show a new prompt and save information about it so that it can be | |
311 | # updated later if the prompt number turns out to be wrong. |
|
312 | # updated later if the prompt number turns out to be wrong. | |
312 | self._prompt_sep = self.input_sep |
|
313 | self._prompt_sep = self.input_sep | |
313 | self._show_prompt(self._make_in_prompt(number), html=True) |
|
314 | self._show_prompt(self._make_in_prompt(number), html=True) | |
314 | block = self._control.document().lastBlock() |
|
315 | block = self._control.document().lastBlock() | |
315 | length = len(self._prompt) |
|
316 | length = len(self._prompt) | |
316 | self._previous_prompt_obj = self._PromptBlock(block, length, number) |
|
317 | self._previous_prompt_obj = self._PromptBlock(block, length, number) | |
317 |
|
318 | |||
318 | # Update continuation prompt to reflect (possibly) new prompt length. |
|
319 | # Update continuation prompt to reflect (possibly) new prompt length. | |
319 | self._set_continuation_prompt( |
|
320 | self._set_continuation_prompt( | |
320 | self._make_continuation_prompt(self._prompt), html=True) |
|
321 | self._make_continuation_prompt(self._prompt), html=True) | |
321 |
|
322 | |||
322 | # Load code from the %loadpy magic, if necessary. |
|
323 | # Load code from the %loadpy magic, if necessary. | |
323 | if self._code_to_load is not None: |
|
324 | if self._code_to_load is not None: | |
324 | self.input_buffer = dedent(self._code_to_load.rstrip()) |
|
325 | self.input_buffer = dedent(self._code_to_load.rstrip()) | |
325 | self._code_to_load = None |
|
326 | self._code_to_load = None | |
326 |
|
327 | |||
327 | def _show_interpreter_prompt_for_reply(self, msg): |
|
328 | def _show_interpreter_prompt_for_reply(self, msg): | |
328 | """ Reimplemented for IPython-style prompts. |
|
329 | """ Reimplemented for IPython-style prompts. | |
329 | """ |
|
330 | """ | |
330 | # Update the old prompt number if necessary. |
|
331 | # Update the old prompt number if necessary. | |
331 | content = msg['content'] |
|
332 | content = msg['content'] | |
332 | previous_prompt_number = content['execution_count'] |
|
333 | previous_prompt_number = content['execution_count'] | |
333 | if self._previous_prompt_obj and \ |
|
334 | if self._previous_prompt_obj and \ | |
334 | self._previous_prompt_obj.number != previous_prompt_number: |
|
335 | self._previous_prompt_obj.number != previous_prompt_number: | |
335 | block = self._previous_prompt_obj.block |
|
336 | block = self._previous_prompt_obj.block | |
336 |
|
337 | |||
337 | # Make sure the prompt block has not been erased. |
|
338 | # Make sure the prompt block has not been erased. | |
338 | if block.isValid() and block.text(): |
|
339 | if block.isValid() and block.text(): | |
339 |
|
340 | |||
340 | # Remove the old prompt and insert a new prompt. |
|
341 | # Remove the old prompt and insert a new prompt. | |
341 | cursor = QtGui.QTextCursor(block) |
|
342 | cursor = QtGui.QTextCursor(block) | |
342 | cursor.movePosition(QtGui.QTextCursor.Right, |
|
343 | cursor.movePosition(QtGui.QTextCursor.Right, | |
343 | QtGui.QTextCursor.KeepAnchor, |
|
344 | QtGui.QTextCursor.KeepAnchor, | |
344 | self._previous_prompt_obj.length) |
|
345 | self._previous_prompt_obj.length) | |
345 | prompt = self._make_in_prompt(previous_prompt_number) |
|
346 | prompt = self._make_in_prompt(previous_prompt_number) | |
346 | self._prompt = self._insert_html_fetching_plain_text( |
|
347 | self._prompt = self._insert_html_fetching_plain_text( | |
347 | cursor, prompt) |
|
348 | cursor, prompt) | |
348 |
|
349 | |||
349 | # When the HTML is inserted, Qt blows away the syntax |
|
350 | # When the HTML is inserted, Qt blows away the syntax | |
350 | # highlighting for the line, so we need to rehighlight it. |
|
351 | # highlighting for the line, so we need to rehighlight it. | |
351 | self._highlighter.rehighlightBlock(cursor.block()) |
|
352 | self._highlighter.rehighlightBlock(cursor.block()) | |
352 |
|
353 | |||
353 | self._previous_prompt_obj = None |
|
354 | self._previous_prompt_obj = None | |
354 |
|
355 | |||
355 | # Show a new prompt with the kernel's estimated prompt number. |
|
356 | # Show a new prompt with the kernel's estimated prompt number. | |
356 | self._show_interpreter_prompt(previous_prompt_number + 1) |
|
357 | self._show_interpreter_prompt(previous_prompt_number + 1) | |
357 |
|
358 | |||
358 | #--------------------------------------------------------------------------- |
|
359 | #--------------------------------------------------------------------------- | |
359 | # 'IPythonWidget' interface |
|
360 | # 'IPythonWidget' interface | |
360 | #--------------------------------------------------------------------------- |
|
361 | #--------------------------------------------------------------------------- | |
361 |
|
362 | |||
362 | def set_default_style(self, colors='lightbg'): |
|
363 | def set_default_style(self, colors='lightbg'): | |
363 | """ Sets the widget style to the class defaults. |
|
364 | """ Sets the widget style to the class defaults. | |
364 |
|
365 | |||
365 | Parameters: |
|
366 | Parameters: | |
366 | ----------- |
|
367 | ----------- | |
367 | colors : str, optional (default lightbg) |
|
368 | colors : str, optional (default lightbg) | |
368 | Whether to use the default IPython light background or dark |
|
369 | Whether to use the default IPython light background or dark | |
369 | background or B&W style. |
|
370 | background or B&W style. | |
370 | """ |
|
371 | """ | |
371 | colors = colors.lower() |
|
372 | colors = colors.lower() | |
372 | if colors=='lightbg': |
|
373 | if colors=='lightbg': | |
373 | self.style_sheet = default_light_style_sheet |
|
374 | self.style_sheet = default_light_style_sheet | |
374 | self.syntax_style = default_light_syntax_style |
|
375 | self.syntax_style = default_light_syntax_style | |
375 | elif colors=='linux': |
|
376 | elif colors=='linux': | |
376 | self.style_sheet = default_dark_style_sheet |
|
377 | self.style_sheet = default_dark_style_sheet | |
377 | self.syntax_style = default_dark_syntax_style |
|
378 | self.syntax_style = default_dark_syntax_style | |
378 | elif colors=='nocolor': |
|
379 | elif colors=='nocolor': | |
379 | self.style_sheet = default_bw_style_sheet |
|
380 | self.style_sheet = default_bw_style_sheet | |
380 | self.syntax_style = default_bw_syntax_style |
|
381 | self.syntax_style = default_bw_syntax_style | |
381 | else: |
|
382 | else: | |
382 | raise KeyError("No such color scheme: %s"%colors) |
|
383 | raise KeyError("No such color scheme: %s"%colors) | |
383 |
|
384 | |||
384 | #--------------------------------------------------------------------------- |
|
385 | #--------------------------------------------------------------------------- | |
385 | # 'IPythonWidget' protected interface |
|
386 | # 'IPythonWidget' protected interface | |
386 | #--------------------------------------------------------------------------- |
|
387 | #--------------------------------------------------------------------------- | |
387 |
|
388 | |||
388 | def _edit(self, filename, line=None): |
|
389 | def _edit(self, filename, line=None): | |
389 | """ Opens a Python script for editing. |
|
390 | """ Opens a Python script for editing. | |
390 |
|
391 | |||
391 | Parameters: |
|
392 | Parameters: | |
392 | ----------- |
|
393 | ----------- | |
393 | filename : str |
|
394 | filename : str | |
394 | A path to a local system file. |
|
395 | A path to a local system file. | |
395 |
|
396 | |||
396 | line : int, optional |
|
397 | line : int, optional | |
397 | A line of interest in the file. |
|
398 | A line of interest in the file. | |
398 | """ |
|
399 | """ | |
399 | if self.custom_edit: |
|
400 | if self.custom_edit: | |
400 | self.custom_edit_requested.emit(filename, line) |
|
401 | self.custom_edit_requested.emit(filename, line) | |
401 | elif self.editor == 'default': |
|
402 | elif self.editor == 'default': | |
402 | self._append_plain_text('No default editor available.\n') |
|
403 | self._append_plain_text('No default editor available.\n') | |
403 | else: |
|
404 | else: | |
404 | try: |
|
405 | try: | |
405 | filename = '"%s"' % filename |
|
406 | filename = '"%s"' % filename | |
406 | if line and self.editor_line: |
|
407 | if line and self.editor_line: | |
407 | command = self.editor_line.format(filename=filename, |
|
408 | command = self.editor_line.format(filename=filename, | |
408 | line=line) |
|
409 | line=line) | |
409 | else: |
|
410 | else: | |
410 | try: |
|
411 | try: | |
411 | command = self.editor.format() |
|
412 | command = self.editor.format() | |
412 | except KeyError: |
|
413 | except KeyError: | |
413 | command = self.editor.format(filename=filename) |
|
414 | command = self.editor.format(filename=filename) | |
414 | else: |
|
415 | else: | |
415 | command += ' ' + filename |
|
416 | command += ' ' + filename | |
416 | except KeyError: |
|
417 | except KeyError: | |
417 | self._append_plain_text('Invalid editor command.\n') |
|
418 | self._append_plain_text('Invalid editor command.\n') | |
418 | else: |
|
419 | else: | |
419 | try: |
|
420 | try: | |
420 | Popen(command, shell=True) |
|
421 | Popen(command, shell=True) | |
421 | except OSError: |
|
422 | except OSError: | |
422 | msg = 'Opening editor with command "%s" failed.\n' |
|
423 | msg = 'Opening editor with command "%s" failed.\n' | |
423 | self._append_plain_text(msg % command) |
|
424 | self._append_plain_text(msg % command) | |
424 |
|
425 | |||
425 | def _make_in_prompt(self, number): |
|
426 | def _make_in_prompt(self, number): | |
426 | """ Given a prompt number, returns an HTML In prompt. |
|
427 | """ Given a prompt number, returns an HTML In prompt. | |
427 | """ |
|
428 | """ | |
428 | body = self.in_prompt % number |
|
429 | body = self.in_prompt % number | |
429 | return '<span class="in-prompt">%s</span>' % body |
|
430 | return '<span class="in-prompt">%s</span>' % body | |
430 |
|
431 | |||
431 | def _make_continuation_prompt(self, prompt): |
|
432 | def _make_continuation_prompt(self, prompt): | |
432 | """ Given a plain text version of an In prompt, returns an HTML |
|
433 | """ Given a plain text version of an In prompt, returns an HTML | |
433 | continuation prompt. |
|
434 | continuation prompt. | |
434 | """ |
|
435 | """ | |
435 | end_chars = '...: ' |
|
436 | end_chars = '...: ' | |
436 | space_count = len(prompt.lstrip('\n')) - len(end_chars) |
|
437 | space_count = len(prompt.lstrip('\n')) - len(end_chars) | |
437 | body = ' ' * space_count + end_chars |
|
438 | body = ' ' * space_count + end_chars | |
438 | return '<span class="in-prompt">%s</span>' % body |
|
439 | return '<span class="in-prompt">%s</span>' % body | |
439 |
|
440 | |||
440 | def _make_out_prompt(self, number): |
|
441 | def _make_out_prompt(self, number): | |
441 | """ Given a prompt number, returns an HTML Out prompt. |
|
442 | """ Given a prompt number, returns an HTML Out prompt. | |
442 | """ |
|
443 | """ | |
443 | body = self.out_prompt % number |
|
444 | body = self.out_prompt % number | |
444 | return '<span class="out-prompt">%s</span>' % body |
|
445 | return '<span class="out-prompt">%s</span>' % body | |
445 |
|
446 | |||
446 | #------ Payload handlers -------------------------------------------------- |
|
447 | #------ Payload handlers -------------------------------------------------- | |
447 |
|
448 | |||
448 | # Payload handlers with a generic interface: each takes the opaque payload |
|
449 | # Payload handlers with a generic interface: each takes the opaque payload | |
449 | # dict, unpacks it and calls the underlying functions with the necessary |
|
450 | # dict, unpacks it and calls the underlying functions with the necessary | |
450 | # arguments. |
|
451 | # arguments. | |
451 |
|
452 | |||
452 | def _handle_payload_edit(self, item): |
|
453 | def _handle_payload_edit(self, item): | |
453 | self._edit(item['filename'], item['line_number']) |
|
454 | self._edit(item['filename'], item['line_number']) | |
454 |
|
455 | |||
455 | def _handle_payload_exit(self, item): |
|
456 | def _handle_payload_exit(self, item): | |
456 | self._keep_kernel_on_exit = item['keepkernel'] |
|
457 | self._keep_kernel_on_exit = item['keepkernel'] | |
457 | self.exit_requested.emit() |
|
458 | self.exit_requested.emit() | |
458 |
|
459 | |||
459 | def _handle_payload_loadpy(self, item): |
|
460 | def _handle_payload_loadpy(self, item): | |
460 | # Simple save the text of the .py file for later. The text is written |
|
461 | # Simple save the text of the .py file for later. The text is written | |
461 | # to the buffer when _prompt_started_hook is called. |
|
462 | # to the buffer when _prompt_started_hook is called. | |
462 | self._code_to_load = item['text'] |
|
463 | self._code_to_load = item['text'] | |
463 |
|
464 | |||
464 | def _handle_payload_page(self, item): |
|
465 | def _handle_payload_page(self, item): | |
465 | # Since the plain text widget supports only a very small subset of HTML |
|
466 | # Since the plain text widget supports only a very small subset of HTML | |
466 | # and we have no control over the HTML source, we only page HTML |
|
467 | # and we have no control over the HTML source, we only page HTML | |
467 | # payloads in the rich text widget. |
|
468 | # payloads in the rich text widget. | |
468 | if item['html'] and self.kind == 'rich': |
|
469 | if item['html'] and self.kind == 'rich': | |
469 | self._page(item['html'], html=True) |
|
470 | self._page(item['html'], html=True) | |
470 | else: |
|
471 | else: | |
471 | self._page(item['text'], html=False) |
|
472 | self._page(item['text'], html=False) | |
472 |
|
473 | |||
473 | #------ Trait change handlers -------------------------------------------- |
|
474 | #------ Trait change handlers -------------------------------------------- | |
474 |
|
475 | |||
475 | def _style_sheet_changed(self): |
|
476 | def _style_sheet_changed(self): | |
476 | """ Set the style sheets of the underlying widgets. |
|
477 | """ Set the style sheets of the underlying widgets. | |
477 | """ |
|
478 | """ | |
478 | self.setStyleSheet(self.style_sheet) |
|
479 | self.setStyleSheet(self.style_sheet) | |
479 | self._control.document().setDefaultStyleSheet(self.style_sheet) |
|
480 | self._control.document().setDefaultStyleSheet(self.style_sheet) | |
480 | if self._page_control: |
|
481 | if self._page_control: | |
481 | self._page_control.document().setDefaultStyleSheet(self.style_sheet) |
|
482 | self._page_control.document().setDefaultStyleSheet(self.style_sheet) | |
482 |
|
483 | |||
483 | bg_color = self._control.palette().window().color() |
|
484 | bg_color = self._control.palette().window().color() | |
484 | self._ansi_processor.set_background_color(bg_color) |
|
485 | self._ansi_processor.set_background_color(bg_color) | |
485 |
|
486 | |||
486 | def _syntax_style_changed(self): |
|
487 | def _syntax_style_changed(self): | |
487 | """ Set the style for the syntax highlighter. |
|
488 | """ Set the style for the syntax highlighter. | |
488 | """ |
|
489 | """ | |
489 | if self.syntax_style: |
|
490 | if self.syntax_style: | |
490 | self._highlighter.set_style(self.syntax_style) |
|
491 | self._highlighter.set_style(self.syntax_style) | |
491 | else: |
|
492 | else: | |
492 | self._highlighter.set_style_sheet(self.style_sheet) |
|
493 | self._highlighter.set_style_sheet(self.style_sheet) | |
493 |
|
494 |
@@ -1,641 +1,640 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | """A simple interactive kernel that talks to a frontend over 0MQ. |
|
2 | """A simple interactive kernel that talks to a frontend over 0MQ. | |
3 |
|
3 | |||
4 | Things to do: |
|
4 | Things to do: | |
5 |
|
5 | |||
6 | * Implement `set_parent` logic. Right before doing exec, the Kernel should |
|
6 | * Implement `set_parent` logic. Right before doing exec, the Kernel should | |
7 | call set_parent on all the PUB objects with the message about to be executed. |
|
7 | call set_parent on all the PUB objects with the message about to be executed. | |
8 | * Implement random port and security key logic. |
|
8 | * Implement random port and security key logic. | |
9 | * Implement control messages. |
|
9 | * Implement control messages. | |
10 | * Implement event loop and poll version. |
|
10 | * Implement event loop and poll version. | |
11 | """ |
|
11 | """ | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | from __future__ import print_function |
|
16 | from __future__ import print_function | |
17 |
|
17 | |||
18 | # Standard library imports. |
|
18 | # Standard library imports. | |
19 | import __builtin__ |
|
19 | import __builtin__ | |
20 | import atexit |
|
20 | import atexit | |
21 | import sys |
|
21 | import sys | |
22 | import time |
|
22 | import time | |
23 | import traceback |
|
23 | import traceback | |
24 | import logging |
|
24 | import logging | |
25 | # System library imports. |
|
25 | # System library imports. | |
26 | import zmq |
|
26 | import zmq | |
27 |
|
27 | |||
28 | # Local imports. |
|
28 | # Local imports. | |
29 | from IPython.config.configurable import Configurable |
|
29 | from IPython.config.configurable import Configurable | |
30 | from IPython.utils import io |
|
30 | from IPython.utils import io | |
31 | from IPython.utils.jsonutil import json_clean |
|
31 | from IPython.utils.jsonutil import json_clean | |
32 | from IPython.lib import pylabtools |
|
32 | from IPython.lib import pylabtools | |
33 | from IPython.utils.traitlets import Instance, Float |
|
33 | from IPython.utils.traitlets import Instance, Float | |
34 | from entry_point import (base_launch_kernel, make_argument_parser, make_kernel, |
|
34 | from entry_point import (base_launch_kernel, make_argument_parser, make_kernel, | |
35 | start_kernel) |
|
35 | start_kernel) | |
36 | from iostream import OutStream |
|
36 | from iostream import OutStream | |
37 | from session import Session, Message |
|
37 | from session import Session, Message | |
38 | from zmqshell import ZMQInteractiveShell |
|
38 | from zmqshell import ZMQInteractiveShell | |
39 |
|
39 | |||
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 | # Globals |
|
41 | # Globals | |
42 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
43 |
|
43 | |||
44 | # Module-level logger |
|
44 | # Module-level logger | |
45 | logger = logging.getLogger(__name__) |
|
45 | logger = logging.getLogger(__name__) | |
46 |
|
46 | |||
47 | #----------------------------------------------------------------------------- |
|
47 | #----------------------------------------------------------------------------- | |
48 | # Main kernel class |
|
48 | # Main kernel class | |
49 | #----------------------------------------------------------------------------- |
|
49 | #----------------------------------------------------------------------------- | |
50 |
|
50 | |||
51 | class Kernel(Configurable): |
|
51 | class Kernel(Configurable): | |
52 |
|
52 | |||
53 | #--------------------------------------------------------------------------- |
|
53 | #--------------------------------------------------------------------------- | |
54 | # Kernel interface |
|
54 | # Kernel interface | |
55 | #--------------------------------------------------------------------------- |
|
55 | #--------------------------------------------------------------------------- | |
56 |
|
56 | |||
57 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
57 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
58 | session = Instance(Session) |
|
58 | session = Instance(Session) | |
59 | reply_socket = Instance('zmq.Socket') |
|
59 | reply_socket = Instance('zmq.Socket') | |
60 | pub_socket = Instance('zmq.Socket') |
|
60 | pub_socket = Instance('zmq.Socket') | |
61 | req_socket = Instance('zmq.Socket') |
|
61 | req_socket = Instance('zmq.Socket') | |
62 |
|
62 | |||
63 | # Private interface |
|
63 | # Private interface | |
64 |
|
64 | |||
65 | # Time to sleep after flushing the stdout/err buffers in each execute |
|
65 | # Time to sleep after flushing the stdout/err buffers in each execute | |
66 | # cycle. While this introduces a hard limit on the minimal latency of the |
|
66 | # cycle. While this introduces a hard limit on the minimal latency of the | |
67 | # execute cycle, it helps prevent output synchronization problems for |
|
67 | # execute cycle, it helps prevent output synchronization problems for | |
68 | # clients. |
|
68 | # clients. | |
69 | # Units are in seconds. The minimum zmq latency on local host is probably |
|
69 | # Units are in seconds. The minimum zmq latency on local host is probably | |
70 | # ~150 microseconds, set this to 500us for now. We may need to increase it |
|
70 | # ~150 microseconds, set this to 500us for now. We may need to increase it | |
71 | # a little if it's not enough after more interactive testing. |
|
71 | # a little if it's not enough after more interactive testing. | |
72 | _execute_sleep = Float(0.0005, config=True) |
|
72 | _execute_sleep = Float(0.0005, config=True) | |
73 |
|
73 | |||
74 | # Frequency of the kernel's event loop. |
|
74 | # Frequency of the kernel's event loop. | |
75 | # Units are in seconds, kernel subclasses for GUI toolkits may need to |
|
75 | # Units are in seconds, kernel subclasses for GUI toolkits may need to | |
76 | # adapt to milliseconds. |
|
76 | # adapt to milliseconds. | |
77 | _poll_interval = Float(0.05, config=True) |
|
77 | _poll_interval = Float(0.05, config=True) | |
78 |
|
78 | |||
79 | # If the shutdown was requested over the network, we leave here the |
|
79 | # If the shutdown was requested over the network, we leave here the | |
80 | # necessary reply message so it can be sent by our registered atexit |
|
80 | # necessary reply message so it can be sent by our registered atexit | |
81 | # handler. This ensures that the reply is only sent to clients truly at |
|
81 | # handler. This ensures that the reply is only sent to clients truly at | |
82 | # the end of our shutdown process (which happens after the underlying |
|
82 | # the end of our shutdown process (which happens after the underlying | |
83 | # IPython shell's own shutdown). |
|
83 | # IPython shell's own shutdown). | |
84 | _shutdown_message = None |
|
84 | _shutdown_message = None | |
85 |
|
85 | |||
86 | # This is a dict of port number that the kernel is listening on. It is set |
|
86 | # This is a dict of port number that the kernel is listening on. It is set | |
87 | # by record_ports and used by connect_request. |
|
87 | # by record_ports and used by connect_request. | |
88 | _recorded_ports = None |
|
88 | _recorded_ports = None | |
89 |
|
89 | |||
90 |
|
90 | |||
91 | def __init__(self, **kwargs): |
|
91 | def __init__(self, **kwargs): | |
92 | super(Kernel, self).__init__(**kwargs) |
|
92 | super(Kernel, self).__init__(**kwargs) | |
93 |
|
93 | |||
94 | # Before we even start up the shell, register *first* our exit handlers |
|
94 | # Before we even start up the shell, register *first* our exit handlers | |
95 | # so they come before the shell's |
|
95 | # so they come before the shell's | |
96 | atexit.register(self._at_shutdown) |
|
96 | atexit.register(self._at_shutdown) | |
97 |
|
97 | |||
98 | # Initialize the InteractiveShell subclass |
|
98 | # Initialize the InteractiveShell subclass | |
99 | self.shell = ZMQInteractiveShell.instance() |
|
99 | self.shell = ZMQInteractiveShell.instance() | |
100 | self.shell.displayhook.session = self.session |
|
100 | self.shell.displayhook.session = self.session | |
101 | self.shell.displayhook.pub_socket = self.pub_socket |
|
101 | self.shell.displayhook.pub_socket = self.pub_socket | |
102 | self.shell.display_pub.session = self.session |
|
102 | self.shell.display_pub.session = self.session | |
103 | self.shell.display_pub.pub_socket = self.pub_socket |
|
103 | self.shell.display_pub.pub_socket = self.pub_socket | |
104 |
|
104 | |||
105 | # TMP - hack while developing |
|
105 | # TMP - hack while developing | |
106 | self.shell._reply_content = None |
|
106 | self.shell._reply_content = None | |
107 |
|
107 | |||
108 | # Build dict of handlers for message types |
|
108 | # Build dict of handlers for message types | |
109 | msg_types = [ 'execute_request', 'complete_request', |
|
109 | msg_types = [ 'execute_request', 'complete_request', | |
110 | 'object_info_request', 'history_request', |
|
110 | 'object_info_request', 'history_request', | |
111 | 'connect_request', 'shutdown_request'] |
|
111 | 'connect_request', 'shutdown_request'] | |
112 | self.handlers = {} |
|
112 | self.handlers = {} | |
113 | for msg_type in msg_types: |
|
113 | for msg_type in msg_types: | |
114 | self.handlers[msg_type] = getattr(self, msg_type) |
|
114 | self.handlers[msg_type] = getattr(self, msg_type) | |
115 |
|
115 | |||
116 | def do_one_iteration(self): |
|
116 | def do_one_iteration(self): | |
117 | """Do one iteration of the kernel's evaluation loop. |
|
117 | """Do one iteration of the kernel's evaluation loop. | |
118 | """ |
|
118 | """ | |
119 | ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK) |
|
119 | ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK) | |
120 | if msg is None: |
|
120 | if msg is None: | |
121 | return |
|
121 | return | |
122 |
|
122 | |||
123 | # This assert will raise in versions of zeromq 2.0.7 and lesser. |
|
123 | # This assert will raise in versions of zeromq 2.0.7 and lesser. | |
124 | # We now require 2.0.8 or above, so we can uncomment for safety. |
|
124 | # We now require 2.0.8 or above, so we can uncomment for safety. | |
125 | # print(ident,msg, file=sys.__stdout__) |
|
125 | # print(ident,msg, file=sys.__stdout__) | |
126 | assert ident is not None, "Missing message part." |
|
126 | assert ident is not None, "Missing message part." | |
127 |
|
127 | |||
128 | # Print some info about this message and leave a '--->' marker, so it's |
|
128 | # Print some info about this message and leave a '--->' marker, so it's | |
129 | # easier to trace visually the message chain when debugging. Each |
|
129 | # easier to trace visually the message chain when debugging. Each | |
130 | # handler prints its message at the end. |
|
130 | # handler prints its message at the end. | |
131 | # Eventually we'll move these from stdout to a logger. |
|
131 | # Eventually we'll move these from stdout to a logger. | |
132 | logger.debug('\n*** MESSAGE TYPE:'+str(msg['msg_type'])+'***') |
|
132 | logger.debug('\n*** MESSAGE TYPE:'+str(msg['msg_type'])+'***') | |
133 | logger.debug(' Content: '+str(msg['content'])+'\n --->\n ') |
|
133 | logger.debug(' Content: '+str(msg['content'])+'\n --->\n ') | |
134 |
|
134 | |||
135 | # Find and call actual handler for message |
|
135 | # Find and call actual handler for message | |
136 | handler = self.handlers.get(msg['msg_type'], None) |
|
136 | handler = self.handlers.get(msg['msg_type'], None) | |
137 | if handler is None: |
|
137 | if handler is None: | |
138 | logger.error("UNKNOWN MESSAGE TYPE:" +str(msg)) |
|
138 | logger.error("UNKNOWN MESSAGE TYPE:" +str(msg)) | |
139 | else: |
|
139 | else: | |
140 | handler(ident, msg) |
|
140 | handler(ident, msg) | |
141 |
|
141 | |||
142 | # Check whether we should exit, in case the incoming message set the |
|
142 | # Check whether we should exit, in case the incoming message set the | |
143 | # exit flag on |
|
143 | # exit flag on | |
144 | if self.shell.exit_now: |
|
144 | if self.shell.exit_now: | |
145 | logger.debug('\nExiting IPython kernel...') |
|
145 | logger.debug('\nExiting IPython kernel...') | |
146 | # We do a normal, clean exit, which allows any actions registered |
|
146 | # We do a normal, clean exit, which allows any actions registered | |
147 | # via atexit (such as history saving) to take place. |
|
147 | # via atexit (such as history saving) to take place. | |
148 | sys.exit(0) |
|
148 | sys.exit(0) | |
149 |
|
149 | |||
150 |
|
150 | |||
151 | def start(self): |
|
151 | def start(self): | |
152 | """ Start the kernel main loop. |
|
152 | """ Start the kernel main loop. | |
153 | """ |
|
153 | """ | |
154 | while True: |
|
154 | while True: | |
155 | time.sleep(self._poll_interval) |
|
155 | time.sleep(self._poll_interval) | |
156 | self.do_one_iteration() |
|
156 | self.do_one_iteration() | |
157 |
|
157 | |||
158 | def record_ports(self, xrep_port, pub_port, req_port, hb_port): |
|
158 | def record_ports(self, xrep_port, pub_port, req_port, hb_port): | |
159 | """Record the ports that this kernel is using. |
|
159 | """Record the ports that this kernel is using. | |
160 |
|
160 | |||
161 | The creator of the Kernel instance must call this methods if they |
|
161 | The creator of the Kernel instance must call this methods if they | |
162 | want the :meth:`connect_request` method to return the port numbers. |
|
162 | want the :meth:`connect_request` method to return the port numbers. | |
163 | """ |
|
163 | """ | |
164 | self._recorded_ports = { |
|
164 | self._recorded_ports = { | |
165 | 'xrep_port' : xrep_port, |
|
165 | 'xrep_port' : xrep_port, | |
166 | 'pub_port' : pub_port, |
|
166 | 'pub_port' : pub_port, | |
167 | 'req_port' : req_port, |
|
167 | 'req_port' : req_port, | |
168 | 'hb_port' : hb_port |
|
168 | 'hb_port' : hb_port | |
169 | } |
|
169 | } | |
170 |
|
170 | |||
171 | #--------------------------------------------------------------------------- |
|
171 | #--------------------------------------------------------------------------- | |
172 | # Kernel request handlers |
|
172 | # Kernel request handlers | |
173 | #--------------------------------------------------------------------------- |
|
173 | #--------------------------------------------------------------------------- | |
174 |
|
174 | |||
175 | def _publish_pyin(self, code, parent): |
|
175 | def _publish_pyin(self, code, parent): | |
176 | """Publish the code request on the pyin stream.""" |
|
176 | """Publish the code request on the pyin stream.""" | |
177 |
|
177 | |||
178 | pyin_msg = self.session.send(self.pub_socket, u'pyin',{u'code':code}, parent=parent) |
|
178 | pyin_msg = self.session.send(self.pub_socket, u'pyin',{u'code':code}, parent=parent) | |
179 |
|
179 | |||
180 | def execute_request(self, ident, parent): |
|
180 | def execute_request(self, ident, parent): | |
181 |
|
181 | |||
182 | status_msg = self.session.send(self.pub_socket, |
|
182 | status_msg = self.session.send(self.pub_socket, | |
183 | u'status', |
|
183 | u'status', | |
184 | {u'execution_state':u'busy'}, |
|
184 | {u'execution_state':u'busy'}, | |
185 | parent=parent |
|
185 | parent=parent | |
186 | ) |
|
186 | ) | |
187 |
|
187 | |||
188 | try: |
|
188 | try: | |
189 | content = parent[u'content'] |
|
189 | content = parent[u'content'] | |
190 | code = content[u'code'] |
|
190 | code = content[u'code'] | |
191 | silent = content[u'silent'] |
|
191 | silent = content[u'silent'] | |
192 | except: |
|
192 | except: | |
193 | logger.error("Got bad msg: ") |
|
193 | logger.error("Got bad msg: ") | |
194 | logger.error(str(Message(parent))) |
|
194 | logger.error(str(Message(parent))) | |
195 | return |
|
195 | return | |
196 |
|
196 | |||
197 | shell = self.shell # we'll need this a lot here |
|
197 | shell = self.shell # we'll need this a lot here | |
198 |
|
198 | |||
199 | # Replace raw_input. Note that is not sufficient to replace |
|
199 | # Replace raw_input. Note that is not sufficient to replace | |
200 | # raw_input in the user namespace. |
|
200 | # raw_input in the user namespace. | |
201 | raw_input = lambda prompt='': self._raw_input(prompt, ident, parent) |
|
201 | raw_input = lambda prompt='': self._raw_input(prompt, ident, parent) | |
202 | __builtin__.raw_input = raw_input |
|
202 | __builtin__.raw_input = raw_input | |
203 |
|
203 | |||
204 | # Set the parent message of the display hook and out streams. |
|
204 | # Set the parent message of the display hook and out streams. | |
205 | shell.displayhook.set_parent(parent) |
|
205 | shell.displayhook.set_parent(parent) | |
206 | shell.display_pub.set_parent(parent) |
|
206 | shell.display_pub.set_parent(parent) | |
207 | sys.stdout.set_parent(parent) |
|
207 | sys.stdout.set_parent(parent) | |
208 | sys.stderr.set_parent(parent) |
|
208 | sys.stderr.set_parent(parent) | |
209 |
|
209 | |||
210 | # Re-broadcast our input for the benefit of listening clients, and |
|
210 | # Re-broadcast our input for the benefit of listening clients, and | |
211 | # start computing output |
|
211 | # start computing output | |
212 | if not silent: |
|
212 | if not silent: | |
213 | self._publish_pyin(code, parent) |
|
213 | self._publish_pyin(code, parent) | |
214 |
|
214 | |||
215 | reply_content = {} |
|
215 | reply_content = {} | |
216 | try: |
|
216 | try: | |
217 | if silent: |
|
217 | if silent: | |
218 | # run_code uses 'exec' mode, so no displayhook will fire, and it |
|
218 | # run_code uses 'exec' mode, so no displayhook will fire, and it | |
219 | # doesn't call logging or history manipulations. Print |
|
219 | # doesn't call logging or history manipulations. Print | |
220 | # statements in that code will obviously still execute. |
|
220 | # statements in that code will obviously still execute. | |
221 | shell.run_code(code) |
|
221 | shell.run_code(code) | |
222 | else: |
|
222 | else: | |
223 | # FIXME: the shell calls the exception handler itself. |
|
223 | # FIXME: the shell calls the exception handler itself. | |
224 | shell._reply_content = None |
|
224 | shell._reply_content = None | |
225 | shell.run_cell(code) |
|
225 | shell.run_cell(code) | |
226 | except: |
|
226 | except: | |
227 | status = u'error' |
|
227 | status = u'error' | |
228 | # FIXME: this code right now isn't being used yet by default, |
|
228 | # FIXME: this code right now isn't being used yet by default, | |
229 | # because the runlines() call above directly fires off exception |
|
229 | # because the runlines() call above directly fires off exception | |
230 | # reporting. This code, therefore, is only active in the scenario |
|
230 | # reporting. This code, therefore, is only active in the scenario | |
231 | # where runlines itself has an unhandled exception. We need to |
|
231 | # where runlines itself has an unhandled exception. We need to | |
232 | # uniformize this, for all exception construction to come from a |
|
232 | # uniformize this, for all exception construction to come from a | |
233 | # single location in the codbase. |
|
233 | # single location in the codbase. | |
234 | etype, evalue, tb = sys.exc_info() |
|
234 | etype, evalue, tb = sys.exc_info() | |
235 | tb_list = traceback.format_exception(etype, evalue, tb) |
|
235 | tb_list = traceback.format_exception(etype, evalue, tb) | |
236 | reply_content.update(shell._showtraceback(etype, evalue, tb_list)) |
|
236 | reply_content.update(shell._showtraceback(etype, evalue, tb_list)) | |
237 | else: |
|
237 | else: | |
238 | status = u'ok' |
|
238 | status = u'ok' | |
239 |
|
239 | |||
240 | reply_content[u'status'] = status |
|
240 | reply_content[u'status'] = status | |
241 |
|
241 | |||
242 | # Return the execution counter so clients can display prompts |
|
242 | # Return the execution counter so clients can display prompts | |
243 | reply_content['execution_count'] = shell.execution_count -1 |
|
243 | reply_content['execution_count'] = shell.execution_count -1 | |
244 |
|
244 | |||
245 | # FIXME - fish exception info out of shell, possibly left there by |
|
245 | # FIXME - fish exception info out of shell, possibly left there by | |
246 | # runlines. We'll need to clean up this logic later. |
|
246 | # runlines. We'll need to clean up this logic later. | |
247 | if shell._reply_content is not None: |
|
247 | if shell._reply_content is not None: | |
248 | reply_content.update(shell._reply_content) |
|
248 | reply_content.update(shell._reply_content) | |
249 |
|
249 | |||
250 | # At this point, we can tell whether the main code execution succeeded |
|
250 | # At this point, we can tell whether the main code execution succeeded | |
251 | # or not. If it did, we proceed to evaluate user_variables/expressions |
|
251 | # or not. If it did, we proceed to evaluate user_variables/expressions | |
252 | if reply_content['status'] == 'ok': |
|
252 | if reply_content['status'] == 'ok': | |
253 | reply_content[u'user_variables'] = \ |
|
253 | reply_content[u'user_variables'] = \ | |
254 | shell.user_variables(content[u'user_variables']) |
|
254 | shell.user_variables(content[u'user_variables']) | |
255 | reply_content[u'user_expressions'] = \ |
|
255 | reply_content[u'user_expressions'] = \ | |
256 | shell.user_expressions(content[u'user_expressions']) |
|
256 | shell.user_expressions(content[u'user_expressions']) | |
257 | else: |
|
257 | else: | |
258 | # If there was an error, don't even try to compute variables or |
|
258 | # If there was an error, don't even try to compute variables or | |
259 | # expressions |
|
259 | # expressions | |
260 | reply_content[u'user_variables'] = {} |
|
260 | reply_content[u'user_variables'] = {} | |
261 | reply_content[u'user_expressions'] = {} |
|
261 | reply_content[u'user_expressions'] = {} | |
262 |
|
262 | |||
263 | # Payloads should be retrieved regardless of outcome, so we can both |
|
263 | # Payloads should be retrieved regardless of outcome, so we can both | |
264 | # recover partial output (that could have been generated early in a |
|
264 | # recover partial output (that could have been generated early in a | |
265 | # block, before an error) and clear the payload system always. |
|
265 | # block, before an error) and clear the payload system always. | |
266 | reply_content[u'payload'] = shell.payload_manager.read_payload() |
|
266 | reply_content[u'payload'] = shell.payload_manager.read_payload() | |
267 | # Be agressive about clearing the payload because we don't want |
|
267 | # Be agressive about clearing the payload because we don't want | |
268 | # it to sit in memory until the next execute_request comes in. |
|
268 | # it to sit in memory until the next execute_request comes in. | |
269 | shell.payload_manager.clear_payload() |
|
269 | shell.payload_manager.clear_payload() | |
270 |
|
270 | |||
271 | # Flush output before sending the reply. |
|
271 | # Flush output before sending the reply. | |
272 | sys.stdout.flush() |
|
272 | sys.stdout.flush() | |
273 | sys.stderr.flush() |
|
273 | sys.stderr.flush() | |
274 | # FIXME: on rare occasions, the flush doesn't seem to make it to the |
|
274 | # FIXME: on rare occasions, the flush doesn't seem to make it to the | |
275 | # clients... This seems to mitigate the problem, but we definitely need |
|
275 | # clients... This seems to mitigate the problem, but we definitely need | |
276 | # to better understand what's going on. |
|
276 | # to better understand what's going on. | |
277 | if self._execute_sleep: |
|
277 | if self._execute_sleep: | |
278 | time.sleep(self._execute_sleep) |
|
278 | time.sleep(self._execute_sleep) | |
279 |
|
279 | |||
280 | # Send the reply. |
|
280 | # Send the reply. | |
281 | reply_msg = self.session.send(self.reply_socket, u'execute_reply', |
|
281 | reply_msg = self.session.send(self.reply_socket, u'execute_reply', | |
282 | reply_content, parent, ident=ident) |
|
282 | reply_content, parent, ident=ident) | |
283 | logger.debug(str(reply_msg)) |
|
283 | logger.debug(str(reply_msg)) | |
284 |
|
284 | |||
285 | if reply_msg['content']['status'] == u'error': |
|
285 | if reply_msg['content']['status'] == u'error': | |
286 | self._abort_queue() |
|
286 | self._abort_queue() | |
287 |
|
287 | |||
288 | status_msg = self.session.send(self.pub_socket, |
|
288 | status_msg = self.session.send(self.pub_socket, | |
289 | u'status', |
|
289 | u'status', | |
290 | {u'execution_state':u'idle'}, |
|
290 | {u'execution_state':u'idle'}, | |
291 | parent=parent |
|
291 | parent=parent | |
292 | ) |
|
292 | ) | |
293 |
|
293 | |||
294 | def complete_request(self, ident, parent): |
|
294 | def complete_request(self, ident, parent): | |
295 | txt, matches = self._complete(parent) |
|
295 | txt, matches = self._complete(parent) | |
296 | matches = {'matches' : matches, |
|
296 | matches = {'matches' : matches, | |
297 | 'matched_text' : txt, |
|
297 | 'matched_text' : txt, | |
298 | 'status' : 'ok'} |
|
298 | 'status' : 'ok'} | |
299 | completion_msg = self.session.send(self.reply_socket, 'complete_reply', |
|
299 | completion_msg = self.session.send(self.reply_socket, 'complete_reply', | |
300 | matches, parent, ident) |
|
300 | matches, parent, ident) | |
301 | logger.debug(str(completion_msg)) |
|
301 | logger.debug(str(completion_msg)) | |
302 |
|
302 | |||
303 | def object_info_request(self, ident, parent): |
|
303 | def object_info_request(self, ident, parent): | |
304 | object_info = self.shell.object_inspect(parent['content']['oname']) |
|
304 | object_info = self.shell.object_inspect(parent['content']['oname']) | |
305 | # Before we send this object over, we scrub it for JSON usage |
|
305 | # Before we send this object over, we scrub it for JSON usage | |
306 | oinfo = json_clean(object_info) |
|
306 | oinfo = json_clean(object_info) | |
307 | msg = self.session.send(self.reply_socket, 'object_info_reply', |
|
307 | msg = self.session.send(self.reply_socket, 'object_info_reply', | |
308 | oinfo, parent, ident) |
|
308 | oinfo, parent, ident) | |
309 | logger.debug(msg) |
|
309 | logger.debug(msg) | |
310 |
|
310 | |||
311 | def history_request(self, ident, parent): |
|
311 | def history_request(self, ident, parent): | |
312 | output = parent['content']['output'] |
|
312 | # parent['content'] should contain keys "index", "raw", "output" and | |
313 | index = parent['content']['index'] |
|
313 | # "this_session". | |
314 | raw = parent['content']['raw'] |
|
314 | hist = self.shell.get_history(**parent['content']) | |
315 | hist = self.shell.get_history(index=index, raw=raw, output=output) |
|
|||
316 | content = {'history' : hist} |
|
315 | content = {'history' : hist} | |
317 | msg = self.session.send(self.reply_socket, 'history_reply', |
|
316 | msg = self.session.send(self.reply_socket, 'history_reply', | |
318 | content, parent, ident) |
|
317 | content, parent, ident) | |
319 | logger.debug(str(msg)) |
|
318 | logger.debug(str(msg)) | |
320 |
|
319 | |||
321 | def connect_request(self, ident, parent): |
|
320 | def connect_request(self, ident, parent): | |
322 | if self._recorded_ports is not None: |
|
321 | if self._recorded_ports is not None: | |
323 | content = self._recorded_ports.copy() |
|
322 | content = self._recorded_ports.copy() | |
324 | else: |
|
323 | else: | |
325 | content = {} |
|
324 | content = {} | |
326 | msg = self.session.send(self.reply_socket, 'connect_reply', |
|
325 | msg = self.session.send(self.reply_socket, 'connect_reply', | |
327 | content, parent, ident) |
|
326 | content, parent, ident) | |
328 | logger.debug(msg) |
|
327 | logger.debug(msg) | |
329 |
|
328 | |||
330 | def shutdown_request(self, ident, parent): |
|
329 | def shutdown_request(self, ident, parent): | |
331 | self.shell.exit_now = True |
|
330 | self.shell.exit_now = True | |
332 | self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent) |
|
331 | self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent) | |
333 | sys.exit(0) |
|
332 | sys.exit(0) | |
334 |
|
333 | |||
335 | #--------------------------------------------------------------------------- |
|
334 | #--------------------------------------------------------------------------- | |
336 | # Protected interface |
|
335 | # Protected interface | |
337 | #--------------------------------------------------------------------------- |
|
336 | #--------------------------------------------------------------------------- | |
338 |
|
337 | |||
339 | def _abort_queue(self): |
|
338 | def _abort_queue(self): | |
340 | while True: |
|
339 | while True: | |
341 | ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK) |
|
340 | ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK) | |
342 | if msg is None: |
|
341 | if msg is None: | |
343 | break |
|
342 | break | |
344 | else: |
|
343 | else: | |
345 | assert ident is not None, \ |
|
344 | assert ident is not None, \ | |
346 | "Unexpected missing message part." |
|
345 | "Unexpected missing message part." | |
347 |
|
346 | |||
348 | logger.debug("Aborting:\n"+str(Message(msg))) |
|
347 | logger.debug("Aborting:\n"+str(Message(msg))) | |
349 | msg_type = msg['msg_type'] |
|
348 | msg_type = msg['msg_type'] | |
350 | reply_type = msg_type.split('_')[0] + '_reply' |
|
349 | reply_type = msg_type.split('_')[0] + '_reply' | |
351 | reply_msg = self.session.send(self.reply_socket, reply_type, |
|
350 | reply_msg = self.session.send(self.reply_socket, reply_type, | |
352 | {'status' : 'aborted'}, msg, ident=ident) |
|
351 | {'status' : 'aborted'}, msg, ident=ident) | |
353 | logger.debug(reply_msg) |
|
352 | logger.debug(reply_msg) | |
354 | # We need to wait a bit for requests to come in. This can probably |
|
353 | # We need to wait a bit for requests to come in. This can probably | |
355 | # be set shorter for true asynchronous clients. |
|
354 | # be set shorter for true asynchronous clients. | |
356 | time.sleep(0.1) |
|
355 | time.sleep(0.1) | |
357 |
|
356 | |||
358 | def _raw_input(self, prompt, ident, parent): |
|
357 | def _raw_input(self, prompt, ident, parent): | |
359 | # Flush output before making the request. |
|
358 | # Flush output before making the request. | |
360 | sys.stderr.flush() |
|
359 | sys.stderr.flush() | |
361 | sys.stdout.flush() |
|
360 | sys.stdout.flush() | |
362 |
|
361 | |||
363 | # Send the input request. |
|
362 | # Send the input request. | |
364 | content = dict(prompt=prompt) |
|
363 | content = dict(prompt=prompt) | |
365 | msg = self.session.send(self.req_socket, u'input_request', content, parent) |
|
364 | msg = self.session.send(self.req_socket, u'input_request', content, parent) | |
366 |
|
365 | |||
367 | # Await a response. |
|
366 | # Await a response. | |
368 | ident, reply = self.session.recv(self.req_socket, 0) |
|
367 | ident, reply = self.session.recv(self.req_socket, 0) | |
369 | try: |
|
368 | try: | |
370 | value = reply['content']['value'] |
|
369 | value = reply['content']['value'] | |
371 | except: |
|
370 | except: | |
372 | logger.error("Got bad raw_input reply: ") |
|
371 | logger.error("Got bad raw_input reply: ") | |
373 | logger.error(str(Message(parent))) |
|
372 | logger.error(str(Message(parent))) | |
374 | value = '' |
|
373 | value = '' | |
375 | return value |
|
374 | return value | |
376 |
|
375 | |||
377 | def _complete(self, msg): |
|
376 | def _complete(self, msg): | |
378 | c = msg['content'] |
|
377 | c = msg['content'] | |
379 | try: |
|
378 | try: | |
380 | cpos = int(c['cursor_pos']) |
|
379 | cpos = int(c['cursor_pos']) | |
381 | except: |
|
380 | except: | |
382 | # If we don't get something that we can convert to an integer, at |
|
381 | # If we don't get something that we can convert to an integer, at | |
383 | # least attempt the completion guessing the cursor is at the end of |
|
382 | # least attempt the completion guessing the cursor is at the end of | |
384 | # the text, if there's any, and otherwise of the line |
|
383 | # the text, if there's any, and otherwise of the line | |
385 | cpos = len(c['text']) |
|
384 | cpos = len(c['text']) | |
386 | if cpos==0: |
|
385 | if cpos==0: | |
387 | cpos = len(c['line']) |
|
386 | cpos = len(c['line']) | |
388 | return self.shell.complete(c['text'], c['line'], cpos) |
|
387 | return self.shell.complete(c['text'], c['line'], cpos) | |
389 |
|
388 | |||
390 | def _object_info(self, context): |
|
389 | def _object_info(self, context): | |
391 | symbol, leftover = self._symbol_from_context(context) |
|
390 | symbol, leftover = self._symbol_from_context(context) | |
392 | if symbol is not None and not leftover: |
|
391 | if symbol is not None and not leftover: | |
393 | doc = getattr(symbol, '__doc__', '') |
|
392 | doc = getattr(symbol, '__doc__', '') | |
394 | else: |
|
393 | else: | |
395 | doc = '' |
|
394 | doc = '' | |
396 | object_info = dict(docstring = doc) |
|
395 | object_info = dict(docstring = doc) | |
397 | return object_info |
|
396 | return object_info | |
398 |
|
397 | |||
399 | def _symbol_from_context(self, context): |
|
398 | def _symbol_from_context(self, context): | |
400 | if not context: |
|
399 | if not context: | |
401 | return None, context |
|
400 | return None, context | |
402 |
|
401 | |||
403 | base_symbol_string = context[0] |
|
402 | base_symbol_string = context[0] | |
404 | symbol = self.shell.user_ns.get(base_symbol_string, None) |
|
403 | symbol = self.shell.user_ns.get(base_symbol_string, None) | |
405 | if symbol is None: |
|
404 | if symbol is None: | |
406 | symbol = __builtin__.__dict__.get(base_symbol_string, None) |
|
405 | symbol = __builtin__.__dict__.get(base_symbol_string, None) | |
407 | if symbol is None: |
|
406 | if symbol is None: | |
408 | return None, context |
|
407 | return None, context | |
409 |
|
408 | |||
410 | context = context[1:] |
|
409 | context = context[1:] | |
411 | for i, name in enumerate(context): |
|
410 | for i, name in enumerate(context): | |
412 | new_symbol = getattr(symbol, name, None) |
|
411 | new_symbol = getattr(symbol, name, None) | |
413 | if new_symbol is None: |
|
412 | if new_symbol is None: | |
414 | return symbol, context[i:] |
|
413 | return symbol, context[i:] | |
415 | else: |
|
414 | else: | |
416 | symbol = new_symbol |
|
415 | symbol = new_symbol | |
417 |
|
416 | |||
418 | return symbol, [] |
|
417 | return symbol, [] | |
419 |
|
418 | |||
420 | def _at_shutdown(self): |
|
419 | def _at_shutdown(self): | |
421 | """Actions taken at shutdown by the kernel, called by python's atexit. |
|
420 | """Actions taken at shutdown by the kernel, called by python's atexit. | |
422 | """ |
|
421 | """ | |
423 | # io.rprint("Kernel at_shutdown") # dbg |
|
422 | # io.rprint("Kernel at_shutdown") # dbg | |
424 | if self._shutdown_message is not None: |
|
423 | if self._shutdown_message is not None: | |
425 | self.session.send(self.reply_socket, self._shutdown_message) |
|
424 | self.session.send(self.reply_socket, self._shutdown_message) | |
426 | self.session.send(self.pub_socket, self._shutdown_message) |
|
425 | self.session.send(self.pub_socket, self._shutdown_message) | |
427 | logger.debug(str(self._shutdown_message)) |
|
426 | logger.debug(str(self._shutdown_message)) | |
428 | # A very short sleep to give zmq time to flush its message buffers |
|
427 | # A very short sleep to give zmq time to flush its message buffers | |
429 | # before Python truly shuts down. |
|
428 | # before Python truly shuts down. | |
430 | time.sleep(0.01) |
|
429 | time.sleep(0.01) | |
431 |
|
430 | |||
432 |
|
431 | |||
433 | class QtKernel(Kernel): |
|
432 | class QtKernel(Kernel): | |
434 | """A Kernel subclass with Qt support.""" |
|
433 | """A Kernel subclass with Qt support.""" | |
435 |
|
434 | |||
436 | def start(self): |
|
435 | def start(self): | |
437 | """Start a kernel with QtPy4 event loop integration.""" |
|
436 | """Start a kernel with QtPy4 event loop integration.""" | |
438 |
|
437 | |||
439 | from PyQt4 import QtCore |
|
438 | from PyQt4 import QtCore | |
440 | from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 |
|
439 | from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 | |
441 |
|
440 | |||
442 | self.app = get_app_qt4([" "]) |
|
441 | self.app = get_app_qt4([" "]) | |
443 | self.app.setQuitOnLastWindowClosed(False) |
|
442 | self.app.setQuitOnLastWindowClosed(False) | |
444 | self.timer = QtCore.QTimer() |
|
443 | self.timer = QtCore.QTimer() | |
445 | self.timer.timeout.connect(self.do_one_iteration) |
|
444 | self.timer.timeout.connect(self.do_one_iteration) | |
446 | # Units for the timer are in milliseconds |
|
445 | # Units for the timer are in milliseconds | |
447 | self.timer.start(1000*self._poll_interval) |
|
446 | self.timer.start(1000*self._poll_interval) | |
448 | start_event_loop_qt4(self.app) |
|
447 | start_event_loop_qt4(self.app) | |
449 |
|
448 | |||
450 |
|
449 | |||
451 | class WxKernel(Kernel): |
|
450 | class WxKernel(Kernel): | |
452 | """A Kernel subclass with Wx support.""" |
|
451 | """A Kernel subclass with Wx support.""" | |
453 |
|
452 | |||
454 | def start(self): |
|
453 | def start(self): | |
455 | """Start a kernel with wx event loop support.""" |
|
454 | """Start a kernel with wx event loop support.""" | |
456 |
|
455 | |||
457 | import wx |
|
456 | import wx | |
458 | from IPython.lib.guisupport import start_event_loop_wx |
|
457 | from IPython.lib.guisupport import start_event_loop_wx | |
459 |
|
458 | |||
460 | doi = self.do_one_iteration |
|
459 | doi = self.do_one_iteration | |
461 | # Wx uses milliseconds |
|
460 | # Wx uses milliseconds | |
462 | poll_interval = int(1000*self._poll_interval) |
|
461 | poll_interval = int(1000*self._poll_interval) | |
463 |
|
462 | |||
464 | # We have to put the wx.Timer in a wx.Frame for it to fire properly. |
|
463 | # We have to put the wx.Timer in a wx.Frame for it to fire properly. | |
465 | # We make the Frame hidden when we create it in the main app below. |
|
464 | # We make the Frame hidden when we create it in the main app below. | |
466 | class TimerFrame(wx.Frame): |
|
465 | class TimerFrame(wx.Frame): | |
467 | def __init__(self, func): |
|
466 | def __init__(self, func): | |
468 | wx.Frame.__init__(self, None, -1) |
|
467 | wx.Frame.__init__(self, None, -1) | |
469 | self.timer = wx.Timer(self) |
|
468 | self.timer = wx.Timer(self) | |
470 | # Units for the timer are in milliseconds |
|
469 | # Units for the timer are in milliseconds | |
471 | self.timer.Start(poll_interval) |
|
470 | self.timer.Start(poll_interval) | |
472 | self.Bind(wx.EVT_TIMER, self.on_timer) |
|
471 | self.Bind(wx.EVT_TIMER, self.on_timer) | |
473 | self.func = func |
|
472 | self.func = func | |
474 |
|
473 | |||
475 | def on_timer(self, event): |
|
474 | def on_timer(self, event): | |
476 | self.func() |
|
475 | self.func() | |
477 |
|
476 | |||
478 | # We need a custom wx.App to create our Frame subclass that has the |
|
477 | # We need a custom wx.App to create our Frame subclass that has the | |
479 | # wx.Timer to drive the ZMQ event loop. |
|
478 | # wx.Timer to drive the ZMQ event loop. | |
480 | class IPWxApp(wx.App): |
|
479 | class IPWxApp(wx.App): | |
481 | def OnInit(self): |
|
480 | def OnInit(self): | |
482 | self.frame = TimerFrame(doi) |
|
481 | self.frame = TimerFrame(doi) | |
483 | self.frame.Show(False) |
|
482 | self.frame.Show(False) | |
484 | return True |
|
483 | return True | |
485 |
|
484 | |||
486 | # The redirect=False here makes sure that wx doesn't replace |
|
485 | # The redirect=False here makes sure that wx doesn't replace | |
487 | # sys.stdout/stderr with its own classes. |
|
486 | # sys.stdout/stderr with its own classes. | |
488 | self.app = IPWxApp(redirect=False) |
|
487 | self.app = IPWxApp(redirect=False) | |
489 | start_event_loop_wx(self.app) |
|
488 | start_event_loop_wx(self.app) | |
490 |
|
489 | |||
491 |
|
490 | |||
492 | class TkKernel(Kernel): |
|
491 | class TkKernel(Kernel): | |
493 | """A Kernel subclass with Tk support.""" |
|
492 | """A Kernel subclass with Tk support.""" | |
494 |
|
493 | |||
495 | def start(self): |
|
494 | def start(self): | |
496 | """Start a Tk enabled event loop.""" |
|
495 | """Start a Tk enabled event loop.""" | |
497 |
|
496 | |||
498 | import Tkinter |
|
497 | import Tkinter | |
499 | doi = self.do_one_iteration |
|
498 | doi = self.do_one_iteration | |
500 | # Tk uses milliseconds |
|
499 | # Tk uses milliseconds | |
501 | poll_interval = int(1000*self._poll_interval) |
|
500 | poll_interval = int(1000*self._poll_interval) | |
502 | # For Tkinter, we create a Tk object and call its withdraw method. |
|
501 | # For Tkinter, we create a Tk object and call its withdraw method. | |
503 | class Timer(object): |
|
502 | class Timer(object): | |
504 | def __init__(self, func): |
|
503 | def __init__(self, func): | |
505 | self.app = Tkinter.Tk() |
|
504 | self.app = Tkinter.Tk() | |
506 | self.app.withdraw() |
|
505 | self.app.withdraw() | |
507 | self.func = func |
|
506 | self.func = func | |
508 |
|
507 | |||
509 | def on_timer(self): |
|
508 | def on_timer(self): | |
510 | self.func() |
|
509 | self.func() | |
511 | self.app.after(poll_interval, self.on_timer) |
|
510 | self.app.after(poll_interval, self.on_timer) | |
512 |
|
511 | |||
513 | def start(self): |
|
512 | def start(self): | |
514 | self.on_timer() # Call it once to get things going. |
|
513 | self.on_timer() # Call it once to get things going. | |
515 | self.app.mainloop() |
|
514 | self.app.mainloop() | |
516 |
|
515 | |||
517 | self.timer = Timer(doi) |
|
516 | self.timer = Timer(doi) | |
518 | self.timer.start() |
|
517 | self.timer.start() | |
519 |
|
518 | |||
520 |
|
519 | |||
521 | class GTKKernel(Kernel): |
|
520 | class GTKKernel(Kernel): | |
522 | """A Kernel subclass with GTK support.""" |
|
521 | """A Kernel subclass with GTK support.""" | |
523 |
|
522 | |||
524 | def start(self): |
|
523 | def start(self): | |
525 | """Start the kernel, coordinating with the GTK event loop""" |
|
524 | """Start the kernel, coordinating with the GTK event loop""" | |
526 | from .gui.gtkembed import GTKEmbed |
|
525 | from .gui.gtkembed import GTKEmbed | |
527 |
|
526 | |||
528 | gtk_kernel = GTKEmbed(self) |
|
527 | gtk_kernel = GTKEmbed(self) | |
529 | gtk_kernel.start() |
|
528 | gtk_kernel.start() | |
530 |
|
529 | |||
531 |
|
530 | |||
532 | #----------------------------------------------------------------------------- |
|
531 | #----------------------------------------------------------------------------- | |
533 | # Kernel main and launch functions |
|
532 | # Kernel main and launch functions | |
534 | #----------------------------------------------------------------------------- |
|
533 | #----------------------------------------------------------------------------- | |
535 |
|
534 | |||
536 | def launch_kernel(ip=None, xrep_port=0, pub_port=0, req_port=0, hb_port=0, |
|
535 | def launch_kernel(ip=None, xrep_port=0, pub_port=0, req_port=0, hb_port=0, | |
537 | independent=False, pylab=False, colors=None): |
|
536 | independent=False, pylab=False, colors=None): | |
538 | """Launches a localhost kernel, binding to the specified ports. |
|
537 | """Launches a localhost kernel, binding to the specified ports. | |
539 |
|
538 | |||
540 | Parameters |
|
539 | Parameters | |
541 | ---------- |
|
540 | ---------- | |
542 | ip : str, optional |
|
541 | ip : str, optional | |
543 | The ip address the kernel will bind to. |
|
542 | The ip address the kernel will bind to. | |
544 |
|
543 | |||
545 | xrep_port : int, optional |
|
544 | xrep_port : int, optional | |
546 | The port to use for XREP channel. |
|
545 | The port to use for XREP channel. | |
547 |
|
546 | |||
548 | pub_port : int, optional |
|
547 | pub_port : int, optional | |
549 | The port to use for the SUB channel. |
|
548 | The port to use for the SUB channel. | |
550 |
|
549 | |||
551 | req_port : int, optional |
|
550 | req_port : int, optional | |
552 | The port to use for the REQ (raw input) channel. |
|
551 | The port to use for the REQ (raw input) channel. | |
553 |
|
552 | |||
554 | hb_port : int, optional |
|
553 | hb_port : int, optional | |
555 | The port to use for the hearbeat REP channel. |
|
554 | The port to use for the hearbeat REP channel. | |
556 |
|
555 | |||
557 | independent : bool, optional (default False) |
|
556 | independent : bool, optional (default False) | |
558 | If set, the kernel process is guaranteed to survive if this process |
|
557 | If set, the kernel process is guaranteed to survive if this process | |
559 | dies. If not set, an effort is made to ensure that the kernel is killed |
|
558 | dies. If not set, an effort is made to ensure that the kernel is killed | |
560 | when this process dies. Note that in this case it is still good practice |
|
559 | when this process dies. Note that in this case it is still good practice | |
561 | to kill kernels manually before exiting. |
|
560 | to kill kernels manually before exiting. | |
562 |
|
561 | |||
563 | pylab : bool or string, optional (default False) |
|
562 | pylab : bool or string, optional (default False) | |
564 | If not False, the kernel will be launched with pylab enabled. If a |
|
563 | If not False, the kernel will be launched with pylab enabled. If a | |
565 | string is passed, matplotlib will use the specified backend. Otherwise, |
|
564 | string is passed, matplotlib will use the specified backend. Otherwise, | |
566 | matplotlib's default backend will be used. |
|
565 | matplotlib's default backend will be used. | |
567 |
|
566 | |||
568 | colors : None or string, optional (default None) |
|
567 | colors : None or string, optional (default None) | |
569 | If not None, specify the color scheme. One of (NoColor, LightBG, Linux) |
|
568 | If not None, specify the color scheme. One of (NoColor, LightBG, Linux) | |
570 |
|
569 | |||
571 | Returns |
|
570 | Returns | |
572 | ------- |
|
571 | ------- | |
573 | A tuple of form: |
|
572 | A tuple of form: | |
574 | (kernel_process, xrep_port, pub_port, req_port) |
|
573 | (kernel_process, xrep_port, pub_port, req_port) | |
575 | where kernel_process is a Popen object and the ports are integers. |
|
574 | where kernel_process is a Popen object and the ports are integers. | |
576 | """ |
|
575 | """ | |
577 | extra_arguments = [] |
|
576 | extra_arguments = [] | |
578 | if pylab: |
|
577 | if pylab: | |
579 | extra_arguments.append('--pylab') |
|
578 | extra_arguments.append('--pylab') | |
580 | if isinstance(pylab, basestring): |
|
579 | if isinstance(pylab, basestring): | |
581 | extra_arguments.append(pylab) |
|
580 | extra_arguments.append(pylab) | |
582 | if ip is not None: |
|
581 | if ip is not None: | |
583 | extra_arguments.append('--ip') |
|
582 | extra_arguments.append('--ip') | |
584 | if isinstance(ip, basestring): |
|
583 | if isinstance(ip, basestring): | |
585 | extra_arguments.append(ip) |
|
584 | extra_arguments.append(ip) | |
586 | if colors is not None: |
|
585 | if colors is not None: | |
587 | extra_arguments.append('--colors') |
|
586 | extra_arguments.append('--colors') | |
588 | extra_arguments.append(colors) |
|
587 | extra_arguments.append(colors) | |
589 | return base_launch_kernel('from IPython.zmq.ipkernel import main; main()', |
|
588 | return base_launch_kernel('from IPython.zmq.ipkernel import main; main()', | |
590 | xrep_port, pub_port, req_port, hb_port, |
|
589 | xrep_port, pub_port, req_port, hb_port, | |
591 | independent, extra_arguments) |
|
590 | independent, extra_arguments) | |
592 |
|
591 | |||
593 |
|
592 | |||
594 | def main(): |
|
593 | def main(): | |
595 | """ The IPython kernel main entry point. |
|
594 | """ The IPython kernel main entry point. | |
596 | """ |
|
595 | """ | |
597 | parser = make_argument_parser() |
|
596 | parser = make_argument_parser() | |
598 | parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?', |
|
597 | parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?', | |
599 | const='auto', help = \ |
|
598 | const='auto', help = \ | |
600 | "Pre-load matplotlib and numpy for interactive use. If GUI is not \ |
|
599 | "Pre-load matplotlib and numpy for interactive use. If GUI is not \ | |
601 | given, the GUI backend is matplotlib's, otherwise use one of: \ |
|
600 | given, the GUI backend is matplotlib's, otherwise use one of: \ | |
602 | ['tk', 'gtk', 'qt', 'wx', 'inline'].") |
|
601 | ['tk', 'gtk', 'qt', 'wx', 'inline'].") | |
603 | parser.add_argument('--colors', |
|
602 | parser.add_argument('--colors', | |
604 | type=str, dest='colors', |
|
603 | type=str, dest='colors', | |
605 | help="Set the color scheme (NoColor, Linux, and LightBG).", |
|
604 | help="Set the color scheme (NoColor, Linux, and LightBG).", | |
606 | metavar='ZMQInteractiveShell.colors') |
|
605 | metavar='ZMQInteractiveShell.colors') | |
607 | namespace = parser.parse_args() |
|
606 | namespace = parser.parse_args() | |
608 |
|
607 | |||
609 | kernel_class = Kernel |
|
608 | kernel_class = Kernel | |
610 |
|
609 | |||
611 | kernel_classes = { |
|
610 | kernel_classes = { | |
612 | 'qt' : QtKernel, |
|
611 | 'qt' : QtKernel, | |
613 | 'qt4': QtKernel, |
|
612 | 'qt4': QtKernel, | |
614 | 'inline': Kernel, |
|
613 | 'inline': Kernel, | |
615 | 'wx' : WxKernel, |
|
614 | 'wx' : WxKernel, | |
616 | 'tk' : TkKernel, |
|
615 | 'tk' : TkKernel, | |
617 | 'gtk': GTKKernel, |
|
616 | 'gtk': GTKKernel, | |
618 | } |
|
617 | } | |
619 | if namespace.pylab: |
|
618 | if namespace.pylab: | |
620 | if namespace.pylab == 'auto': |
|
619 | if namespace.pylab == 'auto': | |
621 | gui, backend = pylabtools.find_gui_and_backend() |
|
620 | gui, backend = pylabtools.find_gui_and_backend() | |
622 | else: |
|
621 | else: | |
623 | gui, backend = pylabtools.find_gui_and_backend(namespace.pylab) |
|
622 | gui, backend = pylabtools.find_gui_and_backend(namespace.pylab) | |
624 | kernel_class = kernel_classes.get(gui) |
|
623 | kernel_class = kernel_classes.get(gui) | |
625 | if kernel_class is None: |
|
624 | if kernel_class is None: | |
626 | raise ValueError('GUI is not supported: %r' % gui) |
|
625 | raise ValueError('GUI is not supported: %r' % gui) | |
627 | pylabtools.activate_matplotlib(backend) |
|
626 | pylabtools.activate_matplotlib(backend) | |
628 | if namespace.colors: |
|
627 | if namespace.colors: | |
629 | ZMQInteractiveShell.colors=namespace.colors |
|
628 | ZMQInteractiveShell.colors=namespace.colors | |
630 |
|
629 | |||
631 | kernel = make_kernel(namespace, kernel_class, OutStream) |
|
630 | kernel = make_kernel(namespace, kernel_class, OutStream) | |
632 |
|
631 | |||
633 | if namespace.pylab: |
|
632 | if namespace.pylab: | |
634 | pylabtools.import_pylab(kernel.shell.user_ns, backend, |
|
633 | pylabtools.import_pylab(kernel.shell.user_ns, backend, | |
635 | shell=kernel.shell) |
|
634 | shell=kernel.shell) | |
636 |
|
635 | |||
637 | start_kernel(namespace, kernel) |
|
636 | start_kernel(namespace, kernel) | |
638 |
|
637 | |||
639 |
|
638 | |||
640 | if __name__ == '__main__': |
|
639 | if __name__ == '__main__': | |
641 | main() |
|
640 | main() |
@@ -1,910 +1,914 b'' | |||||
1 | """Base classes to manage the interaction with a running kernel. |
|
1 | """Base classes to manage the interaction with a running kernel. | |
2 |
|
2 | |||
3 | TODO |
|
3 | TODO | |
4 | * Create logger to handle debugging and console messages. |
|
4 | * Create logger to handle debugging and console messages. | |
5 | """ |
|
5 | """ | |
6 |
|
6 | |||
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Copyright (C) 2008-2010 The IPython Development Team |
|
8 | # Copyright (C) 2008-2010 The IPython Development Team | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | # Standard library imports. |
|
18 | # Standard library imports. | |
19 | import atexit |
|
19 | import atexit | |
20 | from Queue import Queue, Empty |
|
20 | from Queue import Queue, Empty | |
21 | from subprocess import Popen |
|
21 | from subprocess import Popen | |
22 | import signal |
|
22 | import signal | |
23 | import sys |
|
23 | import sys | |
24 | from threading import Thread |
|
24 | from threading import Thread | |
25 | import time |
|
25 | import time | |
26 | import logging |
|
26 | import logging | |
27 |
|
27 | |||
28 | # System library imports. |
|
28 | # System library imports. | |
29 | import zmq |
|
29 | import zmq | |
30 | from zmq import POLLIN, POLLOUT, POLLERR |
|
30 | from zmq import POLLIN, POLLOUT, POLLERR | |
31 | from zmq.eventloop import ioloop |
|
31 | from zmq.eventloop import ioloop | |
32 |
|
32 | |||
33 | # Local imports. |
|
33 | # Local imports. | |
34 | from IPython.utils import io |
|
34 | from IPython.utils import io | |
35 | from IPython.utils.localinterfaces import LOCALHOST, LOCAL_IPS |
|
35 | from IPython.utils.localinterfaces import LOCALHOST, LOCAL_IPS | |
36 | from IPython.utils.traitlets import HasTraits, Any, Instance, Type, TCPAddress |
|
36 | from IPython.utils.traitlets import HasTraits, Any, Instance, Type, TCPAddress | |
37 | from session import Session, Message |
|
37 | from session import Session, Message | |
38 |
|
38 | |||
39 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
40 | # Constants and exceptions |
|
40 | # Constants and exceptions | |
41 | #----------------------------------------------------------------------------- |
|
41 | #----------------------------------------------------------------------------- | |
42 |
|
42 | |||
43 | class InvalidPortNumber(Exception): |
|
43 | class InvalidPortNumber(Exception): | |
44 | pass |
|
44 | pass | |
45 |
|
45 | |||
46 | #----------------------------------------------------------------------------- |
|
46 | #----------------------------------------------------------------------------- | |
47 | # Utility functions |
|
47 | # Utility functions | |
48 | #----------------------------------------------------------------------------- |
|
48 | #----------------------------------------------------------------------------- | |
49 |
|
49 | |||
50 | # some utilities to validate message structure, these might get moved elsewhere |
|
50 | # some utilities to validate message structure, these might get moved elsewhere | |
51 | # if they prove to have more generic utility |
|
51 | # if they prove to have more generic utility | |
52 |
|
52 | |||
53 | def validate_string_list(lst): |
|
53 | def validate_string_list(lst): | |
54 | """Validate that the input is a list of strings. |
|
54 | """Validate that the input is a list of strings. | |
55 |
|
55 | |||
56 | Raises ValueError if not.""" |
|
56 | Raises ValueError if not.""" | |
57 | if not isinstance(lst, list): |
|
57 | if not isinstance(lst, list): | |
58 | raise ValueError('input %r must be a list' % lst) |
|
58 | raise ValueError('input %r must be a list' % lst) | |
59 | for x in lst: |
|
59 | for x in lst: | |
60 | if not isinstance(x, basestring): |
|
60 | if not isinstance(x, basestring): | |
61 | raise ValueError('element %r in list must be a string' % x) |
|
61 | raise ValueError('element %r in list must be a string' % x) | |
62 |
|
62 | |||
63 |
|
63 | |||
64 | def validate_string_dict(dct): |
|
64 | def validate_string_dict(dct): | |
65 | """Validate that the input is a dict with string keys and values. |
|
65 | """Validate that the input is a dict with string keys and values. | |
66 |
|
66 | |||
67 | Raises ValueError if not.""" |
|
67 | Raises ValueError if not.""" | |
68 | for k,v in dct.iteritems(): |
|
68 | for k,v in dct.iteritems(): | |
69 | if not isinstance(k, basestring): |
|
69 | if not isinstance(k, basestring): | |
70 | raise ValueError('key %r in dict must be a string' % k) |
|
70 | raise ValueError('key %r in dict must be a string' % k) | |
71 | if not isinstance(v, basestring): |
|
71 | if not isinstance(v, basestring): | |
72 | raise ValueError('value %r in dict must be a string' % v) |
|
72 | raise ValueError('value %r in dict must be a string' % v) | |
73 |
|
73 | |||
74 |
|
74 | |||
75 | #----------------------------------------------------------------------------- |
|
75 | #----------------------------------------------------------------------------- | |
76 | # ZMQ Socket Channel classes |
|
76 | # ZMQ Socket Channel classes | |
77 | #----------------------------------------------------------------------------- |
|
77 | #----------------------------------------------------------------------------- | |
78 |
|
78 | |||
79 | class ZmqSocketChannel(Thread): |
|
79 | class ZmqSocketChannel(Thread): | |
80 | """The base class for the channels that use ZMQ sockets. |
|
80 | """The base class for the channels that use ZMQ sockets. | |
81 | """ |
|
81 | """ | |
82 | context = None |
|
82 | context = None | |
83 | session = None |
|
83 | session = None | |
84 | socket = None |
|
84 | socket = None | |
85 | ioloop = None |
|
85 | ioloop = None | |
86 | iostate = None |
|
86 | iostate = None | |
87 | _address = None |
|
87 | _address = None | |
88 |
|
88 | |||
89 | def __init__(self, context, session, address): |
|
89 | def __init__(self, context, session, address): | |
90 | """Create a channel |
|
90 | """Create a channel | |
91 |
|
91 | |||
92 | Parameters |
|
92 | Parameters | |
93 | ---------- |
|
93 | ---------- | |
94 | context : :class:`zmq.Context` |
|
94 | context : :class:`zmq.Context` | |
95 | The ZMQ context to use. |
|
95 | The ZMQ context to use. | |
96 | session : :class:`session.Session` |
|
96 | session : :class:`session.Session` | |
97 | The session to use. |
|
97 | The session to use. | |
98 | address : tuple |
|
98 | address : tuple | |
99 | Standard (ip, port) tuple that the kernel is listening on. |
|
99 | Standard (ip, port) tuple that the kernel is listening on. | |
100 | """ |
|
100 | """ | |
101 | super(ZmqSocketChannel, self).__init__() |
|
101 | super(ZmqSocketChannel, self).__init__() | |
102 | self.daemon = True |
|
102 | self.daemon = True | |
103 |
|
103 | |||
104 | self.context = context |
|
104 | self.context = context | |
105 | self.session = session |
|
105 | self.session = session | |
106 | if address[1] == 0: |
|
106 | if address[1] == 0: | |
107 | message = 'The port number for a channel cannot be 0.' |
|
107 | message = 'The port number for a channel cannot be 0.' | |
108 | raise InvalidPortNumber(message) |
|
108 | raise InvalidPortNumber(message) | |
109 | self._address = address |
|
109 | self._address = address | |
110 |
|
110 | |||
111 | def stop(self): |
|
111 | def stop(self): | |
112 | """Stop the channel's activity. |
|
112 | """Stop the channel's activity. | |
113 |
|
113 | |||
114 | This calls :method:`Thread.join` and returns when the thread |
|
114 | This calls :method:`Thread.join` and returns when the thread | |
115 | terminates. :class:`RuntimeError` will be raised if |
|
115 | terminates. :class:`RuntimeError` will be raised if | |
116 | :method:`self.start` is called again. |
|
116 | :method:`self.start` is called again. | |
117 | """ |
|
117 | """ | |
118 | self.join() |
|
118 | self.join() | |
119 |
|
119 | |||
120 | @property |
|
120 | @property | |
121 | def address(self): |
|
121 | def address(self): | |
122 | """Get the channel's address as an (ip, port) tuple. |
|
122 | """Get the channel's address as an (ip, port) tuple. | |
123 |
|
123 | |||
124 | By the default, the address is (localhost, 0), where 0 means a random |
|
124 | By the default, the address is (localhost, 0), where 0 means a random | |
125 | port. |
|
125 | port. | |
126 | """ |
|
126 | """ | |
127 | return self._address |
|
127 | return self._address | |
128 |
|
128 | |||
129 | def add_io_state(self, state): |
|
129 | def add_io_state(self, state): | |
130 | """Add IO state to the eventloop. |
|
130 | """Add IO state to the eventloop. | |
131 |
|
131 | |||
132 | Parameters |
|
132 | Parameters | |
133 | ---------- |
|
133 | ---------- | |
134 | state : zmq.POLLIN|zmq.POLLOUT|zmq.POLLERR |
|
134 | state : zmq.POLLIN|zmq.POLLOUT|zmq.POLLERR | |
135 | The IO state flag to set. |
|
135 | The IO state flag to set. | |
136 |
|
136 | |||
137 | This is thread safe as it uses the thread safe IOLoop.add_callback. |
|
137 | This is thread safe as it uses the thread safe IOLoop.add_callback. | |
138 | """ |
|
138 | """ | |
139 | def add_io_state_callback(): |
|
139 | def add_io_state_callback(): | |
140 | if not self.iostate & state: |
|
140 | if not self.iostate & state: | |
141 | self.iostate = self.iostate | state |
|
141 | self.iostate = self.iostate | state | |
142 | self.ioloop.update_handler(self.socket, self.iostate) |
|
142 | self.ioloop.update_handler(self.socket, self.iostate) | |
143 | self.ioloop.add_callback(add_io_state_callback) |
|
143 | self.ioloop.add_callback(add_io_state_callback) | |
144 |
|
144 | |||
145 | def drop_io_state(self, state): |
|
145 | def drop_io_state(self, state): | |
146 | """Drop IO state from the eventloop. |
|
146 | """Drop IO state from the eventloop. | |
147 |
|
147 | |||
148 | Parameters |
|
148 | Parameters | |
149 | ---------- |
|
149 | ---------- | |
150 | state : zmq.POLLIN|zmq.POLLOUT|zmq.POLLERR |
|
150 | state : zmq.POLLIN|zmq.POLLOUT|zmq.POLLERR | |
151 | The IO state flag to set. |
|
151 | The IO state flag to set. | |
152 |
|
152 | |||
153 | This is thread safe as it uses the thread safe IOLoop.add_callback. |
|
153 | This is thread safe as it uses the thread safe IOLoop.add_callback. | |
154 | """ |
|
154 | """ | |
155 | def drop_io_state_callback(): |
|
155 | def drop_io_state_callback(): | |
156 | if self.iostate & state: |
|
156 | if self.iostate & state: | |
157 | self.iostate = self.iostate & (~state) |
|
157 | self.iostate = self.iostate & (~state) | |
158 | self.ioloop.update_handler(self.socket, self.iostate) |
|
158 | self.ioloop.update_handler(self.socket, self.iostate) | |
159 | self.ioloop.add_callback(drop_io_state_callback) |
|
159 | self.ioloop.add_callback(drop_io_state_callback) | |
160 |
|
160 | |||
161 |
|
161 | |||
162 | class XReqSocketChannel(ZmqSocketChannel): |
|
162 | class XReqSocketChannel(ZmqSocketChannel): | |
163 | """The XREQ channel for issues request/replies to the kernel. |
|
163 | """The XREQ channel for issues request/replies to the kernel. | |
164 | """ |
|
164 | """ | |
165 |
|
165 | |||
166 | command_queue = None |
|
166 | command_queue = None | |
167 |
|
167 | |||
168 | def __init__(self, context, session, address): |
|
168 | def __init__(self, context, session, address): | |
169 | super(XReqSocketChannel, self).__init__(context, session, address) |
|
169 | super(XReqSocketChannel, self).__init__(context, session, address) | |
170 | self.command_queue = Queue() |
|
170 | self.command_queue = Queue() | |
171 | self.ioloop = ioloop.IOLoop() |
|
171 | self.ioloop = ioloop.IOLoop() | |
172 |
|
172 | |||
173 | def run(self): |
|
173 | def run(self): | |
174 | """The thread's main activity. Call start() instead.""" |
|
174 | """The thread's main activity. Call start() instead.""" | |
175 | self.socket = self.context.socket(zmq.XREQ) |
|
175 | self.socket = self.context.socket(zmq.XREQ) | |
176 | self.socket.setsockopt(zmq.IDENTITY, self.session.session) |
|
176 | self.socket.setsockopt(zmq.IDENTITY, self.session.session) | |
177 | self.socket.connect('tcp://%s:%i' % self.address) |
|
177 | self.socket.connect('tcp://%s:%i' % self.address) | |
178 | self.iostate = POLLERR|POLLIN |
|
178 | self.iostate = POLLERR|POLLIN | |
179 | self.ioloop.add_handler(self.socket, self._handle_events, |
|
179 | self.ioloop.add_handler(self.socket, self._handle_events, | |
180 | self.iostate) |
|
180 | self.iostate) | |
181 | self.ioloop.start() |
|
181 | self.ioloop.start() | |
182 |
|
182 | |||
183 | def stop(self): |
|
183 | def stop(self): | |
184 | self.ioloop.stop() |
|
184 | self.ioloop.stop() | |
185 | super(XReqSocketChannel, self).stop() |
|
185 | super(XReqSocketChannel, self).stop() | |
186 |
|
186 | |||
187 | def call_handlers(self, msg): |
|
187 | def call_handlers(self, msg): | |
188 | """This method is called in the ioloop thread when a message arrives. |
|
188 | """This method is called in the ioloop thread when a message arrives. | |
189 |
|
189 | |||
190 | Subclasses should override this method to handle incoming messages. |
|
190 | Subclasses should override this method to handle incoming messages. | |
191 | It is important to remember that this method is called in the thread |
|
191 | It is important to remember that this method is called in the thread | |
192 | so that some logic must be done to ensure that the application leve |
|
192 | so that some logic must be done to ensure that the application leve | |
193 | handlers are called in the application thread. |
|
193 | handlers are called in the application thread. | |
194 | """ |
|
194 | """ | |
195 | raise NotImplementedError('call_handlers must be defined in a subclass.') |
|
195 | raise NotImplementedError('call_handlers must be defined in a subclass.') | |
196 |
|
196 | |||
197 | def execute(self, code, silent=False, |
|
197 | def execute(self, code, silent=False, | |
198 | user_variables=None, user_expressions=None): |
|
198 | user_variables=None, user_expressions=None): | |
199 | """Execute code in the kernel. |
|
199 | """Execute code in the kernel. | |
200 |
|
200 | |||
201 | Parameters |
|
201 | Parameters | |
202 | ---------- |
|
202 | ---------- | |
203 | code : str |
|
203 | code : str | |
204 | A string of Python code. |
|
204 | A string of Python code. | |
205 |
|
205 | |||
206 | silent : bool, optional (default False) |
|
206 | silent : bool, optional (default False) | |
207 | If set, the kernel will execute the code as quietly possible. |
|
207 | If set, the kernel will execute the code as quietly possible. | |
208 |
|
208 | |||
209 | user_variables : list, optional |
|
209 | user_variables : list, optional | |
210 | A list of variable names to pull from the user's namespace. They |
|
210 | A list of variable names to pull from the user's namespace. They | |
211 | will come back as a dict with these names as keys and their |
|
211 | will come back as a dict with these names as keys and their | |
212 | :func:`repr` as values. |
|
212 | :func:`repr` as values. | |
213 |
|
213 | |||
214 | user_expressions : dict, optional |
|
214 | user_expressions : dict, optional | |
215 | A dict with string keys and to pull from the user's |
|
215 | A dict with string keys and to pull from the user's | |
216 | namespace. They will come back as a dict with these names as keys |
|
216 | namespace. They will come back as a dict with these names as keys | |
217 | and their :func:`repr` as values. |
|
217 | and their :func:`repr` as values. | |
218 |
|
218 | |||
219 | Returns |
|
219 | Returns | |
220 | ------- |
|
220 | ------- | |
221 | The msg_id of the message sent. |
|
221 | The msg_id of the message sent. | |
222 | """ |
|
222 | """ | |
223 | if user_variables is None: |
|
223 | if user_variables is None: | |
224 | user_variables = [] |
|
224 | user_variables = [] | |
225 | if user_expressions is None: |
|
225 | if user_expressions is None: | |
226 | user_expressions = {} |
|
226 | user_expressions = {} | |
227 |
|
227 | |||
228 | # Don't waste network traffic if inputs are invalid |
|
228 | # Don't waste network traffic if inputs are invalid | |
229 | if not isinstance(code, basestring): |
|
229 | if not isinstance(code, basestring): | |
230 | raise ValueError('code %r must be a string' % code) |
|
230 | raise ValueError('code %r must be a string' % code) | |
231 | validate_string_list(user_variables) |
|
231 | validate_string_list(user_variables) | |
232 | validate_string_dict(user_expressions) |
|
232 | validate_string_dict(user_expressions) | |
233 |
|
233 | |||
234 | # Create class for content/msg creation. Related to, but possibly |
|
234 | # Create class for content/msg creation. Related to, but possibly | |
235 | # not in Session. |
|
235 | # not in Session. | |
236 | content = dict(code=code, silent=silent, |
|
236 | content = dict(code=code, silent=silent, | |
237 | user_variables=user_variables, |
|
237 | user_variables=user_variables, | |
238 | user_expressions=user_expressions) |
|
238 | user_expressions=user_expressions) | |
239 | msg = self.session.msg('execute_request', content) |
|
239 | msg = self.session.msg('execute_request', content) | |
240 | self._queue_request(msg) |
|
240 | self._queue_request(msg) | |
241 | return msg['header']['msg_id'] |
|
241 | return msg['header']['msg_id'] | |
242 |
|
242 | |||
243 | def complete(self, text, line, cursor_pos, block=None): |
|
243 | def complete(self, text, line, cursor_pos, block=None): | |
244 | """Tab complete text in the kernel's namespace. |
|
244 | """Tab complete text in the kernel's namespace. | |
245 |
|
245 | |||
246 | Parameters |
|
246 | Parameters | |
247 | ---------- |
|
247 | ---------- | |
248 | text : str |
|
248 | text : str | |
249 | The text to complete. |
|
249 | The text to complete. | |
250 | line : str |
|
250 | line : str | |
251 | The full line of text that is the surrounding context for the |
|
251 | The full line of text that is the surrounding context for the | |
252 | text to complete. |
|
252 | text to complete. | |
253 | cursor_pos : int |
|
253 | cursor_pos : int | |
254 | The position of the cursor in the line where the completion was |
|
254 | The position of the cursor in the line where the completion was | |
255 | requested. |
|
255 | requested. | |
256 | block : str, optional |
|
256 | block : str, optional | |
257 | The full block of code in which the completion is being requested. |
|
257 | The full block of code in which the completion is being requested. | |
258 |
|
258 | |||
259 | Returns |
|
259 | Returns | |
260 | ------- |
|
260 | ------- | |
261 | The msg_id of the message sent. |
|
261 | The msg_id of the message sent. | |
262 | """ |
|
262 | """ | |
263 | content = dict(text=text, line=line, block=block, cursor_pos=cursor_pos) |
|
263 | content = dict(text=text, line=line, block=block, cursor_pos=cursor_pos) | |
264 | msg = self.session.msg('complete_request', content) |
|
264 | msg = self.session.msg('complete_request', content) | |
265 | self._queue_request(msg) |
|
265 | self._queue_request(msg) | |
266 | return msg['header']['msg_id'] |
|
266 | return msg['header']['msg_id'] | |
267 |
|
267 | |||
268 | def object_info(self, oname): |
|
268 | def object_info(self, oname): | |
269 | """Get metadata information about an object. |
|
269 | """Get metadata information about an object. | |
270 |
|
270 | |||
271 | Parameters |
|
271 | Parameters | |
272 | ---------- |
|
272 | ---------- | |
273 | oname : str |
|
273 | oname : str | |
274 | A string specifying the object name. |
|
274 | A string specifying the object name. | |
275 |
|
275 | |||
276 | Returns |
|
276 | Returns | |
277 | ------- |
|
277 | ------- | |
278 | The msg_id of the message sent. |
|
278 | The msg_id of the message sent. | |
279 | """ |
|
279 | """ | |
280 | content = dict(oname=oname) |
|
280 | content = dict(oname=oname) | |
281 | msg = self.session.msg('object_info_request', content) |
|
281 | msg = self.session.msg('object_info_request', content) | |
282 | self._queue_request(msg) |
|
282 | self._queue_request(msg) | |
283 | return msg['header']['msg_id'] |
|
283 | return msg['header']['msg_id'] | |
284 |
|
284 | |||
285 | def history(self, index=None, raw=False, output=True): |
|
285 | def history(self, index=None, raw=False, output=True, this_session=True): | |
286 | """Get the history list. |
|
286 | """Get the history list. | |
287 |
|
287 | |||
288 | Parameters |
|
288 | Parameters | |
289 | ---------- |
|
289 | ---------- | |
290 | index : n or (n1, n2) or None |
|
290 | index : n or (n1, n2) or None | |
291 | If n, then the last entries. If a tuple, then all in |
|
291 | If n, then the last entries. If a tuple, then all in | |
292 | range(n1, n2). If None, then all entries. Raises IndexError if |
|
292 | range(n1, n2). If None, then all entries. Raises IndexError if | |
293 | the format of index is incorrect. |
|
293 | the format of index is incorrect. | |
294 | raw : bool |
|
294 | raw : bool | |
295 | If True, return the raw input. |
|
295 | If True, return the raw input. | |
296 | output : bool |
|
296 | output : bool | |
297 | If True, then return the output as well. |
|
297 | If True, then return the output as well. | |
|
298 | this_session : bool | |||
|
299 | If True, returns only history from the current session. Otherwise, | |||
|
300 | includes reloaded history from previous sessions. | |||
298 |
|
301 | |||
299 | Returns |
|
302 | Returns | |
300 | ------- |
|
303 | ------- | |
301 | The msg_id of the message sent. |
|
304 | The msg_id of the message sent. | |
302 | """ |
|
305 | """ | |
303 |
content = dict(index=index, raw=raw, output=output |
|
306 | content = dict(index=index, raw=raw, output=output, | |
|
307 | this_session=this_session) | |||
304 | msg = self.session.msg('history_request', content) |
|
308 | msg = self.session.msg('history_request', content) | |
305 | self._queue_request(msg) |
|
309 | self._queue_request(msg) | |
306 | return msg['header']['msg_id'] |
|
310 | return msg['header']['msg_id'] | |
307 |
|
311 | |||
308 | def shutdown(self, restart=False): |
|
312 | def shutdown(self, restart=False): | |
309 | """Request an immediate kernel shutdown. |
|
313 | """Request an immediate kernel shutdown. | |
310 |
|
314 | |||
311 | Upon receipt of the (empty) reply, client code can safely assume that |
|
315 | Upon receipt of the (empty) reply, client code can safely assume that | |
312 | the kernel has shut down and it's safe to forcefully terminate it if |
|
316 | the kernel has shut down and it's safe to forcefully terminate it if | |
313 | it's still alive. |
|
317 | it's still alive. | |
314 |
|
318 | |||
315 | The kernel will send the reply via a function registered with Python's |
|
319 | The kernel will send the reply via a function registered with Python's | |
316 | atexit module, ensuring it's truly done as the kernel is done with all |
|
320 | atexit module, ensuring it's truly done as the kernel is done with all | |
317 | normal operation. |
|
321 | normal operation. | |
318 | """ |
|
322 | """ | |
319 | # Send quit message to kernel. Once we implement kernel-side setattr, |
|
323 | # Send quit message to kernel. Once we implement kernel-side setattr, | |
320 | # this should probably be done that way, but for now this will do. |
|
324 | # this should probably be done that way, but for now this will do. | |
321 | msg = self.session.msg('shutdown_request', {'restart':restart}) |
|
325 | msg = self.session.msg('shutdown_request', {'restart':restart}) | |
322 | self._queue_request(msg) |
|
326 | self._queue_request(msg) | |
323 | return msg['header']['msg_id'] |
|
327 | return msg['header']['msg_id'] | |
324 |
|
328 | |||
325 | def _handle_events(self, socket, events): |
|
329 | def _handle_events(self, socket, events): | |
326 | if events & POLLERR: |
|
330 | if events & POLLERR: | |
327 | self._handle_err() |
|
331 | self._handle_err() | |
328 | if events & POLLOUT: |
|
332 | if events & POLLOUT: | |
329 | self._handle_send() |
|
333 | self._handle_send() | |
330 | if events & POLLIN: |
|
334 | if events & POLLIN: | |
331 | self._handle_recv() |
|
335 | self._handle_recv() | |
332 |
|
336 | |||
333 | def _handle_recv(self): |
|
337 | def _handle_recv(self): | |
334 | ident,msg = self.session.recv(self.socket, 0) |
|
338 | ident,msg = self.session.recv(self.socket, 0) | |
335 | self.call_handlers(msg) |
|
339 | self.call_handlers(msg) | |
336 |
|
340 | |||
337 | def _handle_send(self): |
|
341 | def _handle_send(self): | |
338 | try: |
|
342 | try: | |
339 | msg = self.command_queue.get(False) |
|
343 | msg = self.command_queue.get(False) | |
340 | except Empty: |
|
344 | except Empty: | |
341 | pass |
|
345 | pass | |
342 | else: |
|
346 | else: | |
343 | self.session.send(self.socket,msg) |
|
347 | self.session.send(self.socket,msg) | |
344 | if self.command_queue.empty(): |
|
348 | if self.command_queue.empty(): | |
345 | self.drop_io_state(POLLOUT) |
|
349 | self.drop_io_state(POLLOUT) | |
346 |
|
350 | |||
347 | def _handle_err(self): |
|
351 | def _handle_err(self): | |
348 | # We don't want to let this go silently, so eventually we should log. |
|
352 | # We don't want to let this go silently, so eventually we should log. | |
349 | raise zmq.ZMQError() |
|
353 | raise zmq.ZMQError() | |
350 |
|
354 | |||
351 | def _queue_request(self, msg): |
|
355 | def _queue_request(self, msg): | |
352 | self.command_queue.put(msg) |
|
356 | self.command_queue.put(msg) | |
353 | self.add_io_state(POLLOUT) |
|
357 | self.add_io_state(POLLOUT) | |
354 |
|
358 | |||
355 |
|
359 | |||
356 | class SubSocketChannel(ZmqSocketChannel): |
|
360 | class SubSocketChannel(ZmqSocketChannel): | |
357 | """The SUB channel which listens for messages that the kernel publishes. |
|
361 | """The SUB channel which listens for messages that the kernel publishes. | |
358 | """ |
|
362 | """ | |
359 |
|
363 | |||
360 | def __init__(self, context, session, address): |
|
364 | def __init__(self, context, session, address): | |
361 | super(SubSocketChannel, self).__init__(context, session, address) |
|
365 | super(SubSocketChannel, self).__init__(context, session, address) | |
362 | self.ioloop = ioloop.IOLoop() |
|
366 | self.ioloop = ioloop.IOLoop() | |
363 |
|
367 | |||
364 | def run(self): |
|
368 | def run(self): | |
365 | """The thread's main activity. Call start() instead.""" |
|
369 | """The thread's main activity. Call start() instead.""" | |
366 | self.socket = self.context.socket(zmq.SUB) |
|
370 | self.socket = self.context.socket(zmq.SUB) | |
367 | self.socket.setsockopt(zmq.SUBSCRIBE,'') |
|
371 | self.socket.setsockopt(zmq.SUBSCRIBE,'') | |
368 | self.socket.setsockopt(zmq.IDENTITY, self.session.session) |
|
372 | self.socket.setsockopt(zmq.IDENTITY, self.session.session) | |
369 | self.socket.connect('tcp://%s:%i' % self.address) |
|
373 | self.socket.connect('tcp://%s:%i' % self.address) | |
370 | self.iostate = POLLIN|POLLERR |
|
374 | self.iostate = POLLIN|POLLERR | |
371 | self.ioloop.add_handler(self.socket, self._handle_events, |
|
375 | self.ioloop.add_handler(self.socket, self._handle_events, | |
372 | self.iostate) |
|
376 | self.iostate) | |
373 | self.ioloop.start() |
|
377 | self.ioloop.start() | |
374 |
|
378 | |||
375 | def stop(self): |
|
379 | def stop(self): | |
376 | self.ioloop.stop() |
|
380 | self.ioloop.stop() | |
377 | super(SubSocketChannel, self).stop() |
|
381 | super(SubSocketChannel, self).stop() | |
378 |
|
382 | |||
379 | def call_handlers(self, msg): |
|
383 | def call_handlers(self, msg): | |
380 | """This method is called in the ioloop thread when a message arrives. |
|
384 | """This method is called in the ioloop thread when a message arrives. | |
381 |
|
385 | |||
382 | Subclasses should override this method to handle incoming messages. |
|
386 | Subclasses should override this method to handle incoming messages. | |
383 | It is important to remember that this method is called in the thread |
|
387 | It is important to remember that this method is called in the thread | |
384 | so that some logic must be done to ensure that the application leve |
|
388 | so that some logic must be done to ensure that the application leve | |
385 | handlers are called in the application thread. |
|
389 | handlers are called in the application thread. | |
386 | """ |
|
390 | """ | |
387 | raise NotImplementedError('call_handlers must be defined in a subclass.') |
|
391 | raise NotImplementedError('call_handlers must be defined in a subclass.') | |
388 |
|
392 | |||
389 | def flush(self, timeout=1.0): |
|
393 | def flush(self, timeout=1.0): | |
390 | """Immediately processes all pending messages on the SUB channel. |
|
394 | """Immediately processes all pending messages on the SUB channel. | |
391 |
|
395 | |||
392 | Callers should use this method to ensure that :method:`call_handlers` |
|
396 | Callers should use this method to ensure that :method:`call_handlers` | |
393 | has been called for all messages that have been received on the |
|
397 | has been called for all messages that have been received on the | |
394 | 0MQ SUB socket of this channel. |
|
398 | 0MQ SUB socket of this channel. | |
395 |
|
399 | |||
396 | This method is thread safe. |
|
400 | This method is thread safe. | |
397 |
|
401 | |||
398 | Parameters |
|
402 | Parameters | |
399 | ---------- |
|
403 | ---------- | |
400 | timeout : float, optional |
|
404 | timeout : float, optional | |
401 | The maximum amount of time to spend flushing, in seconds. The |
|
405 | The maximum amount of time to spend flushing, in seconds. The | |
402 | default is one second. |
|
406 | default is one second. | |
403 | """ |
|
407 | """ | |
404 | # We do the IOLoop callback process twice to ensure that the IOLoop |
|
408 | # We do the IOLoop callback process twice to ensure that the IOLoop | |
405 | # gets to perform at least one full poll. |
|
409 | # gets to perform at least one full poll. | |
406 | stop_time = time.time() + timeout |
|
410 | stop_time = time.time() + timeout | |
407 | for i in xrange(2): |
|
411 | for i in xrange(2): | |
408 | self._flushed = False |
|
412 | self._flushed = False | |
409 | self.ioloop.add_callback(self._flush) |
|
413 | self.ioloop.add_callback(self._flush) | |
410 | while not self._flushed and time.time() < stop_time: |
|
414 | while not self._flushed and time.time() < stop_time: | |
411 | time.sleep(0.01) |
|
415 | time.sleep(0.01) | |
412 |
|
416 | |||
413 | def _handle_events(self, socket, events): |
|
417 | def _handle_events(self, socket, events): | |
414 | # Turn on and off POLLOUT depending on if we have made a request |
|
418 | # Turn on and off POLLOUT depending on if we have made a request | |
415 | if events & POLLERR: |
|
419 | if events & POLLERR: | |
416 | self._handle_err() |
|
420 | self._handle_err() | |
417 | if events & POLLIN: |
|
421 | if events & POLLIN: | |
418 | self._handle_recv() |
|
422 | self._handle_recv() | |
419 |
|
423 | |||
420 | def _handle_err(self): |
|
424 | def _handle_err(self): | |
421 | # We don't want to let this go silently, so eventually we should log. |
|
425 | # We don't want to let this go silently, so eventually we should log. | |
422 | raise zmq.ZMQError() |
|
426 | raise zmq.ZMQError() | |
423 |
|
427 | |||
424 | def _handle_recv(self): |
|
428 | def _handle_recv(self): | |
425 | # Get all of the messages we can |
|
429 | # Get all of the messages we can | |
426 | while True: |
|
430 | while True: | |
427 | try: |
|
431 | try: | |
428 | ident,msg = self.session.recv(self.socket) |
|
432 | ident,msg = self.session.recv(self.socket) | |
429 | except zmq.ZMQError: |
|
433 | except zmq.ZMQError: | |
430 | # Check the errno? |
|
434 | # Check the errno? | |
431 | # Will this trigger POLLERR? |
|
435 | # Will this trigger POLLERR? | |
432 | break |
|
436 | break | |
433 | else: |
|
437 | else: | |
434 | if msg is None: |
|
438 | if msg is None: | |
435 | break |
|
439 | break | |
436 | self.call_handlers(msg) |
|
440 | self.call_handlers(msg) | |
437 |
|
441 | |||
438 | def _flush(self): |
|
442 | def _flush(self): | |
439 | """Callback for :method:`self.flush`.""" |
|
443 | """Callback for :method:`self.flush`.""" | |
440 | self._flushed = True |
|
444 | self._flushed = True | |
441 |
|
445 | |||
442 |
|
446 | |||
443 | class RepSocketChannel(ZmqSocketChannel): |
|
447 | class RepSocketChannel(ZmqSocketChannel): | |
444 | """A reply channel to handle raw_input requests that the kernel makes.""" |
|
448 | """A reply channel to handle raw_input requests that the kernel makes.""" | |
445 |
|
449 | |||
446 | msg_queue = None |
|
450 | msg_queue = None | |
447 |
|
451 | |||
448 | def __init__(self, context, session, address): |
|
452 | def __init__(self, context, session, address): | |
449 | super(RepSocketChannel, self).__init__(context, session, address) |
|
453 | super(RepSocketChannel, self).__init__(context, session, address) | |
450 | self.ioloop = ioloop.IOLoop() |
|
454 | self.ioloop = ioloop.IOLoop() | |
451 | self.msg_queue = Queue() |
|
455 | self.msg_queue = Queue() | |
452 |
|
456 | |||
453 | def run(self): |
|
457 | def run(self): | |
454 | """The thread's main activity. Call start() instead.""" |
|
458 | """The thread's main activity. Call start() instead.""" | |
455 | self.socket = self.context.socket(zmq.XREQ) |
|
459 | self.socket = self.context.socket(zmq.XREQ) | |
456 | self.socket.setsockopt(zmq.IDENTITY, self.session.session) |
|
460 | self.socket.setsockopt(zmq.IDENTITY, self.session.session) | |
457 | self.socket.connect('tcp://%s:%i' % self.address) |
|
461 | self.socket.connect('tcp://%s:%i' % self.address) | |
458 | self.iostate = POLLERR|POLLIN |
|
462 | self.iostate = POLLERR|POLLIN | |
459 | self.ioloop.add_handler(self.socket, self._handle_events, |
|
463 | self.ioloop.add_handler(self.socket, self._handle_events, | |
460 | self.iostate) |
|
464 | self.iostate) | |
461 | self.ioloop.start() |
|
465 | self.ioloop.start() | |
462 |
|
466 | |||
463 | def stop(self): |
|
467 | def stop(self): | |
464 | self.ioloop.stop() |
|
468 | self.ioloop.stop() | |
465 | super(RepSocketChannel, self).stop() |
|
469 | super(RepSocketChannel, self).stop() | |
466 |
|
470 | |||
467 | def call_handlers(self, msg): |
|
471 | def call_handlers(self, msg): | |
468 | """This method is called in the ioloop thread when a message arrives. |
|
472 | """This method is called in the ioloop thread when a message arrives. | |
469 |
|
473 | |||
470 | Subclasses should override this method to handle incoming messages. |
|
474 | Subclasses should override this method to handle incoming messages. | |
471 | It is important to remember that this method is called in the thread |
|
475 | It is important to remember that this method is called in the thread | |
472 | so that some logic must be done to ensure that the application leve |
|
476 | so that some logic must be done to ensure that the application leve | |
473 | handlers are called in the application thread. |
|
477 | handlers are called in the application thread. | |
474 | """ |
|
478 | """ | |
475 | raise NotImplementedError('call_handlers must be defined in a subclass.') |
|
479 | raise NotImplementedError('call_handlers must be defined in a subclass.') | |
476 |
|
480 | |||
477 | def input(self, string): |
|
481 | def input(self, string): | |
478 | """Send a string of raw input to the kernel.""" |
|
482 | """Send a string of raw input to the kernel.""" | |
479 | content = dict(value=string) |
|
483 | content = dict(value=string) | |
480 | msg = self.session.msg('input_reply', content) |
|
484 | msg = self.session.msg('input_reply', content) | |
481 | self._queue_reply(msg) |
|
485 | self._queue_reply(msg) | |
482 |
|
486 | |||
483 | def _handle_events(self, socket, events): |
|
487 | def _handle_events(self, socket, events): | |
484 | if events & POLLERR: |
|
488 | if events & POLLERR: | |
485 | self._handle_err() |
|
489 | self._handle_err() | |
486 | if events & POLLOUT: |
|
490 | if events & POLLOUT: | |
487 | self._handle_send() |
|
491 | self._handle_send() | |
488 | if events & POLLIN: |
|
492 | if events & POLLIN: | |
489 | self._handle_recv() |
|
493 | self._handle_recv() | |
490 |
|
494 | |||
491 | def _handle_recv(self): |
|
495 | def _handle_recv(self): | |
492 | ident,msg = self.session.recv(self.socket, 0) |
|
496 | ident,msg = self.session.recv(self.socket, 0) | |
493 | self.call_handlers(msg) |
|
497 | self.call_handlers(msg) | |
494 |
|
498 | |||
495 | def _handle_send(self): |
|
499 | def _handle_send(self): | |
496 | try: |
|
500 | try: | |
497 | msg = self.msg_queue.get(False) |
|
501 | msg = self.msg_queue.get(False) | |
498 | except Empty: |
|
502 | except Empty: | |
499 | pass |
|
503 | pass | |
500 | else: |
|
504 | else: | |
501 | self.session.send(self.socket,msg) |
|
505 | self.session.send(self.socket,msg) | |
502 | if self.msg_queue.empty(): |
|
506 | if self.msg_queue.empty(): | |
503 | self.drop_io_state(POLLOUT) |
|
507 | self.drop_io_state(POLLOUT) | |
504 |
|
508 | |||
505 | def _handle_err(self): |
|
509 | def _handle_err(self): | |
506 | # We don't want to let this go silently, so eventually we should log. |
|
510 | # We don't want to let this go silently, so eventually we should log. | |
507 | raise zmq.ZMQError() |
|
511 | raise zmq.ZMQError() | |
508 |
|
512 | |||
509 | def _queue_reply(self, msg): |
|
513 | def _queue_reply(self, msg): | |
510 | self.msg_queue.put(msg) |
|
514 | self.msg_queue.put(msg) | |
511 | self.add_io_state(POLLOUT) |
|
515 | self.add_io_state(POLLOUT) | |
512 |
|
516 | |||
513 |
|
517 | |||
514 | class HBSocketChannel(ZmqSocketChannel): |
|
518 | class HBSocketChannel(ZmqSocketChannel): | |
515 | """The heartbeat channel which monitors the kernel heartbeat. |
|
519 | """The heartbeat channel which monitors the kernel heartbeat. | |
516 |
|
520 | |||
517 | Note that the heartbeat channel is paused by default. As long as you start |
|
521 | Note that the heartbeat channel is paused by default. As long as you start | |
518 | this channel, the kernel manager will ensure that it is paused and un-paused |
|
522 | this channel, the kernel manager will ensure that it is paused and un-paused | |
519 | as appropriate. |
|
523 | as appropriate. | |
520 | """ |
|
524 | """ | |
521 |
|
525 | |||
522 | time_to_dead = 3.0 |
|
526 | time_to_dead = 3.0 | |
523 | socket = None |
|
527 | socket = None | |
524 | poller = None |
|
528 | poller = None | |
525 | _running = None |
|
529 | _running = None | |
526 | _pause = None |
|
530 | _pause = None | |
527 |
|
531 | |||
528 | def __init__(self, context, session, address): |
|
532 | def __init__(self, context, session, address): | |
529 | super(HBSocketChannel, self).__init__(context, session, address) |
|
533 | super(HBSocketChannel, self).__init__(context, session, address) | |
530 | self._running = False |
|
534 | self._running = False | |
531 | self._pause = True |
|
535 | self._pause = True | |
532 |
|
536 | |||
533 | def _create_socket(self): |
|
537 | def _create_socket(self): | |
534 | self.socket = self.context.socket(zmq.REQ) |
|
538 | self.socket = self.context.socket(zmq.REQ) | |
535 | self.socket.setsockopt(zmq.IDENTITY, self.session.session) |
|
539 | self.socket.setsockopt(zmq.IDENTITY, self.session.session) | |
536 | self.socket.connect('tcp://%s:%i' % self.address) |
|
540 | self.socket.connect('tcp://%s:%i' % self.address) | |
537 | self.poller = zmq.Poller() |
|
541 | self.poller = zmq.Poller() | |
538 | self.poller.register(self.socket, zmq.POLLIN) |
|
542 | self.poller.register(self.socket, zmq.POLLIN) | |
539 |
|
543 | |||
540 | def run(self): |
|
544 | def run(self): | |
541 | """The thread's main activity. Call start() instead.""" |
|
545 | """The thread's main activity. Call start() instead.""" | |
542 | self._create_socket() |
|
546 | self._create_socket() | |
543 | self._running = True |
|
547 | self._running = True | |
544 | while self._running: |
|
548 | while self._running: | |
545 | if self._pause: |
|
549 | if self._pause: | |
546 | time.sleep(self.time_to_dead) |
|
550 | time.sleep(self.time_to_dead) | |
547 | else: |
|
551 | else: | |
548 | since_last_heartbeat = 0.0 |
|
552 | since_last_heartbeat = 0.0 | |
549 | request_time = time.time() |
|
553 | request_time = time.time() | |
550 | try: |
|
554 | try: | |
551 | #io.rprint('Ping from HB channel') # dbg |
|
555 | #io.rprint('Ping from HB channel') # dbg | |
552 | self.socket.send(b'ping') |
|
556 | self.socket.send(b'ping') | |
553 | except zmq.ZMQError, e: |
|
557 | except zmq.ZMQError, e: | |
554 | #io.rprint('*** HB Error:', e) # dbg |
|
558 | #io.rprint('*** HB Error:', e) # dbg | |
555 | if e.errno == zmq.EFSM: |
|
559 | if e.errno == zmq.EFSM: | |
556 | #io.rprint('sleep...', self.time_to_dead) # dbg |
|
560 | #io.rprint('sleep...', self.time_to_dead) # dbg | |
557 | time.sleep(self.time_to_dead) |
|
561 | time.sleep(self.time_to_dead) | |
558 | self._create_socket() |
|
562 | self._create_socket() | |
559 | else: |
|
563 | else: | |
560 | raise |
|
564 | raise | |
561 | else: |
|
565 | else: | |
562 | while True: |
|
566 | while True: | |
563 | try: |
|
567 | try: | |
564 | self.socket.recv(zmq.NOBLOCK) |
|
568 | self.socket.recv(zmq.NOBLOCK) | |
565 | except zmq.ZMQError, e: |
|
569 | except zmq.ZMQError, e: | |
566 | #io.rprint('*** HB Error 2:', e) # dbg |
|
570 | #io.rprint('*** HB Error 2:', e) # dbg | |
567 | if e.errno == zmq.EAGAIN: |
|
571 | if e.errno == zmq.EAGAIN: | |
568 | before_poll = time.time() |
|
572 | before_poll = time.time() | |
569 | until_dead = self.time_to_dead - (before_poll - |
|
573 | until_dead = self.time_to_dead - (before_poll - | |
570 | request_time) |
|
574 | request_time) | |
571 |
|
575 | |||
572 | # When the return value of poll() is an empty |
|
576 | # When the return value of poll() is an empty | |
573 | # list, that is when things have gone wrong |
|
577 | # list, that is when things have gone wrong | |
574 | # (zeromq bug). As long as it is not an empty |
|
578 | # (zeromq bug). As long as it is not an empty | |
575 | # list, poll is working correctly even if it |
|
579 | # list, poll is working correctly even if it | |
576 | # returns quickly. Note: poll timeout is in |
|
580 | # returns quickly. Note: poll timeout is in | |
577 | # milliseconds. |
|
581 | # milliseconds. | |
578 | self.poller.poll(1000*until_dead) |
|
582 | self.poller.poll(1000*until_dead) | |
579 |
|
583 | |||
580 | since_last_heartbeat = time.time()-request_time |
|
584 | since_last_heartbeat = time.time()-request_time | |
581 | if since_last_heartbeat > self.time_to_dead: |
|
585 | if since_last_heartbeat > self.time_to_dead: | |
582 | self.call_handlers(since_last_heartbeat) |
|
586 | self.call_handlers(since_last_heartbeat) | |
583 | break |
|
587 | break | |
584 | else: |
|
588 | else: | |
585 | # FIXME: We should probably log this instead. |
|
589 | # FIXME: We should probably log this instead. | |
586 | raise |
|
590 | raise | |
587 | else: |
|
591 | else: | |
588 | until_dead = self.time_to_dead - (time.time() - |
|
592 | until_dead = self.time_to_dead - (time.time() - | |
589 | request_time) |
|
593 | request_time) | |
590 | if until_dead > 0.0: |
|
594 | if until_dead > 0.0: | |
591 | #io.rprint('sleep...', self.time_to_dead) # dbg |
|
595 | #io.rprint('sleep...', self.time_to_dead) # dbg | |
592 | time.sleep(until_dead) |
|
596 | time.sleep(until_dead) | |
593 | break |
|
597 | break | |
594 |
|
598 | |||
595 | def pause(self): |
|
599 | def pause(self): | |
596 | """Pause the heartbeat.""" |
|
600 | """Pause the heartbeat.""" | |
597 | self._pause = True |
|
601 | self._pause = True | |
598 |
|
602 | |||
599 | def unpause(self): |
|
603 | def unpause(self): | |
600 | """Unpause the heartbeat.""" |
|
604 | """Unpause the heartbeat.""" | |
601 | self._pause = False |
|
605 | self._pause = False | |
602 |
|
606 | |||
603 | def is_beating(self): |
|
607 | def is_beating(self): | |
604 | """Is the heartbeat running and not paused.""" |
|
608 | """Is the heartbeat running and not paused.""" | |
605 | if self.is_alive() and not self._pause: |
|
609 | if self.is_alive() and not self._pause: | |
606 | return True |
|
610 | return True | |
607 | else: |
|
611 | else: | |
608 | return False |
|
612 | return False | |
609 |
|
613 | |||
610 | def stop(self): |
|
614 | def stop(self): | |
611 | self._running = False |
|
615 | self._running = False | |
612 | super(HBSocketChannel, self).stop() |
|
616 | super(HBSocketChannel, self).stop() | |
613 |
|
617 | |||
614 | def call_handlers(self, since_last_heartbeat): |
|
618 | def call_handlers(self, since_last_heartbeat): | |
615 | """This method is called in the ioloop thread when a message arrives. |
|
619 | """This method is called in the ioloop thread when a message arrives. | |
616 |
|
620 | |||
617 | Subclasses should override this method to handle incoming messages. |
|
621 | Subclasses should override this method to handle incoming messages. | |
618 | It is important to remember that this method is called in the thread |
|
622 | It is important to remember that this method is called in the thread | |
619 | so that some logic must be done to ensure that the application leve |
|
623 | so that some logic must be done to ensure that the application leve | |
620 | handlers are called in the application thread. |
|
624 | handlers are called in the application thread. | |
621 | """ |
|
625 | """ | |
622 | raise NotImplementedError('call_handlers must be defined in a subclass.') |
|
626 | raise NotImplementedError('call_handlers must be defined in a subclass.') | |
623 |
|
627 | |||
624 |
|
628 | |||
625 | #----------------------------------------------------------------------------- |
|
629 | #----------------------------------------------------------------------------- | |
626 | # Main kernel manager class |
|
630 | # Main kernel manager class | |
627 | #----------------------------------------------------------------------------- |
|
631 | #----------------------------------------------------------------------------- | |
628 |
|
632 | |||
629 | class KernelManager(HasTraits): |
|
633 | class KernelManager(HasTraits): | |
630 | """ Manages a kernel for a frontend. |
|
634 | """ Manages a kernel for a frontend. | |
631 |
|
635 | |||
632 | The SUB channel is for the frontend to receive messages published by the |
|
636 | The SUB channel is for the frontend to receive messages published by the | |
633 | kernel. |
|
637 | kernel. | |
634 |
|
638 | |||
635 | The REQ channel is for the frontend to make requests of the kernel. |
|
639 | The REQ channel is for the frontend to make requests of the kernel. | |
636 |
|
640 | |||
637 | The REP channel is for the kernel to request stdin (raw_input) from the |
|
641 | The REP channel is for the kernel to request stdin (raw_input) from the | |
638 | frontend. |
|
642 | frontend. | |
639 | """ |
|
643 | """ | |
640 | # The PyZMQ Context to use for communication with the kernel. |
|
644 | # The PyZMQ Context to use for communication with the kernel. | |
641 | context = Instance(zmq.Context,(),{}) |
|
645 | context = Instance(zmq.Context,(),{}) | |
642 |
|
646 | |||
643 | # The Session to use for communication with the kernel. |
|
647 | # The Session to use for communication with the kernel. | |
644 | session = Instance(Session,(),{}) |
|
648 | session = Instance(Session,(),{}) | |
645 |
|
649 | |||
646 | # The kernel process with which the KernelManager is communicating. |
|
650 | # The kernel process with which the KernelManager is communicating. | |
647 | kernel = Instance(Popen) |
|
651 | kernel = Instance(Popen) | |
648 |
|
652 | |||
649 | # The addresses for the communication channels. |
|
653 | # The addresses for the communication channels. | |
650 | xreq_address = TCPAddress((LOCALHOST, 0)) |
|
654 | xreq_address = TCPAddress((LOCALHOST, 0)) | |
651 | sub_address = TCPAddress((LOCALHOST, 0)) |
|
655 | sub_address = TCPAddress((LOCALHOST, 0)) | |
652 | rep_address = TCPAddress((LOCALHOST, 0)) |
|
656 | rep_address = TCPAddress((LOCALHOST, 0)) | |
653 | hb_address = TCPAddress((LOCALHOST, 0)) |
|
657 | hb_address = TCPAddress((LOCALHOST, 0)) | |
654 |
|
658 | |||
655 | # The classes to use for the various channels. |
|
659 | # The classes to use for the various channels. | |
656 | xreq_channel_class = Type(XReqSocketChannel) |
|
660 | xreq_channel_class = Type(XReqSocketChannel) | |
657 | sub_channel_class = Type(SubSocketChannel) |
|
661 | sub_channel_class = Type(SubSocketChannel) | |
658 | rep_channel_class = Type(RepSocketChannel) |
|
662 | rep_channel_class = Type(RepSocketChannel) | |
659 | hb_channel_class = Type(HBSocketChannel) |
|
663 | hb_channel_class = Type(HBSocketChannel) | |
660 |
|
664 | |||
661 | # Protected traits. |
|
665 | # Protected traits. | |
662 | _launch_args = Any |
|
666 | _launch_args = Any | |
663 | _xreq_channel = Any |
|
667 | _xreq_channel = Any | |
664 | _sub_channel = Any |
|
668 | _sub_channel = Any | |
665 | _rep_channel = Any |
|
669 | _rep_channel = Any | |
666 | _hb_channel = Any |
|
670 | _hb_channel = Any | |
667 |
|
671 | |||
668 | def __init__(self, **kwargs): |
|
672 | def __init__(self, **kwargs): | |
669 | super(KernelManager, self).__init__(**kwargs) |
|
673 | super(KernelManager, self).__init__(**kwargs) | |
670 | # Uncomment this to try closing the context. |
|
674 | # Uncomment this to try closing the context. | |
671 | # atexit.register(self.context.close) |
|
675 | # atexit.register(self.context.close) | |
672 |
|
676 | |||
673 | #-------------------------------------------------------------------------- |
|
677 | #-------------------------------------------------------------------------- | |
674 | # Channel management methods: |
|
678 | # Channel management methods: | |
675 | #-------------------------------------------------------------------------- |
|
679 | #-------------------------------------------------------------------------- | |
676 |
|
680 | |||
677 | def start_channels(self, xreq=True, sub=True, rep=True, hb=True): |
|
681 | def start_channels(self, xreq=True, sub=True, rep=True, hb=True): | |
678 | """Starts the channels for this kernel. |
|
682 | """Starts the channels for this kernel. | |
679 |
|
683 | |||
680 | This will create the channels if they do not exist and then start |
|
684 | This will create the channels if they do not exist and then start | |
681 | them. If port numbers of 0 are being used (random ports) then you |
|
685 | them. If port numbers of 0 are being used (random ports) then you | |
682 | must first call :method:`start_kernel`. If the channels have been |
|
686 | must first call :method:`start_kernel`. If the channels have been | |
683 | stopped and you call this, :class:`RuntimeError` will be raised. |
|
687 | stopped and you call this, :class:`RuntimeError` will be raised. | |
684 | """ |
|
688 | """ | |
685 | if xreq: |
|
689 | if xreq: | |
686 | self.xreq_channel.start() |
|
690 | self.xreq_channel.start() | |
687 | if sub: |
|
691 | if sub: | |
688 | self.sub_channel.start() |
|
692 | self.sub_channel.start() | |
689 | if rep: |
|
693 | if rep: | |
690 | self.rep_channel.start() |
|
694 | self.rep_channel.start() | |
691 | if hb: |
|
695 | if hb: | |
692 | self.hb_channel.start() |
|
696 | self.hb_channel.start() | |
693 |
|
697 | |||
694 | def stop_channels(self): |
|
698 | def stop_channels(self): | |
695 | """Stops all the running channels for this kernel. |
|
699 | """Stops all the running channels for this kernel. | |
696 | """ |
|
700 | """ | |
697 | if self.xreq_channel.is_alive(): |
|
701 | if self.xreq_channel.is_alive(): | |
698 | self.xreq_channel.stop() |
|
702 | self.xreq_channel.stop() | |
699 | if self.sub_channel.is_alive(): |
|
703 | if self.sub_channel.is_alive(): | |
700 | self.sub_channel.stop() |
|
704 | self.sub_channel.stop() | |
701 | if self.rep_channel.is_alive(): |
|
705 | if self.rep_channel.is_alive(): | |
702 | self.rep_channel.stop() |
|
706 | self.rep_channel.stop() | |
703 | if self.hb_channel.is_alive(): |
|
707 | if self.hb_channel.is_alive(): | |
704 | self.hb_channel.stop() |
|
708 | self.hb_channel.stop() | |
705 |
|
709 | |||
706 | @property |
|
710 | @property | |
707 | def channels_running(self): |
|
711 | def channels_running(self): | |
708 | """Are any of the channels created and running?""" |
|
712 | """Are any of the channels created and running?""" | |
709 | return (self.xreq_channel.is_alive() or self.sub_channel.is_alive() or |
|
713 | return (self.xreq_channel.is_alive() or self.sub_channel.is_alive() or | |
710 | self.rep_channel.is_alive() or self.hb_channel.is_alive()) |
|
714 | self.rep_channel.is_alive() or self.hb_channel.is_alive()) | |
711 |
|
715 | |||
712 | #-------------------------------------------------------------------------- |
|
716 | #-------------------------------------------------------------------------- | |
713 | # Kernel process management methods: |
|
717 | # Kernel process management methods: | |
714 | #-------------------------------------------------------------------------- |
|
718 | #-------------------------------------------------------------------------- | |
715 |
|
719 | |||
716 | def start_kernel(self, **kw): |
|
720 | def start_kernel(self, **kw): | |
717 | """Starts a kernel process and configures the manager to use it. |
|
721 | """Starts a kernel process and configures the manager to use it. | |
718 |
|
722 | |||
719 | If random ports (port=0) are being used, this method must be called |
|
723 | If random ports (port=0) are being used, this method must be called | |
720 | before the channels are created. |
|
724 | before the channels are created. | |
721 |
|
725 | |||
722 | Parameters: |
|
726 | Parameters: | |
723 | ----------- |
|
727 | ----------- | |
724 | ipython : bool, optional (default True) |
|
728 | ipython : bool, optional (default True) | |
725 | Whether to use an IPython kernel instead of a plain Python kernel. |
|
729 | Whether to use an IPython kernel instead of a plain Python kernel. | |
726 | """ |
|
730 | """ | |
727 | xreq, sub, rep, hb = self.xreq_address, self.sub_address, \ |
|
731 | xreq, sub, rep, hb = self.xreq_address, self.sub_address, \ | |
728 | self.rep_address, self.hb_address |
|
732 | self.rep_address, self.hb_address | |
729 | if xreq[0] not in LOCAL_IPS or sub[0] not in LOCAL_IPS or \ |
|
733 | if xreq[0] not in LOCAL_IPS or sub[0] not in LOCAL_IPS or \ | |
730 | rep[0] not in LOCAL_IPS or hb[0] not in LOCAL_IPS: |
|
734 | rep[0] not in LOCAL_IPS or hb[0] not in LOCAL_IPS: | |
731 | raise RuntimeError("Can only launch a kernel on a local interface. " |
|
735 | raise RuntimeError("Can only launch a kernel on a local interface. " | |
732 | "Make sure that the '*_address' attributes are " |
|
736 | "Make sure that the '*_address' attributes are " | |
733 | "configured properly. " |
|
737 | "configured properly. " | |
734 | "Currently valid addresses are: %s"%LOCAL_IPS |
|
738 | "Currently valid addresses are: %s"%LOCAL_IPS | |
735 | ) |
|
739 | ) | |
736 |
|
740 | |||
737 | self._launch_args = kw.copy() |
|
741 | self._launch_args = kw.copy() | |
738 | if kw.pop('ipython', True): |
|
742 | if kw.pop('ipython', True): | |
739 | from ipkernel import launch_kernel |
|
743 | from ipkernel import launch_kernel | |
740 | else: |
|
744 | else: | |
741 | from pykernel import launch_kernel |
|
745 | from pykernel import launch_kernel | |
742 | self.kernel, xrep, pub, req, _hb = launch_kernel( |
|
746 | self.kernel, xrep, pub, req, _hb = launch_kernel( | |
743 | xrep_port=xreq[1], pub_port=sub[1], |
|
747 | xrep_port=xreq[1], pub_port=sub[1], | |
744 | req_port=rep[1], hb_port=hb[1], **kw) |
|
748 | req_port=rep[1], hb_port=hb[1], **kw) | |
745 | self.xreq_address = (xreq[0], xrep) |
|
749 | self.xreq_address = (xreq[0], xrep) | |
746 | self.sub_address = (sub[0], pub) |
|
750 | self.sub_address = (sub[0], pub) | |
747 | self.rep_address = (rep[0], req) |
|
751 | self.rep_address = (rep[0], req) | |
748 | self.hb_address = (hb[0], _hb) |
|
752 | self.hb_address = (hb[0], _hb) | |
749 |
|
753 | |||
750 | def shutdown_kernel(self, restart=False): |
|
754 | def shutdown_kernel(self, restart=False): | |
751 | """ Attempts to the stop the kernel process cleanly. If the kernel |
|
755 | """ Attempts to the stop the kernel process cleanly. If the kernel | |
752 | cannot be stopped, it is killed, if possible. |
|
756 | cannot be stopped, it is killed, if possible. | |
753 | """ |
|
757 | """ | |
754 | # FIXME: Shutdown does not work on Windows due to ZMQ errors! |
|
758 | # FIXME: Shutdown does not work on Windows due to ZMQ errors! | |
755 | if sys.platform == 'win32': |
|
759 | if sys.platform == 'win32': | |
756 | self.kill_kernel() |
|
760 | self.kill_kernel() | |
757 | return |
|
761 | return | |
758 |
|
762 | |||
759 | # Pause the heart beat channel if it exists. |
|
763 | # Pause the heart beat channel if it exists. | |
760 | if self._hb_channel is not None: |
|
764 | if self._hb_channel is not None: | |
761 | self._hb_channel.pause() |
|
765 | self._hb_channel.pause() | |
762 |
|
766 | |||
763 | # Don't send any additional kernel kill messages immediately, to give |
|
767 | # Don't send any additional kernel kill messages immediately, to give | |
764 | # the kernel a chance to properly execute shutdown actions. Wait for at |
|
768 | # the kernel a chance to properly execute shutdown actions. Wait for at | |
765 | # most 1s, checking every 0.1s. |
|
769 | # most 1s, checking every 0.1s. | |
766 | self.xreq_channel.shutdown(restart=restart) |
|
770 | self.xreq_channel.shutdown(restart=restart) | |
767 | for i in range(10): |
|
771 | for i in range(10): | |
768 | if self.is_alive: |
|
772 | if self.is_alive: | |
769 | time.sleep(0.1) |
|
773 | time.sleep(0.1) | |
770 | else: |
|
774 | else: | |
771 | break |
|
775 | break | |
772 | else: |
|
776 | else: | |
773 | # OK, we've waited long enough. |
|
777 | # OK, we've waited long enough. | |
774 | if self.has_kernel: |
|
778 | if self.has_kernel: | |
775 | self.kill_kernel() |
|
779 | self.kill_kernel() | |
776 |
|
780 | |||
777 | def restart_kernel(self, now=False): |
|
781 | def restart_kernel(self, now=False): | |
778 | """Restarts a kernel with the same arguments that were used to launch |
|
782 | """Restarts a kernel with the same arguments that were used to launch | |
779 | it. If the old kernel was launched with random ports, the same ports |
|
783 | it. If the old kernel was launched with random ports, the same ports | |
780 | will be used for the new kernel. |
|
784 | will be used for the new kernel. | |
781 |
|
785 | |||
782 | Parameters |
|
786 | Parameters | |
783 | ---------- |
|
787 | ---------- | |
784 | now : bool, optional |
|
788 | now : bool, optional | |
785 | If True, the kernel is forcefully restarted *immediately*, without |
|
789 | If True, the kernel is forcefully restarted *immediately*, without | |
786 | having a chance to do any cleanup action. Otherwise the kernel is |
|
790 | having a chance to do any cleanup action. Otherwise the kernel is | |
787 | given 1s to clean up before a forceful restart is issued. |
|
791 | given 1s to clean up before a forceful restart is issued. | |
788 |
|
792 | |||
789 | In all cases the kernel is restarted, the only difference is whether |
|
793 | In all cases the kernel is restarted, the only difference is whether | |
790 | it is given a chance to perform a clean shutdown or not. |
|
794 | it is given a chance to perform a clean shutdown or not. | |
791 | """ |
|
795 | """ | |
792 | if self._launch_args is None: |
|
796 | if self._launch_args is None: | |
793 | raise RuntimeError("Cannot restart the kernel. " |
|
797 | raise RuntimeError("Cannot restart the kernel. " | |
794 | "No previous call to 'start_kernel'.") |
|
798 | "No previous call to 'start_kernel'.") | |
795 | else: |
|
799 | else: | |
796 | if self.has_kernel: |
|
800 | if self.has_kernel: | |
797 | if now: |
|
801 | if now: | |
798 | self.kill_kernel() |
|
802 | self.kill_kernel() | |
799 | else: |
|
803 | else: | |
800 | self.shutdown_kernel(restart=True) |
|
804 | self.shutdown_kernel(restart=True) | |
801 | self.start_kernel(**self._launch_args) |
|
805 | self.start_kernel(**self._launch_args) | |
802 |
|
806 | |||
803 | # FIXME: Messages get dropped in Windows due to probable ZMQ bug |
|
807 | # FIXME: Messages get dropped in Windows due to probable ZMQ bug | |
804 | # unless there is some delay here. |
|
808 | # unless there is some delay here. | |
805 | if sys.platform == 'win32': |
|
809 | if sys.platform == 'win32': | |
806 | time.sleep(0.2) |
|
810 | time.sleep(0.2) | |
807 |
|
811 | |||
808 | @property |
|
812 | @property | |
809 | def has_kernel(self): |
|
813 | def has_kernel(self): | |
810 | """Returns whether a kernel process has been specified for the kernel |
|
814 | """Returns whether a kernel process has been specified for the kernel | |
811 | manager. |
|
815 | manager. | |
812 | """ |
|
816 | """ | |
813 | return self.kernel is not None |
|
817 | return self.kernel is not None | |
814 |
|
818 | |||
815 | def kill_kernel(self): |
|
819 | def kill_kernel(self): | |
816 | """ Kill the running kernel. """ |
|
820 | """ Kill the running kernel. """ | |
817 | if self.has_kernel: |
|
821 | if self.has_kernel: | |
818 | # Pause the heart beat channel if it exists. |
|
822 | # Pause the heart beat channel if it exists. | |
819 | if self._hb_channel is not None: |
|
823 | if self._hb_channel is not None: | |
820 | self._hb_channel.pause() |
|
824 | self._hb_channel.pause() | |
821 |
|
825 | |||
822 | # Attempt to kill the kernel. |
|
826 | # Attempt to kill the kernel. | |
823 | try: |
|
827 | try: | |
824 | self.kernel.kill() |
|
828 | self.kernel.kill() | |
825 | except OSError, e: |
|
829 | except OSError, e: | |
826 | # In Windows, we will get an Access Denied error if the process |
|
830 | # In Windows, we will get an Access Denied error if the process | |
827 | # has already terminated. Ignore it. |
|
831 | # has already terminated. Ignore it. | |
828 | if not (sys.platform == 'win32' and e.winerror == 5): |
|
832 | if not (sys.platform == 'win32' and e.winerror == 5): | |
829 | raise |
|
833 | raise | |
830 | self.kernel = None |
|
834 | self.kernel = None | |
831 | else: |
|
835 | else: | |
832 | raise RuntimeError("Cannot kill kernel. No kernel is running!") |
|
836 | raise RuntimeError("Cannot kill kernel. No kernel is running!") | |
833 |
|
837 | |||
834 | def interrupt_kernel(self): |
|
838 | def interrupt_kernel(self): | |
835 | """ Interrupts the kernel. Unlike ``signal_kernel``, this operation is |
|
839 | """ Interrupts the kernel. Unlike ``signal_kernel``, this operation is | |
836 | well supported on all platforms. |
|
840 | well supported on all platforms. | |
837 | """ |
|
841 | """ | |
838 | if self.has_kernel: |
|
842 | if self.has_kernel: | |
839 | if sys.platform == 'win32': |
|
843 | if sys.platform == 'win32': | |
840 | from parentpoller import ParentPollerWindows as Poller |
|
844 | from parentpoller import ParentPollerWindows as Poller | |
841 | Poller.send_interrupt(self.kernel.win32_interrupt_event) |
|
845 | Poller.send_interrupt(self.kernel.win32_interrupt_event) | |
842 | else: |
|
846 | else: | |
843 | self.kernel.send_signal(signal.SIGINT) |
|
847 | self.kernel.send_signal(signal.SIGINT) | |
844 | else: |
|
848 | else: | |
845 | raise RuntimeError("Cannot interrupt kernel. No kernel is running!") |
|
849 | raise RuntimeError("Cannot interrupt kernel. No kernel is running!") | |
846 |
|
850 | |||
847 | def signal_kernel(self, signum): |
|
851 | def signal_kernel(self, signum): | |
848 | """ Sends a signal to the kernel. Note that since only SIGTERM is |
|
852 | """ Sends a signal to the kernel. Note that since only SIGTERM is | |
849 | supported on Windows, this function is only useful on Unix systems. |
|
853 | supported on Windows, this function is only useful on Unix systems. | |
850 | """ |
|
854 | """ | |
851 | if self.has_kernel: |
|
855 | if self.has_kernel: | |
852 | self.kernel.send_signal(signum) |
|
856 | self.kernel.send_signal(signum) | |
853 | else: |
|
857 | else: | |
854 | raise RuntimeError("Cannot signal kernel. No kernel is running!") |
|
858 | raise RuntimeError("Cannot signal kernel. No kernel is running!") | |
855 |
|
859 | |||
856 | @property |
|
860 | @property | |
857 | def is_alive(self): |
|
861 | def is_alive(self): | |
858 | """Is the kernel process still running?""" |
|
862 | """Is the kernel process still running?""" | |
859 | # FIXME: not using a heartbeat means this method is broken for any |
|
863 | # FIXME: not using a heartbeat means this method is broken for any | |
860 | # remote kernel, it's only capable of handling local kernels. |
|
864 | # remote kernel, it's only capable of handling local kernels. | |
861 | if self.has_kernel: |
|
865 | if self.has_kernel: | |
862 | if self.kernel.poll() is None: |
|
866 | if self.kernel.poll() is None: | |
863 | return True |
|
867 | return True | |
864 | else: |
|
868 | else: | |
865 | return False |
|
869 | return False | |
866 | else: |
|
870 | else: | |
867 | # We didn't start the kernel with this KernelManager so we don't |
|
871 | # We didn't start the kernel with this KernelManager so we don't | |
868 | # know if it is running. We should use a heartbeat for this case. |
|
872 | # know if it is running. We should use a heartbeat for this case. | |
869 | return True |
|
873 | return True | |
870 |
|
874 | |||
871 | #-------------------------------------------------------------------------- |
|
875 | #-------------------------------------------------------------------------- | |
872 | # Channels used for communication with the kernel: |
|
876 | # Channels used for communication with the kernel: | |
873 | #-------------------------------------------------------------------------- |
|
877 | #-------------------------------------------------------------------------- | |
874 |
|
878 | |||
875 | @property |
|
879 | @property | |
876 | def xreq_channel(self): |
|
880 | def xreq_channel(self): | |
877 | """Get the REQ socket channel object to make requests of the kernel.""" |
|
881 | """Get the REQ socket channel object to make requests of the kernel.""" | |
878 | if self._xreq_channel is None: |
|
882 | if self._xreq_channel is None: | |
879 | self._xreq_channel = self.xreq_channel_class(self.context, |
|
883 | self._xreq_channel = self.xreq_channel_class(self.context, | |
880 | self.session, |
|
884 | self.session, | |
881 | self.xreq_address) |
|
885 | self.xreq_address) | |
882 | return self._xreq_channel |
|
886 | return self._xreq_channel | |
883 |
|
887 | |||
884 | @property |
|
888 | @property | |
885 | def sub_channel(self): |
|
889 | def sub_channel(self): | |
886 | """Get the SUB socket channel object.""" |
|
890 | """Get the SUB socket channel object.""" | |
887 | if self._sub_channel is None: |
|
891 | if self._sub_channel is None: | |
888 | self._sub_channel = self.sub_channel_class(self.context, |
|
892 | self._sub_channel = self.sub_channel_class(self.context, | |
889 | self.session, |
|
893 | self.session, | |
890 | self.sub_address) |
|
894 | self.sub_address) | |
891 | return self._sub_channel |
|
895 | return self._sub_channel | |
892 |
|
896 | |||
893 | @property |
|
897 | @property | |
894 | def rep_channel(self): |
|
898 | def rep_channel(self): | |
895 | """Get the REP socket channel object to handle stdin (raw_input).""" |
|
899 | """Get the REP socket channel object to handle stdin (raw_input).""" | |
896 | if self._rep_channel is None: |
|
900 | if self._rep_channel is None: | |
897 | self._rep_channel = self.rep_channel_class(self.context, |
|
901 | self._rep_channel = self.rep_channel_class(self.context, | |
898 | self.session, |
|
902 | self.session, | |
899 | self.rep_address) |
|
903 | self.rep_address) | |
900 | return self._rep_channel |
|
904 | return self._rep_channel | |
901 |
|
905 | |||
902 | @property |
|
906 | @property | |
903 | def hb_channel(self): |
|
907 | def hb_channel(self): | |
904 | """Get the heartbeat socket channel object to check that the |
|
908 | """Get the heartbeat socket channel object to check that the | |
905 | kernel is alive.""" |
|
909 | kernel is alive.""" | |
906 | if self._hb_channel is None: |
|
910 | if self._hb_channel is None: | |
907 | self._hb_channel = self.hb_channel_class(self.context, |
|
911 | self._hb_channel = self.hb_channel_class(self.context, | |
908 | self.session, |
|
912 | self.session, | |
909 | self.hb_address) |
|
913 | self.hb_address) | |
910 | return self._hb_channel |
|
914 | return self._hb_channel |
General Comments 0
You need to be logged in to leave comments.
Login now