##// END OF EJS Templates
Created HistoryManager to better organize history control....
Fernando Perez -
Show More
@@ -1,283 +1,431 b''
1 # -*- coding: utf-8 -*-
2 """ History related magics and functionality """
1 """ History related magics and functionality """
2 #-----------------------------------------------------------------------------
3 # Copyright (C) 2010 The IPython Development Team.
4 #
5 # Distributed under the terms of the BSD License.
6 #
7 # The full license is in the file COPYING.txt, distributed with this software.
8 #-----------------------------------------------------------------------------
9
10 #-----------------------------------------------------------------------------
11 # Imports
12 #-----------------------------------------------------------------------------
13 from __future__ import print_function
3
14
4 # Stdlib imports
15 # Stdlib imports
5 import fnmatch
16 import fnmatch
6 import os
17 import os
18 import sys
7
19
20 # Our own packages
8 import IPython.utils.io
21 import IPython.utils.io
22
23 from IPython.core import ipapi
24 from IPython.core.inputlist import InputList
25 from IPython.utils.pickleshare import PickleShareDB
9 from IPython.utils.io import ask_yes_no
26 from IPython.utils.io import ask_yes_no
10 from IPython.utils.warn import warn
27 from IPython.utils.warn import warn
11 from IPython.core import ipapi
28
29 #-----------------------------------------------------------------------------
30 # Classes and functions
31 #-----------------------------------------------------------------------------
32
33 class HistoryManager(object):
34 """A class to organize all history-related functionality in one place.
35 """
36 def __init__(self, shell):
37 """Create a new history manager associated with a shell instance.
38 """
39 self.shell = shell
40
41 # List of input with multi-line handling.
42 self.input_hist = InputList()
43 # This one will hold the 'raw' input history, without any
44 # pre-processing. This will allow users to retrieve the input just as
45 # it was exactly typed in by the user, with %hist -r.
46 self.input_hist_raw = InputList()
47
48 # list of visited directories
49 try:
50 self.dir_hist = [os.getcwd()]
51 except OSError:
52 self.dir_hist = []
53
54 # dict of output history
55 self.output_hist = {}
56
57 # Now the history file
58 if shell.profile:
59 histfname = 'history-%s' % shell.profile
60 else:
61 histfname = 'history'
62 self.hist_file = os.path.join(shell.ipython_dir, histfname)
63
64 # Fill the history zero entry, user counter starts at 1
65 self.input_hist.append('\n')
66 self.input_hist_raw.append('\n')
67
68 # Objects related to shadow history management
69 self._init_shadow_hist()
70
71 # For backwards compatibility, we must put these back in the shell
72 # object, until we've removed all direct uses of the history objects in
73 # the shell itself.
74 shell.input_hist = self.input_hist
75 shell.input_hist_raw = self.input_hist_raw
76 shell.output_hist = self.output_hist
77 shell.dir_hist = self.dir_hist
78 shell.histfile = self.hist_file
79 shell.shadowhist = self.shadow_hist
80 shell.db = self.shadow_db
81
82 def _init_shadow_hist(self):
83 try:
84 self.shadow_db = PickleShareDB(os.path.join(
85 self.shell.ipython_dir, 'db'))
86 except UnicodeDecodeError:
87 print("Your ipython_dir can't be decoded to unicode!")
88 print("Please set HOME environment variable to something that")
89 print(r"only has ASCII characters, e.g. c:\home")
90 print("Now it is", self.ipython_dir)
91 sys.exit()
92 self.shadow_hist = ShadowHist(self.shadow_db)
93
94 def save_hist(self):
95 """Save input history to a file (via readline library)."""
96
97 try:
98 self.shell.readline.write_history_file(self.hist_file)
99 except:
100 print('Unable to save IPython command history to file: ' +
101 `self.hist_file`)
102
103 def reload_hist(self):
104 """Reload the input history from disk file."""
105
106 try:
107 self.shell.readline.clear_history()
108 self.shell.readline.read_history_file(self.hist_file)
109 except AttributeError:
110 pass
111
112 def get_history(self, index=None, raw=False, output=True):
113 """Get the history list.
114
115 Get the input and output history.
116
117 Parameters
118 ----------
119 index : n or (n1, n2) or None
120 If n, then the last entries. If a tuple, then all in
121 range(n1, n2). If None, then all entries. Raises IndexError if
122 the format of index is incorrect.
123 raw : bool
124 If True, return the raw input.
125 output : bool
126 If True, then return the output as well.
127
128 Returns
129 -------
130 If output is True, then return a dict of tuples, keyed by the prompt
131 numbers and with values of (input, output). If output is False, then
132 a dict, keyed by the prompt number with the values of input. Raises
133 IndexError if no history is found.
134 """
135 if raw:
136 input_hist = self.input_hist_raw
137 else:
138 input_hist = self.input_hist
139 if output:
140 output_hist = self.output_hist
141 n = len(input_hist)
142 if index is None:
143 start=0; stop=n
144 elif isinstance(index, int):
145 start=n-index; stop=n
146 elif isinstance(index, tuple) and len(index) == 2:
147 start=index[0]; stop=index[1]
148 else:
149 raise IndexError('Not a valid index for the input history: %r'
150 % index)
151 hist = {}
152 for i in range(start, stop):
153 if output:
154 hist[i] = (input_hist[i], output_hist.get(i))
155 else:
156 hist[i] = input_hist[i]
157 if len(hist)==0:
158 raise IndexError('No history for range of indices: %r' % index)
159 return hist
160
12
161
13 def magic_history(self, parameter_s = ''):
162 def magic_history(self, parameter_s = ''):
14 """Print input history (_i<n> variables), with most recent last.
163 """Print input history (_i<n> variables), with most recent last.
15
164
16 %history -> print at most 40 inputs (some may be multi-line)\\
165 %history -> print at most 40 inputs (some may be multi-line)\\
17 %history n -> print at most n inputs\\
166 %history n -> print at most n inputs\\
18 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
167 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
19
168
20 By default, input history is printed without line numbers so it can be
169 By default, input history is printed without line numbers so it can be
21 directly pasted into an editor.
170 directly pasted into an editor.
22
171
23 With -n, each input's number <n> is shown, and is accessible as the
172 With -n, each input's number <n> is shown, and is accessible as the
24 automatically generated variable _i<n> as well as In[<n>]. Multi-line
173 automatically generated variable _i<n> as well as In[<n>]. Multi-line
25 statements are printed starting at a new line for easy copy/paste.
174 statements are printed starting at a new line for easy copy/paste.
26
175
27 Options:
176 Options:
28
177
29 -n: print line numbers for each input.
178 -n: print line numbers for each input.
30 This feature is only available if numbered prompts are in use.
179 This feature is only available if numbered prompts are in use.
31
180
32 -o: also print outputs for each input.
181 -o: also print outputs for each input.
33
182
34 -p: print classic '>>>' python prompts before each input. This is useful
183 -p: print classic '>>>' python prompts before each input. This is useful
35 for making documentation, and in conjunction with -o, for producing
184 for making documentation, and in conjunction with -o, for producing
36 doctest-ready output.
185 doctest-ready output.
37
186
38 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
187 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
39
188
40 -t: print the 'translated' history, as IPython understands it. IPython
189 -t: print the 'translated' history, as IPython understands it. IPython
41 filters your input and converts it all into valid Python source before
190 filters your input and converts it all into valid Python source before
42 executing it (things like magics or aliases are turned into function
191 executing it (things like magics or aliases are turned into function
43 calls, for example). With this option, you'll see the native history
192 calls, for example). With this option, you'll see the native history
44 instead of the user-entered version: '%cd /' will be seen as
193 instead of the user-entered version: '%cd /' will be seen as
45 'get_ipython().magic("%cd /")' instead of '%cd /'.
194 'get_ipython().magic("%cd /")' instead of '%cd /'.
46
195
47 -g: treat the arg as a pattern to grep for in (full) history.
196 -g: treat the arg as a pattern to grep for in (full) history.
48 This includes the "shadow history" (almost all commands ever written).
197 This includes the "shadow history" (almost all commands ever written).
49 Use '%hist -g' to show full shadow history (may be very long).
198 Use '%hist -g' to show full shadow history (may be very long).
50 In shadow history, every index nuwber starts with 0.
199 In shadow history, every index nuwber starts with 0.
51
200
52 -f FILENAME: instead of printing the output to the screen, redirect it to
201 -f FILENAME: instead of printing the output to the screen, redirect it to
53 the given file. The file is always overwritten, though IPython asks for
202 the given file. The file is always overwritten, though IPython asks for
54 confirmation first if it already exists.
203 confirmation first if it already exists.
55 """
204 """
56
205
57 if not self.shell.displayhook.do_full_cache:
206 if not self.shell.displayhook.do_full_cache:
58 print 'This feature is only available if numbered prompts are in use.'
207 print('This feature is only available if numbered prompts are in use.')
59 return
208 return
60 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
209 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
61
210
62 # Check if output to specific file was requested.
211 # Check if output to specific file was requested.
63 try:
212 try:
64 outfname = opts['f']
213 outfname = opts['f']
65 except KeyError:
214 except KeyError:
66 outfile = IPython.utils.io.Term.cout # default
215 outfile = IPython.utils.io.Term.cout # default
67 # We don't want to close stdout at the end!
216 # We don't want to close stdout at the end!
68 close_at_end = False
217 close_at_end = False
69 else:
218 else:
70 if os.path.exists(outfname):
219 if os.path.exists(outfname):
71 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
220 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
72 print 'Aborting.'
221 print('Aborting.')
73 return
222 return
74
223
75 outfile = open(outfname,'w')
224 outfile = open(outfname,'w')
76 close_at_end = True
225 close_at_end = True
77
226
78 if 't' in opts:
227 if 't' in opts:
79 input_hist = self.shell.input_hist
228 input_hist = self.shell.input_hist
80 elif 'r' in opts:
229 elif 'r' in opts:
81 input_hist = self.shell.input_hist_raw
230 input_hist = self.shell.input_hist_raw
82 else:
231 else:
83 # Raw history is the default
232 # Raw history is the default
84 input_hist = self.shell.input_hist_raw
233 input_hist = self.shell.input_hist_raw
85
234
86 default_length = 40
235 default_length = 40
87 pattern = None
236 pattern = None
88 if 'g' in opts:
237 if 'g' in opts:
89 init = 1
238 init = 1
90 final = len(input_hist)
239 final = len(input_hist)
91 parts = parameter_s.split(None, 1)
240 parts = parameter_s.split(None, 1)
92 if len(parts) == 1:
241 if len(parts) == 1:
93 parts += '*'
242 parts += '*'
94 head, pattern = parts
243 head, pattern = parts
95 pattern = "*" + pattern + "*"
244 pattern = "*" + pattern + "*"
96 elif len(args) == 0:
245 elif len(args) == 0:
97 final = len(input_hist)-1
246 final = len(input_hist)-1
98 init = max(1,final-default_length)
247 init = max(1,final-default_length)
99 elif len(args) == 1:
248 elif len(args) == 1:
100 final = len(input_hist)
249 final = len(input_hist)
101 init = max(1, final-int(args[0]))
250 init = max(1, final-int(args[0]))
102 elif len(args) == 2:
251 elif len(args) == 2:
103 init, final = map(int, args)
252 init, final = map(int, args)
104 else:
253 else:
105 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
254 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
106 print >> IPython.utils.io.Term.cout, self.magic_hist.__doc__
255 print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout)
107 return
256 return
108
257
109 width = len(str(final))
258 width = len(str(final))
110 line_sep = ['','\n']
259 line_sep = ['','\n']
111 print_nums = 'n' in opts
260 print_nums = 'n' in opts
112 print_outputs = 'o' in opts
261 print_outputs = 'o' in opts
113 pyprompts = 'p' in opts
262 pyprompts = 'p' in opts
114
263
115 found = False
264 found = False
116 if pattern is not None:
265 if pattern is not None:
117 sh = self.shell.shadowhist.all()
266 sh = self.shell.shadowhist.all()
118 for idx, s in sh:
267 for idx, s in sh:
119 if fnmatch.fnmatch(s, pattern):
268 if fnmatch.fnmatch(s, pattern):
120 print >> outfile, "0%d: %s" %(idx, s.expandtabs(4))
269 print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile)
121 found = True
270 found = True
122
271
123 if found:
272 if found:
124 print >> outfile, "==="
273 print("===", file=outfile)
125 print >> outfile, \
274 print("shadow history ends, fetch by %rep <number> (must start with 0)",
126 "shadow history ends, fetch by %rep <number> (must start with 0)"
275 file=outfile)
127 print >> outfile, "=== start of normal history ==="
276 print("=== start of normal history ===", file=outfile)
128
277
129 for in_num in range(init, final):
278 for in_num in range(init, final):
130 # Print user history with tabs expanded to 4 spaces. The GUI clients
279 # Print user history with tabs expanded to 4 spaces. The GUI clients
131 # use hard tabs for easier usability in auto-indented code, but we want
280 # use hard tabs for easier usability in auto-indented code, but we want
132 # to produce PEP-8 compliant history for safe pasting into an editor.
281 # to produce PEP-8 compliant history for safe pasting into an editor.
133 inline = input_hist[in_num].expandtabs(4)
282 inline = input_hist[in_num].expandtabs(4)
134
283
135 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
284 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
136 continue
285 continue
137
286
138 multiline = int(inline.count('\n') > 1)
287 multiline = int(inline.count('\n') > 1)
139 if print_nums:
288 if print_nums:
140 print >> outfile, \
289 print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
141 '%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
290 file=outfile)
142 if pyprompts:
291 if pyprompts:
143 print >> outfile, '>>>',
292 print('>>>', file=outfile)
144 if multiline:
293 if multiline:
145 lines = inline.splitlines()
294 lines = inline.splitlines()
146 print >> outfile, '\n... '.join(lines)
295 print('\n... '.join(lines), file=outfile)
147 print >> outfile, '... '
296 print('... ', file=outfile)
148 else:
297 else:
149 print >> outfile, inline,
298 print(inline, end='', file=outfile)
150 else:
299 else:
151 print >> outfile, inline,
300 print(inline,end='', file=outfile)
152 if print_outputs:
301 if print_outputs:
153 output = self.shell.output_hist.get(in_num)
302 output = self.shell.output_hist.get(in_num)
154 if output is not None:
303 if output is not None:
155 print >> outfile, repr(output)
304 print(repr(output), file=outfile)
156
305
157 if close_at_end:
306 if close_at_end:
158 outfile.close()
307 outfile.close()
159
308
160
309
161 def magic_hist(self, parameter_s=''):
310 def magic_hist(self, parameter_s=''):
162 """Alternate name for %history."""
311 """Alternate name for %history."""
163 return self.magic_history(parameter_s)
312 return self.magic_history(parameter_s)
164
313
165
314
166 def rep_f(self, arg):
315 def rep_f(self, arg):
167 r""" Repeat a command, or get command to input line for editing
316 r""" Repeat a command, or get command to input line for editing
168
317
169 - %rep (no arguments):
318 - %rep (no arguments):
170
319
171 Place a string version of last computation result (stored in the special '_'
320 Place a string version of last computation result (stored in the special '_'
172 variable) to the next input prompt. Allows you to create elaborate command
321 variable) to the next input prompt. Allows you to create elaborate command
173 lines without using copy-paste::
322 lines without using copy-paste::
174
323
175 $ l = ["hei", "vaan"]
324 $ l = ["hei", "vaan"]
176 $ "".join(l)
325 $ "".join(l)
177 ==> heivaan
326 ==> heivaan
178 $ %rep
327 $ %rep
179 $ heivaan_ <== cursor blinking
328 $ heivaan_ <== cursor blinking
180
329
181 %rep 45
330 %rep 45
182
331
183 Place history line 45 to next input prompt. Use %hist to find out the
332 Place history line 45 to next input prompt. Use %hist to find out the
184 number.
333 number.
185
334
186 %rep 1-4 6-7 3
335 %rep 1-4 6-7 3
187
336
188 Repeat the specified lines immediately. Input slice syntax is the same as
337 Repeat the specified lines immediately. Input slice syntax is the same as
189 in %macro and %save.
338 in %macro and %save.
190
339
191 %rep foo
340 %rep foo
192
341
193 Place the most recent line that has the substring "foo" to next input.
342 Place the most recent line that has the substring "foo" to next input.
194 (e.g. 'svn ci -m foobar').
343 (e.g. 'svn ci -m foobar').
195 """
344 """
196
345
197 opts,args = self.parse_options(arg,'',mode='list')
346 opts,args = self.parse_options(arg,'',mode='list')
198 if not args:
347 if not args:
199 self.set_next_input(str(self.shell.user_ns["_"]))
348 self.set_next_input(str(self.shell.user_ns["_"]))
200 return
349 return
201
350
202 if len(args) == 1 and not '-' in args[0]:
351 if len(args) == 1 and not '-' in args[0]:
203 arg = args[0]
352 arg = args[0]
204 if len(arg) > 1 and arg.startswith('0'):
353 if len(arg) > 1 and arg.startswith('0'):
205 # get from shadow hist
354 # get from shadow hist
206 num = int(arg[1:])
355 num = int(arg[1:])
207 line = self.shell.shadowhist.get(num)
356 line = self.shell.shadowhist.get(num)
208 self.set_next_input(str(line))
357 self.set_next_input(str(line))
209 return
358 return
210 try:
359 try:
211 num = int(args[0])
360 num = int(args[0])
212 self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip())
361 self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip())
213 return
362 return
214 except ValueError:
363 except ValueError:
215 pass
364 pass
216
365
217 for h in reversed(self.shell.input_hist_raw):
366 for h in reversed(self.shell.input_hist_raw):
218 if 'rep' in h:
367 if 'rep' in h:
219 continue
368 continue
220 if fnmatch.fnmatch(h,'*' + arg + '*'):
369 if fnmatch.fnmatch(h,'*' + arg + '*'):
221 self.set_next_input(str(h).rstrip())
370 self.set_next_input(str(h).rstrip())
222 return
371 return
223
372
224 try:
373 try:
225 lines = self.extract_input_slices(args, True)
374 lines = self.extract_input_slices(args, True)
226 print "lines",lines
375 print("lines", lines)
227 self.runlines(lines)
376 self.runlines(lines)
228 except ValueError:
377 except ValueError:
229 print "Not found in recent history:", args
378 print("Not found in recent history:", args)
230
379
231
380
232 _sentinel = object()
381 _sentinel = object()
233
382
234 class ShadowHist(object):
383 class ShadowHist(object):
235 def __init__(self, db):
384 def __init__(self, db):
236 # cmd => idx mapping
385 # cmd => idx mapping
237 self.curidx = 0
386 self.curidx = 0
238 self.db = db
387 self.db = db
239 self.disabled = False
388 self.disabled = False
240
389
241 def inc_idx(self):
390 def inc_idx(self):
242 idx = self.db.get('shadowhist_idx', 1)
391 idx = self.db.get('shadowhist_idx', 1)
243 self.db['shadowhist_idx'] = idx + 1
392 self.db['shadowhist_idx'] = idx + 1
244 return idx
393 return idx
245
394
246 def add(self, ent):
395 def add(self, ent):
247 if self.disabled:
396 if self.disabled:
248 return
397 return
249 try:
398 try:
250 old = self.db.hget('shadowhist', ent, _sentinel)
399 old = self.db.hget('shadowhist', ent, _sentinel)
251 if old is not _sentinel:
400 if old is not _sentinel:
252 return
401 return
253 newidx = self.inc_idx()
402 newidx = self.inc_idx()
254 #print "new",newidx # dbg
403 #print("new", newidx) # dbg
255 self.db.hset('shadowhist',ent, newidx)
404 self.db.hset('shadowhist',ent, newidx)
256 except:
405 except:
257 ipapi.get().showtraceback()
406 ipapi.get().showtraceback()
258 print "WARNING: disabling shadow history"
407 print("WARNING: disabling shadow history")
259 self.disabled = True
408 self.disabled = True
260
409
261 def all(self):
410 def all(self):
262 d = self.db.hdict('shadowhist')
411 d = self.db.hdict('shadowhist')
263 items = [(i,s) for (s,i) in d.items()]
412 items = [(i,s) for (s,i) in d.items()]
264 items.sort()
413 items.sort()
265 return items
414 return items
266
415
267 def get(self, idx):
416 def get(self, idx):
268 all = self.all()
417 all = self.all()
269
418
270 for k, v in all:
419 for k, v in all:
271 #print k,v
272 if k == idx:
420 if k == idx:
273 return v
421 return v
274
422
275
423
276 def init_ipython(ip):
424 def init_ipython(ip):
277 ip.define_magic("rep",rep_f)
425 ip.define_magic("rep",rep_f)
278 ip.define_magic("hist",magic_hist)
426 ip.define_magic("hist",magic_hist)
279 ip.define_magic("history",magic_history)
427 ip.define_magic("history",magic_history)
280
428
281 # XXX - ipy_completers are in quarantine, need to be updated to new apis
429 # XXX - ipy_completers are in quarantine, need to be updated to new apis
282 #import ipy_completers
430 #import ipy_completers
283 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
431 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,2619 +1,2539 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-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 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 exceptions
25 import exceptions
26 import new
26 import new
27 import os
27 import os
28 import re
28 import re
29 import string
29 import string
30 import sys
30 import sys
31 import tempfile
31 import tempfile
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
36 from IPython.core import history as ipcorehist
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager
41 from IPython.core.alias import AliasManager
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.display_trap import DisplayTrap
44 from IPython.core.displayhook import DisplayHook
44 from IPython.core.displayhook import DisplayHook
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.history import HistoryManager
48 from IPython.core.inputlist import InputList
49 from IPython.core.inputlist import InputList
49 from IPython.core.inputsplitter import IPythonInputSplitter
50 from IPython.core.inputsplitter import IPythonInputSplitter
50 from IPython.core.logger import Logger
51 from IPython.core.logger import Logger
51 from IPython.core.magic import Magic
52 from IPython.core.magic import Magic
52 from IPython.core.payload import PayloadManager
53 from IPython.core.payload import PayloadManager
53 from IPython.core.plugin import PluginManager
54 from IPython.core.plugin import PluginManager
54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
55 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
55 from IPython.external.Itpl import ItplNS
56 from IPython.external.Itpl import ItplNS
56 from IPython.utils import PyColorize
57 from IPython.utils import PyColorize
57 from IPython.utils import io
58 from IPython.utils import io
58 from IPython.utils import pickleshare
59 from IPython.utils import pickleshare
59 from IPython.utils.doctestreload import doctest_reload
60 from IPython.utils.doctestreload import doctest_reload
60 from IPython.utils.io import ask_yes_no, rprint
61 from IPython.utils.io import ask_yes_no, rprint
61 from IPython.utils.ipstruct import Struct
62 from IPython.utils.ipstruct import Struct
62 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
63 from IPython.utils.process import system, getoutput
64 from IPython.utils.process import system, getoutput
64 from IPython.utils.strdispatch import StrDispatch
65 from IPython.utils.strdispatch import StrDispatch
65 from IPython.utils.syspathcontext import prepended_to_syspath
66 from IPython.utils.syspathcontext import prepended_to_syspath
66 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
67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
68 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
68 List, Unicode, Instance, Type)
69 List, Unicode, Instance, Type)
69 from IPython.utils.warn import warn, error, fatal
70 from IPython.utils.warn import warn, error, fatal
70 import IPython.core.hooks
71 import IPython.core.hooks
71
72
72 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
73 # Globals
74 # Globals
74 #-----------------------------------------------------------------------------
75 #-----------------------------------------------------------------------------
75
76
76 # compiled regexps for autoindent management
77 # compiled regexps for autoindent management
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78
79
79 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
80 # Utilities
81 # Utilities
81 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
82
83
83 # 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
84 # overwrites it (like wx.py.PyShell does)
85 # overwrites it (like wx.py.PyShell does)
85 raw_input_original = raw_input
86 raw_input_original = raw_input
86
87
87 def softspace(file, newvalue):
88 def softspace(file, newvalue):
88 """Copied from code.py, to remove the dependency"""
89 """Copied from code.py, to remove the dependency"""
89
90
90 oldvalue = 0
91 oldvalue = 0
91 try:
92 try:
92 oldvalue = file.softspace
93 oldvalue = file.softspace
93 except AttributeError:
94 except AttributeError:
94 pass
95 pass
95 try:
96 try:
96 file.softspace = newvalue
97 file.softspace = newvalue
97 except (AttributeError, TypeError):
98 except (AttributeError, TypeError):
98 # "attribute-less object" or "read-only attributes"
99 # "attribute-less object" or "read-only attributes"
99 pass
100 pass
100 return oldvalue
101 return oldvalue
101
102
102
103
103 def no_op(*a, **kw): pass
104 def no_op(*a, **kw): pass
104
105
105 class SpaceInInput(exceptions.Exception): pass
106 class SpaceInInput(exceptions.Exception): pass
106
107
107 class Bunch: pass
108 class Bunch: pass
108
109
109
110
110 def get_default_colors():
111 def get_default_colors():
111 if sys.platform=='darwin':
112 if sys.platform=='darwin':
112 return "LightBG"
113 return "LightBG"
113 elif os.name=='nt':
114 elif os.name=='nt':
114 return 'Linux'
115 return 'Linux'
115 else:
116 else:
116 return 'Linux'
117 return 'Linux'
117
118
118
119
119 class SeparateStr(Str):
120 class SeparateStr(Str):
120 """A Str subclass to validate separate_in, separate_out, etc.
121 """A Str subclass to validate separate_in, separate_out, etc.
121
122
122 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'.
123 """
124 """
124
125
125 def validate(self, obj, value):
126 def validate(self, obj, value):
126 if value == '0': value = ''
127 if value == '0': value = ''
127 value = value.replace('\\n','\n')
128 value = value.replace('\\n','\n')
128 return super(SeparateStr, self).validate(obj, value)
129 return super(SeparateStr, self).validate(obj, value)
129
130
130 class MultipleInstanceError(Exception):
131 class MultipleInstanceError(Exception):
131 pass
132 pass
132
133
133
134
134 #-----------------------------------------------------------------------------
135 #-----------------------------------------------------------------------------
135 # Main IPython class
136 # Main IPython class
136 #-----------------------------------------------------------------------------
137 #-----------------------------------------------------------------------------
137
138
138
139
139 class InteractiveShell(Configurable, Magic):
140 class InteractiveShell(Configurable, Magic):
140 """An enhanced, interactive shell for Python."""
141 """An enhanced, interactive shell for Python."""
141
142
142 _instance = None
143 _instance = None
143 autocall = Enum((0,1,2), default_value=1, config=True)
144 autocall = Enum((0,1,2), default_value=1, config=True)
144 # TODO: remove all autoindent logic and put into frontends.
145 # TODO: remove all autoindent logic and put into frontends.
145 # We can't do this yet because even runlines uses the autoindent.
146 # We can't do this yet because even runlines uses the autoindent.
146 autoindent = CBool(True, config=True)
147 autoindent = CBool(True, config=True)
147 automagic = CBool(True, config=True)
148 automagic = CBool(True, config=True)
148 cache_size = Int(1000, config=True)
149 cache_size = Int(1000, config=True)
149 color_info = CBool(True, config=True)
150 color_info = CBool(True, config=True)
150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
151 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
151 default_value=get_default_colors(), config=True)
152 default_value=get_default_colors(), config=True)
152 debug = CBool(False, config=True)
153 debug = CBool(False, config=True)
153 deep_reload = CBool(False, config=True)
154 deep_reload = CBool(False, config=True)
154 displayhook_class = Type(DisplayHook)
155 displayhook_class = Type(DisplayHook)
155 exit_now = CBool(False)
156 exit_now = CBool(False)
156 filename = Str("<ipython console>")
157 filename = Str("<ipython console>")
157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158
159
159 # Input splitter, to split entire cells of input into either individual
160 # Input splitter, to split entire cells of input into either individual
160 # interactive statements or whole blocks.
161 # interactive statements or whole blocks.
161 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
162 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
162 (), {})
163 (), {})
163 logstart = CBool(False, config=True)
164 logstart = CBool(False, config=True)
164 logfile = Str('', config=True)
165 logfile = Str('', config=True)
165 logappend = Str('', config=True)
166 logappend = Str('', config=True)
166 object_info_string_level = Enum((0,1,2), default_value=0,
167 object_info_string_level = Enum((0,1,2), default_value=0,
167 config=True)
168 config=True)
168 pdb = CBool(False, config=True)
169 pdb = CBool(False, config=True)
169
170
170 pprint = CBool(True, config=True)
171 pprint = CBool(True, config=True)
171 profile = Str('', config=True)
172 profile = Str('', config=True)
172 prompt_in1 = Str('In [\\#]: ', config=True)
173 prompt_in1 = Str('In [\\#]: ', config=True)
173 prompt_in2 = Str(' .\\D.: ', config=True)
174 prompt_in2 = Str(' .\\D.: ', config=True)
174 prompt_out = Str('Out[\\#]: ', config=True)
175 prompt_out = Str('Out[\\#]: ', config=True)
175 prompts_pad_left = CBool(True, config=True)
176 prompts_pad_left = CBool(True, config=True)
176 quiet = CBool(False, config=True)
177 quiet = CBool(False, config=True)
177
178
178 # The readline stuff will eventually be moved to the terminal subclass
179 # The readline stuff will eventually be moved to the terminal subclass
179 # but for now, we can't do that as readline is welded in everywhere.
180 # but for now, we can't do that as readline is welded in everywhere.
180 readline_use = CBool(True, config=True)
181 readline_use = CBool(True, config=True)
181 readline_merge_completions = CBool(True, config=True)
182 readline_merge_completions = CBool(True, config=True)
182 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
183 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
183 readline_remove_delims = Str('-/~', config=True)
184 readline_remove_delims = Str('-/~', config=True)
184 readline_parse_and_bind = List([
185 readline_parse_and_bind = List([
185 'tab: complete',
186 'tab: complete',
186 '"\C-l": clear-screen',
187 '"\C-l": clear-screen',
187 'set show-all-if-ambiguous on',
188 'set show-all-if-ambiguous on',
188 '"\C-o": tab-insert',
189 '"\C-o": tab-insert',
189 '"\M-i": " "',
190 '"\M-i": " "',
190 '"\M-o": "\d\d\d\d"',
191 '"\M-o": "\d\d\d\d"',
191 '"\M-I": "\d\d\d\d"',
192 '"\M-I": "\d\d\d\d"',
192 '"\C-r": reverse-search-history',
193 '"\C-r": reverse-search-history',
193 '"\C-s": forward-search-history',
194 '"\C-s": forward-search-history',
194 '"\C-p": history-search-backward',
195 '"\C-p": history-search-backward',
195 '"\C-n": history-search-forward',
196 '"\C-n": history-search-forward',
196 '"\e[A": history-search-backward',
197 '"\e[A": history-search-backward',
197 '"\e[B": history-search-forward',
198 '"\e[B": history-search-forward',
198 '"\C-k": kill-line',
199 '"\C-k": kill-line',
199 '"\C-u": unix-line-discard',
200 '"\C-u": unix-line-discard',
200 ], allow_none=False, config=True)
201 ], allow_none=False, config=True)
201
202
202 # TODO: this part of prompt management should be moved to the frontends.
203 # TODO: this part of prompt management should be moved to the frontends.
203 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
204 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
204 separate_in = SeparateStr('\n', config=True)
205 separate_in = SeparateStr('\n', config=True)
205 separate_out = SeparateStr('', config=True)
206 separate_out = SeparateStr('', config=True)
206 separate_out2 = SeparateStr('', config=True)
207 separate_out2 = SeparateStr('', config=True)
207 wildcards_case_sensitive = CBool(True, config=True)
208 wildcards_case_sensitive = CBool(True, config=True)
208 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
209 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
209 default_value='Context', config=True)
210 default_value='Context', config=True)
210
211
211 # Subcomponents of InteractiveShell
212 # Subcomponents of InteractiveShell
212 alias_manager = Instance('IPython.core.alias.AliasManager')
213 alias_manager = Instance('IPython.core.alias.AliasManager')
213 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
214 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
214 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
215 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
215 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
216 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
216 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
217 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
217 plugin_manager = Instance('IPython.core.plugin.PluginManager')
218 plugin_manager = Instance('IPython.core.plugin.PluginManager')
218 payload_manager = Instance('IPython.core.payload.PayloadManager')
219 payload_manager = Instance('IPython.core.payload.PayloadManager')
219
220 history_manager = Instance('IPython.core.history.HistoryManager')
221
220 # Private interface
222 # Private interface
221 _post_execute = set()
223 _post_execute = set()
222
224
223 def __init__(self, config=None, ipython_dir=None,
225 def __init__(self, config=None, ipython_dir=None,
224 user_ns=None, user_global_ns=None,
226 user_ns=None, user_global_ns=None,
225 custom_exceptions=((), None)):
227 custom_exceptions=((), None)):
226
228
227 # This is where traits with a config_key argument are updated
229 # This is where traits with a config_key argument are updated
228 # from the values on config.
230 # from the values on config.
229 super(InteractiveShell, self).__init__(config=config)
231 super(InteractiveShell, self).__init__(config=config)
230
232
231 # These are relatively independent and stateless
233 # These are relatively independent and stateless
232 self.init_ipython_dir(ipython_dir)
234 self.init_ipython_dir(ipython_dir)
233 self.init_instance_attrs()
235 self.init_instance_attrs()
234 self.init_environment()
236 self.init_environment()
235
237
236 # Create namespaces (user_ns, user_global_ns, etc.)
238 # Create namespaces (user_ns, user_global_ns, etc.)
237 self.init_create_namespaces(user_ns, user_global_ns)
239 self.init_create_namespaces(user_ns, user_global_ns)
238 # This has to be done after init_create_namespaces because it uses
240 # This has to be done after init_create_namespaces because it uses
239 # something in self.user_ns, but before init_sys_modules, which
241 # something in self.user_ns, but before init_sys_modules, which
240 # is the first thing to modify sys.
242 # is the first thing to modify sys.
241 # TODO: When we override sys.stdout and sys.stderr before this class
243 # TODO: When we override sys.stdout and sys.stderr before this class
242 # is created, we are saving the overridden ones here. Not sure if this
244 # is created, we are saving the overridden ones here. Not sure if this
243 # is what we want to do.
245 # is what we want to do.
244 self.save_sys_module_state()
246 self.save_sys_module_state()
245 self.init_sys_modules()
247 self.init_sys_modules()
246
248
247 self.init_history()
249 self.init_history()
248 self.init_encoding()
250 self.init_encoding()
249 self.init_prefilter()
251 self.init_prefilter()
250
252
251 Magic.__init__(self, self)
253 Magic.__init__(self, self)
252
254
253 self.init_syntax_highlighting()
255 self.init_syntax_highlighting()
254 self.init_hooks()
256 self.init_hooks()
255 self.init_pushd_popd_magic()
257 self.init_pushd_popd_magic()
256 # self.init_traceback_handlers use to be here, but we moved it below
258 # self.init_traceback_handlers use to be here, but we moved it below
257 # because it and init_io have to come after init_readline.
259 # because it and init_io have to come after init_readline.
258 self.init_user_ns()
260 self.init_user_ns()
259 self.init_logger()
261 self.init_logger()
260 self.init_alias()
262 self.init_alias()
261 self.init_builtins()
263 self.init_builtins()
262
264
263 # pre_config_initialization
265 # pre_config_initialization
264 self.init_shadow_hist()
265
266
266 # The next section should contain everything that was in ipmaker.
267 # The next section should contain everything that was in ipmaker.
267 self.init_logstart()
268 self.init_logstart()
268
269
269 # The following was in post_config_initialization
270 # The following was in post_config_initialization
270 self.init_inspector()
271 self.init_inspector()
271 # init_readline() must come before init_io(), because init_io uses
272 # init_readline() must come before init_io(), because init_io uses
272 # readline related things.
273 # readline related things.
273 self.init_readline()
274 self.init_readline()
274 # init_completer must come after init_readline, because it needs to
275 # init_completer must come after init_readline, because it needs to
275 # know whether readline is present or not system-wide to configure the
276 # know whether readline is present or not system-wide to configure the
276 # completers, since the completion machinery can now operate
277 # completers, since the completion machinery can now operate
277 # independently of readline (e.g. over the network)
278 # independently of readline (e.g. over the network)
278 self.init_completer()
279 self.init_completer()
279 # TODO: init_io() needs to happen before init_traceback handlers
280 # TODO: init_io() needs to happen before init_traceback handlers
280 # because the traceback handlers hardcode the stdout/stderr streams.
281 # because the traceback handlers hardcode the stdout/stderr streams.
281 # This logic in in debugger.Pdb and should eventually be changed.
282 # This logic in in debugger.Pdb and should eventually be changed.
282 self.init_io()
283 self.init_io()
283 self.init_traceback_handlers(custom_exceptions)
284 self.init_traceback_handlers(custom_exceptions)
284 self.init_prompts()
285 self.init_prompts()
285 self.init_displayhook()
286 self.init_displayhook()
286 self.init_reload_doctest()
287 self.init_reload_doctest()
287 self.init_magics()
288 self.init_magics()
288 self.init_pdb()
289 self.init_pdb()
289 self.init_extension_manager()
290 self.init_extension_manager()
290 self.init_plugin_manager()
291 self.init_plugin_manager()
291 self.init_payload()
292 self.init_payload()
292 self.hooks.late_startup_hook()
293 self.hooks.late_startup_hook()
293 atexit.register(self.atexit_operations)
294 atexit.register(self.atexit_operations)
294
295
295 @classmethod
296 @classmethod
296 def instance(cls, *args, **kwargs):
297 def instance(cls, *args, **kwargs):
297 """Returns a global InteractiveShell instance."""
298 """Returns a global InteractiveShell instance."""
298 if cls._instance is None:
299 if cls._instance is None:
299 inst = cls(*args, **kwargs)
300 inst = cls(*args, **kwargs)
300 # Now make sure that the instance will also be returned by
301 # Now make sure that the instance will also be returned by
301 # the subclasses instance attribute.
302 # the subclasses instance attribute.
302 for subclass in cls.mro():
303 for subclass in cls.mro():
303 if issubclass(cls, subclass) and \
304 if issubclass(cls, subclass) and \
304 issubclass(subclass, InteractiveShell):
305 issubclass(subclass, InteractiveShell):
305 subclass._instance = inst
306 subclass._instance = inst
306 else:
307 else:
307 break
308 break
308 if isinstance(cls._instance, cls):
309 if isinstance(cls._instance, cls):
309 return cls._instance
310 return cls._instance
310 else:
311 else:
311 raise MultipleInstanceError(
312 raise MultipleInstanceError(
312 'Multiple incompatible subclass instances of '
313 'Multiple incompatible subclass instances of '
313 'InteractiveShell are being created.'
314 'InteractiveShell are being created.'
314 )
315 )
315
316
316 @classmethod
317 @classmethod
317 def initialized(cls):
318 def initialized(cls):
318 return hasattr(cls, "_instance")
319 return hasattr(cls, "_instance")
319
320
320 def get_ipython(self):
321 def get_ipython(self):
321 """Return the currently running IPython instance."""
322 """Return the currently running IPython instance."""
322 return self
323 return self
323
324
324 #-------------------------------------------------------------------------
325 #-------------------------------------------------------------------------
325 # Trait changed handlers
326 # Trait changed handlers
326 #-------------------------------------------------------------------------
327 #-------------------------------------------------------------------------
327
328
328 def _ipython_dir_changed(self, name, new):
329 def _ipython_dir_changed(self, name, new):
329 if not os.path.isdir(new):
330 if not os.path.isdir(new):
330 os.makedirs(new, mode = 0777)
331 os.makedirs(new, mode = 0777)
331
332
332 def set_autoindent(self,value=None):
333 def set_autoindent(self,value=None):
333 """Set the autoindent flag, checking for readline support.
334 """Set the autoindent flag, checking for readline support.
334
335
335 If called with no arguments, it acts as a toggle."""
336 If called with no arguments, it acts as a toggle."""
336
337
337 if not self.has_readline:
338 if not self.has_readline:
338 if os.name == 'posix':
339 if os.name == 'posix':
339 warn("The auto-indent feature requires the readline library")
340 warn("The auto-indent feature requires the readline library")
340 self.autoindent = 0
341 self.autoindent = 0
341 return
342 return
342 if value is None:
343 if value is None:
343 self.autoindent = not self.autoindent
344 self.autoindent = not self.autoindent
344 else:
345 else:
345 self.autoindent = value
346 self.autoindent = value
346
347
347 #-------------------------------------------------------------------------
348 #-------------------------------------------------------------------------
348 # init_* methods called by __init__
349 # init_* methods called by __init__
349 #-------------------------------------------------------------------------
350 #-------------------------------------------------------------------------
350
351
351 def init_ipython_dir(self, ipython_dir):
352 def init_ipython_dir(self, ipython_dir):
352 if ipython_dir is not None:
353 if ipython_dir is not None:
353 self.ipython_dir = ipython_dir
354 self.ipython_dir = ipython_dir
354 self.config.Global.ipython_dir = self.ipython_dir
355 self.config.Global.ipython_dir = self.ipython_dir
355 return
356 return
356
357
357 if hasattr(self.config.Global, 'ipython_dir'):
358 if hasattr(self.config.Global, 'ipython_dir'):
358 self.ipython_dir = self.config.Global.ipython_dir
359 self.ipython_dir = self.config.Global.ipython_dir
359 else:
360 else:
360 self.ipython_dir = get_ipython_dir()
361 self.ipython_dir = get_ipython_dir()
361
362
362 # All children can just read this
363 # All children can just read this
363 self.config.Global.ipython_dir = self.ipython_dir
364 self.config.Global.ipython_dir = self.ipython_dir
364
365
365 def init_instance_attrs(self):
366 def init_instance_attrs(self):
366 self.more = False
367 self.more = False
367
368
368 # command compiler
369 # command compiler
369 self.compile = codeop.CommandCompiler()
370 self.compile = codeop.CommandCompiler()
370
371
371 # User input buffer
372 # User input buffer
372 self.buffer = []
373 self.buffer = []
373
374
374 # Make an empty namespace, which extension writers can rely on both
375 # Make an empty namespace, which extension writers can rely on both
375 # existing and NEVER being used by ipython itself. This gives them a
376 # existing and NEVER being used by ipython itself. This gives them a
376 # convenient location for storing additional information and state
377 # convenient location for storing additional information and state
377 # their extensions may require, without fear of collisions with other
378 # their extensions may require, without fear of collisions with other
378 # ipython names that may develop later.
379 # ipython names that may develop later.
379 self.meta = Struct()
380 self.meta = Struct()
380
381
381 # Object variable to store code object waiting execution. This is
382 # Object variable to store code object waiting execution. This is
382 # used mainly by the multithreaded shells, but it can come in handy in
383 # used mainly by the multithreaded shells, but it can come in handy in
383 # other situations. No need to use a Queue here, since it's a single
384 # other situations. No need to use a Queue here, since it's a single
384 # item which gets cleared once run.
385 # item which gets cleared once run.
385 self.code_to_run = None
386 self.code_to_run = None
386
387
387 # Temporary files used for various purposes. Deleted at exit.
388 # Temporary files used for various purposes. Deleted at exit.
388 self.tempfiles = []
389 self.tempfiles = []
389
390
390 # Keep track of readline usage (later set by init_readline)
391 # Keep track of readline usage (later set by init_readline)
391 self.has_readline = False
392 self.has_readline = False
392
393
393 # keep track of where we started running (mainly for crash post-mortem)
394 # keep track of where we started running (mainly for crash post-mortem)
394 # This is not being used anywhere currently.
395 # This is not being used anywhere currently.
395 self.starting_dir = os.getcwd()
396 self.starting_dir = os.getcwd()
396
397
397 # Indentation management
398 # Indentation management
398 self.indent_current_nsp = 0
399 self.indent_current_nsp = 0
399
400
400 # Increasing execution counter
401 # Increasing execution counter
401 self.execution_count = 0
402 self.execution_count = 0
402
403
403 def init_environment(self):
404 def init_environment(self):
404 """Any changes we need to make to the user's environment."""
405 """Any changes we need to make to the user's environment."""
405 pass
406 pass
406
407
407 def init_encoding(self):
408 def init_encoding(self):
408 # Get system encoding at startup time. Certain terminals (like Emacs
409 # Get system encoding at startup time. Certain terminals (like Emacs
409 # under Win32 have it set to None, and we need to have a known valid
410 # under Win32 have it set to None, and we need to have a known valid
410 # encoding to use in the raw_input() method
411 # encoding to use in the raw_input() method
411 try:
412 try:
412 self.stdin_encoding = sys.stdin.encoding or 'ascii'
413 self.stdin_encoding = sys.stdin.encoding or 'ascii'
413 except AttributeError:
414 except AttributeError:
414 self.stdin_encoding = 'ascii'
415 self.stdin_encoding = 'ascii'
415
416
416 def init_syntax_highlighting(self):
417 def init_syntax_highlighting(self):
417 # Python source parser/formatter for syntax highlighting
418 # Python source parser/formatter for syntax highlighting
418 pyformat = PyColorize.Parser().format
419 pyformat = PyColorize.Parser().format
419 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
420 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
420
421
421 def init_pushd_popd_magic(self):
422 def init_pushd_popd_magic(self):
422 # for pushd/popd management
423 # for pushd/popd management
423 try:
424 try:
424 self.home_dir = get_home_dir()
425 self.home_dir = get_home_dir()
425 except HomeDirError, msg:
426 except HomeDirError, msg:
426 fatal(msg)
427 fatal(msg)
427
428
428 self.dir_stack = []
429 self.dir_stack = []
429
430
430 def init_logger(self):
431 def init_logger(self):
431 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
432 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
432 # local shortcut, this is used a LOT
433 # local shortcut, this is used a LOT
433 self.log = self.logger.log
434 self.log = self.logger.log
434
435
435 def init_logstart(self):
436 def init_logstart(self):
436 if self.logappend:
437 if self.logappend:
437 self.magic_logstart(self.logappend + ' append')
438 self.magic_logstart(self.logappend + ' append')
438 elif self.logfile:
439 elif self.logfile:
439 self.magic_logstart(self.logfile)
440 self.magic_logstart(self.logfile)
440 elif self.logstart:
441 elif self.logstart:
441 self.magic_logstart()
442 self.magic_logstart()
442
443
443 def init_builtins(self):
444 def init_builtins(self):
444 self.builtin_trap = BuiltinTrap(shell=self)
445 self.builtin_trap = BuiltinTrap(shell=self)
445
446
446 def init_inspector(self):
447 def init_inspector(self):
447 # Object inspector
448 # Object inspector
448 self.inspector = oinspect.Inspector(oinspect.InspectColors,
449 self.inspector = oinspect.Inspector(oinspect.InspectColors,
449 PyColorize.ANSICodeColors,
450 PyColorize.ANSICodeColors,
450 'NoColor',
451 'NoColor',
451 self.object_info_string_level)
452 self.object_info_string_level)
452
453
453 def init_io(self):
454 def init_io(self):
454 # This will just use sys.stdout and sys.stderr. If you want to
455 # This will just use sys.stdout and sys.stderr. If you want to
455 # override sys.stdout and sys.stderr themselves, you need to do that
456 # override sys.stdout and sys.stderr themselves, you need to do that
456 # *before* instantiating this class, because Term holds onto
457 # *before* instantiating this class, because Term holds onto
457 # references to the underlying streams.
458 # references to the underlying streams.
458 if sys.platform == 'win32' and self.has_readline:
459 if sys.platform == 'win32' and self.has_readline:
459 Term = io.IOTerm(cout=self.readline._outputfile,
460 Term = io.IOTerm(cout=self.readline._outputfile,
460 cerr=self.readline._outputfile)
461 cerr=self.readline._outputfile)
461 else:
462 else:
462 Term = io.IOTerm()
463 Term = io.IOTerm()
463 io.Term = Term
464 io.Term = Term
464
465
465 def init_prompts(self):
466 def init_prompts(self):
466 # TODO: This is a pass for now because the prompts are managed inside
467 # TODO: This is a pass for now because the prompts are managed inside
467 # the DisplayHook. Once there is a separate prompt manager, this
468 # the DisplayHook. Once there is a separate prompt manager, this
468 # will initialize that object and all prompt related information.
469 # will initialize that object and all prompt related information.
469 pass
470 pass
470
471
471 def init_displayhook(self):
472 def init_displayhook(self):
472 # Initialize displayhook, set in/out prompts and printing system
473 # Initialize displayhook, set in/out prompts and printing system
473 self.displayhook = self.displayhook_class(
474 self.displayhook = self.displayhook_class(
474 shell=self,
475 shell=self,
475 cache_size=self.cache_size,
476 cache_size=self.cache_size,
476 input_sep = self.separate_in,
477 input_sep = self.separate_in,
477 output_sep = self.separate_out,
478 output_sep = self.separate_out,
478 output_sep2 = self.separate_out2,
479 output_sep2 = self.separate_out2,
479 ps1 = self.prompt_in1,
480 ps1 = self.prompt_in1,
480 ps2 = self.prompt_in2,
481 ps2 = self.prompt_in2,
481 ps_out = self.prompt_out,
482 ps_out = self.prompt_out,
482 pad_left = self.prompts_pad_left
483 pad_left = self.prompts_pad_left
483 )
484 )
484 # This is a context manager that installs/revmoes the displayhook at
485 # This is a context manager that installs/revmoes the displayhook at
485 # the appropriate time.
486 # the appropriate time.
486 self.display_trap = DisplayTrap(hook=self.displayhook)
487 self.display_trap = DisplayTrap(hook=self.displayhook)
487
488
488 def init_reload_doctest(self):
489 def init_reload_doctest(self):
489 # Do a proper resetting of doctest, including the necessary displayhook
490 # Do a proper resetting of doctest, including the necessary displayhook
490 # monkeypatching
491 # monkeypatching
491 try:
492 try:
492 doctest_reload()
493 doctest_reload()
493 except ImportError:
494 except ImportError:
494 warn("doctest module does not exist.")
495 warn("doctest module does not exist.")
495
496
496 #-------------------------------------------------------------------------
497 #-------------------------------------------------------------------------
497 # Things related to injections into the sys module
498 # Things related to injections into the sys module
498 #-------------------------------------------------------------------------
499 #-------------------------------------------------------------------------
499
500
500 def save_sys_module_state(self):
501 def save_sys_module_state(self):
501 """Save the state of hooks in the sys module.
502 """Save the state of hooks in the sys module.
502
503
503 This has to be called after self.user_ns is created.
504 This has to be called after self.user_ns is created.
504 """
505 """
505 self._orig_sys_module_state = {}
506 self._orig_sys_module_state = {}
506 self._orig_sys_module_state['stdin'] = sys.stdin
507 self._orig_sys_module_state['stdin'] = sys.stdin
507 self._orig_sys_module_state['stdout'] = sys.stdout
508 self._orig_sys_module_state['stdout'] = sys.stdout
508 self._orig_sys_module_state['stderr'] = sys.stderr
509 self._orig_sys_module_state['stderr'] = sys.stderr
509 self._orig_sys_module_state['excepthook'] = sys.excepthook
510 self._orig_sys_module_state['excepthook'] = sys.excepthook
510 try:
511 try:
511 self._orig_sys_modules_main_name = self.user_ns['__name__']
512 self._orig_sys_modules_main_name = self.user_ns['__name__']
512 except KeyError:
513 except KeyError:
513 pass
514 pass
514
515
515 def restore_sys_module_state(self):
516 def restore_sys_module_state(self):
516 """Restore the state of the sys module."""
517 """Restore the state of the sys module."""
517 try:
518 try:
518 for k, v in self._orig_sys_module_state.items():
519 for k, v in self._orig_sys_module_state.items():
519 setattr(sys, k, v)
520 setattr(sys, k, v)
520 except AttributeError:
521 except AttributeError:
521 pass
522 pass
522 # Reset what what done in self.init_sys_modules
523 # Reset what what done in self.init_sys_modules
523 try:
524 try:
524 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
525 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
525 except (AttributeError, KeyError):
526 except (AttributeError, KeyError):
526 pass
527 pass
527
528
528 #-------------------------------------------------------------------------
529 #-------------------------------------------------------------------------
529 # Things related to hooks
530 # Things related to hooks
530 #-------------------------------------------------------------------------
531 #-------------------------------------------------------------------------
531
532
532 def init_hooks(self):
533 def init_hooks(self):
533 # hooks holds pointers used for user-side customizations
534 # hooks holds pointers used for user-side customizations
534 self.hooks = Struct()
535 self.hooks = Struct()
535
536
536 self.strdispatchers = {}
537 self.strdispatchers = {}
537
538
538 # Set all default hooks, defined in the IPython.hooks module.
539 # Set all default hooks, defined in the IPython.hooks module.
539 hooks = IPython.core.hooks
540 hooks = IPython.core.hooks
540 for hook_name in hooks.__all__:
541 for hook_name in hooks.__all__:
541 # default hooks have priority 100, i.e. low; user hooks should have
542 # default hooks have priority 100, i.e. low; user hooks should have
542 # 0-100 priority
543 # 0-100 priority
543 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
544 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
544
545
545 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
546 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
546 """set_hook(name,hook) -> sets an internal IPython hook.
547 """set_hook(name,hook) -> sets an internal IPython hook.
547
548
548 IPython exposes some of its internal API as user-modifiable hooks. By
549 IPython exposes some of its internal API as user-modifiable hooks. By
549 adding your function to one of these hooks, you can modify IPython's
550 adding your function to one of these hooks, you can modify IPython's
550 behavior to call at runtime your own routines."""
551 behavior to call at runtime your own routines."""
551
552
552 # At some point in the future, this should validate the hook before it
553 # At some point in the future, this should validate the hook before it
553 # accepts it. Probably at least check that the hook takes the number
554 # accepts it. Probably at least check that the hook takes the number
554 # of args it's supposed to.
555 # of args it's supposed to.
555
556
556 f = new.instancemethod(hook,self,self.__class__)
557 f = new.instancemethod(hook,self,self.__class__)
557
558
558 # check if the hook is for strdispatcher first
559 # check if the hook is for strdispatcher first
559 if str_key is not None:
560 if str_key is not None:
560 sdp = self.strdispatchers.get(name, StrDispatch())
561 sdp = self.strdispatchers.get(name, StrDispatch())
561 sdp.add_s(str_key, f, priority )
562 sdp.add_s(str_key, f, priority )
562 self.strdispatchers[name] = sdp
563 self.strdispatchers[name] = sdp
563 return
564 return
564 if re_key is not None:
565 if re_key is not None:
565 sdp = self.strdispatchers.get(name, StrDispatch())
566 sdp = self.strdispatchers.get(name, StrDispatch())
566 sdp.add_re(re.compile(re_key), f, priority )
567 sdp.add_re(re.compile(re_key), f, priority )
567 self.strdispatchers[name] = sdp
568 self.strdispatchers[name] = sdp
568 return
569 return
569
570
570 dp = getattr(self.hooks, name, None)
571 dp = getattr(self.hooks, name, None)
571 if name not in IPython.core.hooks.__all__:
572 if name not in IPython.core.hooks.__all__:
572 print "Warning! Hook '%s' is not one of %s" % \
573 print "Warning! Hook '%s' is not one of %s" % \
573 (name, IPython.core.hooks.__all__ )
574 (name, IPython.core.hooks.__all__ )
574 if not dp:
575 if not dp:
575 dp = IPython.core.hooks.CommandChainDispatcher()
576 dp = IPython.core.hooks.CommandChainDispatcher()
576
577
577 try:
578 try:
578 dp.add(f,priority)
579 dp.add(f,priority)
579 except AttributeError:
580 except AttributeError:
580 # it was not commandchain, plain old func - replace
581 # it was not commandchain, plain old func - replace
581 dp = f
582 dp = f
582
583
583 setattr(self.hooks,name, dp)
584 setattr(self.hooks,name, dp)
584
585
585 def register_post_execute(self, func):
586 def register_post_execute(self, func):
586 """Register a function for calling after code execution.
587 """Register a function for calling after code execution.
587 """
588 """
588 if not callable(func):
589 if not callable(func):
589 raise ValueError('argument %s must be callable' % func)
590 raise ValueError('argument %s must be callable' % func)
590 self._post_execute.add(func)
591 self._post_execute.add(func)
591
592
592 #-------------------------------------------------------------------------
593 #-------------------------------------------------------------------------
593 # Things related to the "main" module
594 # Things related to the "main" module
594 #-------------------------------------------------------------------------
595 #-------------------------------------------------------------------------
595
596
596 def new_main_mod(self,ns=None):
597 def new_main_mod(self,ns=None):
597 """Return a new 'main' module object for user code execution.
598 """Return a new 'main' module object for user code execution.
598 """
599 """
599 main_mod = self._user_main_module
600 main_mod = self._user_main_module
600 init_fakemod_dict(main_mod,ns)
601 init_fakemod_dict(main_mod,ns)
601 return main_mod
602 return main_mod
602
603
603 def cache_main_mod(self,ns,fname):
604 def cache_main_mod(self,ns,fname):
604 """Cache a main module's namespace.
605 """Cache a main module's namespace.
605
606
606 When scripts are executed via %run, we must keep a reference to the
607 When scripts are executed via %run, we must keep a reference to the
607 namespace of their __main__ module (a FakeModule instance) around so
608 namespace of their __main__ module (a FakeModule instance) around so
608 that Python doesn't clear it, rendering objects defined therein
609 that Python doesn't clear it, rendering objects defined therein
609 useless.
610 useless.
610
611
611 This method keeps said reference in a private dict, keyed by the
612 This method keeps said reference in a private dict, keyed by the
612 absolute path of the module object (which corresponds to the script
613 absolute path of the module object (which corresponds to the script
613 path). This way, for multiple executions of the same script we only
614 path). This way, for multiple executions of the same script we only
614 keep one copy of the namespace (the last one), thus preventing memory
615 keep one copy of the namespace (the last one), thus preventing memory
615 leaks from old references while allowing the objects from the last
616 leaks from old references while allowing the objects from the last
616 execution to be accessible.
617 execution to be accessible.
617
618
618 Note: we can not allow the actual FakeModule instances to be deleted,
619 Note: we can not allow the actual FakeModule instances to be deleted,
619 because of how Python tears down modules (it hard-sets all their
620 because of how Python tears down modules (it hard-sets all their
620 references to None without regard for reference counts). This method
621 references to None without regard for reference counts). This method
621 must therefore make a *copy* of the given namespace, to allow the
622 must therefore make a *copy* of the given namespace, to allow the
622 original module's __dict__ to be cleared and reused.
623 original module's __dict__ to be cleared and reused.
623
624
624
625
625 Parameters
626 Parameters
626 ----------
627 ----------
627 ns : a namespace (a dict, typically)
628 ns : a namespace (a dict, typically)
628
629
629 fname : str
630 fname : str
630 Filename associated with the namespace.
631 Filename associated with the namespace.
631
632
632 Examples
633 Examples
633 --------
634 --------
634
635
635 In [10]: import IPython
636 In [10]: import IPython
636
637
637 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
638 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
638
639
639 In [12]: IPython.__file__ in _ip._main_ns_cache
640 In [12]: IPython.__file__ in _ip._main_ns_cache
640 Out[12]: True
641 Out[12]: True
641 """
642 """
642 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
643 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
643
644
644 def clear_main_mod_cache(self):
645 def clear_main_mod_cache(self):
645 """Clear the cache of main modules.
646 """Clear the cache of main modules.
646
647
647 Mainly for use by utilities like %reset.
648 Mainly for use by utilities like %reset.
648
649
649 Examples
650 Examples
650 --------
651 --------
651
652
652 In [15]: import IPython
653 In [15]: import IPython
653
654
654 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
655 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
655
656
656 In [17]: len(_ip._main_ns_cache) > 0
657 In [17]: len(_ip._main_ns_cache) > 0
657 Out[17]: True
658 Out[17]: True
658
659
659 In [18]: _ip.clear_main_mod_cache()
660 In [18]: _ip.clear_main_mod_cache()
660
661
661 In [19]: len(_ip._main_ns_cache) == 0
662 In [19]: len(_ip._main_ns_cache) == 0
662 Out[19]: True
663 Out[19]: True
663 """
664 """
664 self._main_ns_cache.clear()
665 self._main_ns_cache.clear()
665
666
666 #-------------------------------------------------------------------------
667 #-------------------------------------------------------------------------
667 # Things related to debugging
668 # Things related to debugging
668 #-------------------------------------------------------------------------
669 #-------------------------------------------------------------------------
669
670
670 def init_pdb(self):
671 def init_pdb(self):
671 # Set calling of pdb on exceptions
672 # Set calling of pdb on exceptions
672 # self.call_pdb is a property
673 # self.call_pdb is a property
673 self.call_pdb = self.pdb
674 self.call_pdb = self.pdb
674
675
675 def _get_call_pdb(self):
676 def _get_call_pdb(self):
676 return self._call_pdb
677 return self._call_pdb
677
678
678 def _set_call_pdb(self,val):
679 def _set_call_pdb(self,val):
679
680
680 if val not in (0,1,False,True):
681 if val not in (0,1,False,True):
681 raise ValueError,'new call_pdb value must be boolean'
682 raise ValueError,'new call_pdb value must be boolean'
682
683
683 # store value in instance
684 # store value in instance
684 self._call_pdb = val
685 self._call_pdb = val
685
686
686 # notify the actual exception handlers
687 # notify the actual exception handlers
687 self.InteractiveTB.call_pdb = val
688 self.InteractiveTB.call_pdb = val
688
689
689 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
690 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
690 'Control auto-activation of pdb at exceptions')
691 'Control auto-activation of pdb at exceptions')
691
692
692 def debugger(self,force=False):
693 def debugger(self,force=False):
693 """Call the pydb/pdb debugger.
694 """Call the pydb/pdb debugger.
694
695
695 Keywords:
696 Keywords:
696
697
697 - force(False): by default, this routine checks the instance call_pdb
698 - force(False): by default, this routine checks the instance call_pdb
698 flag and does not actually invoke the debugger if the flag is false.
699 flag and does not actually invoke the debugger if the flag is false.
699 The 'force' option forces the debugger to activate even if the flag
700 The 'force' option forces the debugger to activate even if the flag
700 is false.
701 is false.
701 """
702 """
702
703
703 if not (force or self.call_pdb):
704 if not (force or self.call_pdb):
704 return
705 return
705
706
706 if not hasattr(sys,'last_traceback'):
707 if not hasattr(sys,'last_traceback'):
707 error('No traceback has been produced, nothing to debug.')
708 error('No traceback has been produced, nothing to debug.')
708 return
709 return
709
710
710 # use pydb if available
711 # use pydb if available
711 if debugger.has_pydb:
712 if debugger.has_pydb:
712 from pydb import pm
713 from pydb import pm
713 else:
714 else:
714 # fallback to our internal debugger
715 # fallback to our internal debugger
715 pm = lambda : self.InteractiveTB.debugger(force=True)
716 pm = lambda : self.InteractiveTB.debugger(force=True)
716 self.history_saving_wrapper(pm)()
717 self.history_saving_wrapper(pm)()
717
718
718 #-------------------------------------------------------------------------
719 #-------------------------------------------------------------------------
719 # Things related to IPython's various namespaces
720 # Things related to IPython's various namespaces
720 #-------------------------------------------------------------------------
721 #-------------------------------------------------------------------------
721
722
722 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
723 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
723 # Create the namespace where the user will operate. user_ns is
724 # Create the namespace where the user will operate. user_ns is
724 # normally the only one used, and it is passed to the exec calls as
725 # normally the only one used, and it is passed to the exec calls as
725 # the locals argument. But we do carry a user_global_ns namespace
726 # the locals argument. But we do carry a user_global_ns namespace
726 # given as the exec 'globals' argument, This is useful in embedding
727 # given as the exec 'globals' argument, This is useful in embedding
727 # situations where the ipython shell opens in a context where the
728 # situations where the ipython shell opens in a context where the
728 # distinction between locals and globals is meaningful. For
729 # distinction between locals and globals is meaningful. For
729 # non-embedded contexts, it is just the same object as the user_ns dict.
730 # non-embedded contexts, it is just the same object as the user_ns dict.
730
731
731 # FIXME. For some strange reason, __builtins__ is showing up at user
732 # FIXME. For some strange reason, __builtins__ is showing up at user
732 # level as a dict instead of a module. This is a manual fix, but I
733 # level as a dict instead of a module. This is a manual fix, but I
733 # should really track down where the problem is coming from. Alex
734 # should really track down where the problem is coming from. Alex
734 # Schmolck reported this problem first.
735 # Schmolck reported this problem first.
735
736
736 # A useful post by Alex Martelli on this topic:
737 # A useful post by Alex Martelli on this topic:
737 # Re: inconsistent value from __builtins__
738 # Re: inconsistent value from __builtins__
738 # Von: Alex Martelli <aleaxit@yahoo.com>
739 # Von: Alex Martelli <aleaxit@yahoo.com>
739 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
740 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
740 # Gruppen: comp.lang.python
741 # Gruppen: comp.lang.python
741
742
742 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
743 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
743 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
744 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
744 # > <type 'dict'>
745 # > <type 'dict'>
745 # > >>> print type(__builtins__)
746 # > >>> print type(__builtins__)
746 # > <type 'module'>
747 # > <type 'module'>
747 # > Is this difference in return value intentional?
748 # > Is this difference in return value intentional?
748
749
749 # Well, it's documented that '__builtins__' can be either a dictionary
750 # Well, it's documented that '__builtins__' can be either a dictionary
750 # or a module, and it's been that way for a long time. Whether it's
751 # or a module, and it's been that way for a long time. Whether it's
751 # intentional (or sensible), I don't know. In any case, the idea is
752 # intentional (or sensible), I don't know. In any case, the idea is
752 # that if you need to access the built-in namespace directly, you
753 # that if you need to access the built-in namespace directly, you
753 # should start with "import __builtin__" (note, no 's') which will
754 # should start with "import __builtin__" (note, no 's') which will
754 # definitely give you a module. Yeah, it's somewhat confusing:-(.
755 # definitely give you a module. Yeah, it's somewhat confusing:-(.
755
756
756 # These routines return properly built dicts as needed by the rest of
757 # These routines return properly built dicts as needed by the rest of
757 # the code, and can also be used by extension writers to generate
758 # the code, and can also be used by extension writers to generate
758 # properly initialized namespaces.
759 # properly initialized namespaces.
759 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
760 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
760 user_global_ns)
761 user_global_ns)
761
762
762 # Assign namespaces
763 # Assign namespaces
763 # This is the namespace where all normal user variables live
764 # This is the namespace where all normal user variables live
764 self.user_ns = user_ns
765 self.user_ns = user_ns
765 self.user_global_ns = user_global_ns
766 self.user_global_ns = user_global_ns
766
767
767 # An auxiliary namespace that checks what parts of the user_ns were
768 # An auxiliary namespace that checks what parts of the user_ns were
768 # loaded at startup, so we can list later only variables defined in
769 # loaded at startup, so we can list later only variables defined in
769 # actual interactive use. Since it is always a subset of user_ns, it
770 # actual interactive use. Since it is always a subset of user_ns, it
770 # doesn't need to be separately tracked in the ns_table.
771 # doesn't need to be separately tracked in the ns_table.
771 self.user_ns_hidden = {}
772 self.user_ns_hidden = {}
772
773
773 # A namespace to keep track of internal data structures to prevent
774 # A namespace to keep track of internal data structures to prevent
774 # them from cluttering user-visible stuff. Will be updated later
775 # them from cluttering user-visible stuff. Will be updated later
775 self.internal_ns = {}
776 self.internal_ns = {}
776
777
777 # Now that FakeModule produces a real module, we've run into a nasty
778 # Now that FakeModule produces a real module, we've run into a nasty
778 # problem: after script execution (via %run), the module where the user
779 # problem: after script execution (via %run), the module where the user
779 # code ran is deleted. Now that this object is a true module (needed
780 # code ran is deleted. Now that this object is a true module (needed
780 # so docetst and other tools work correctly), the Python module
781 # so docetst and other tools work correctly), the Python module
781 # teardown mechanism runs over it, and sets to None every variable
782 # teardown mechanism runs over it, and sets to None every variable
782 # present in that module. Top-level references to objects from the
783 # present in that module. Top-level references to objects from the
783 # script survive, because the user_ns is updated with them. However,
784 # script survive, because the user_ns is updated with them. However,
784 # calling functions defined in the script that use other things from
785 # calling functions defined in the script that use other things from
785 # the script will fail, because the function's closure had references
786 # the script will fail, because the function's closure had references
786 # to the original objects, which are now all None. So we must protect
787 # to the original objects, which are now all None. So we must protect
787 # these modules from deletion by keeping a cache.
788 # these modules from deletion by keeping a cache.
788 #
789 #
789 # To avoid keeping stale modules around (we only need the one from the
790 # To avoid keeping stale modules around (we only need the one from the
790 # last run), we use a dict keyed with the full path to the script, so
791 # last run), we use a dict keyed with the full path to the script, so
791 # only the last version of the module is held in the cache. Note,
792 # only the last version of the module is held in the cache. Note,
792 # however, that we must cache the module *namespace contents* (their
793 # however, that we must cache the module *namespace contents* (their
793 # __dict__). Because if we try to cache the actual modules, old ones
794 # __dict__). Because if we try to cache the actual modules, old ones
794 # (uncached) could be destroyed while still holding references (such as
795 # (uncached) could be destroyed while still holding references (such as
795 # those held by GUI objects that tend to be long-lived)>
796 # those held by GUI objects that tend to be long-lived)>
796 #
797 #
797 # The %reset command will flush this cache. See the cache_main_mod()
798 # The %reset command will flush this cache. See the cache_main_mod()
798 # and clear_main_mod_cache() methods for details on use.
799 # and clear_main_mod_cache() methods for details on use.
799
800
800 # This is the cache used for 'main' namespaces
801 # This is the cache used for 'main' namespaces
801 self._main_ns_cache = {}
802 self._main_ns_cache = {}
802 # And this is the single instance of FakeModule whose __dict__ we keep
803 # And this is the single instance of FakeModule whose __dict__ we keep
803 # copying and clearing for reuse on each %run
804 # copying and clearing for reuse on each %run
804 self._user_main_module = FakeModule()
805 self._user_main_module = FakeModule()
805
806
806 # A table holding all the namespaces IPython deals with, so that
807 # A table holding all the namespaces IPython deals with, so that
807 # introspection facilities can search easily.
808 # introspection facilities can search easily.
808 self.ns_table = {'user':user_ns,
809 self.ns_table = {'user':user_ns,
809 'user_global':user_global_ns,
810 'user_global':user_global_ns,
810 'internal':self.internal_ns,
811 'internal':self.internal_ns,
811 'builtin':__builtin__.__dict__
812 'builtin':__builtin__.__dict__
812 }
813 }
813
814
814 # Similarly, track all namespaces where references can be held and that
815 # Similarly, track all namespaces where references can be held and that
815 # we can safely clear (so it can NOT include builtin). This one can be
816 # we can safely clear (so it can NOT include builtin). This one can be
816 # a simple list.
817 # a simple list.
817 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
818 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
818 self.internal_ns, self._main_ns_cache ]
819 self.internal_ns, self._main_ns_cache ]
819
820
820 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
821 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
821 """Return a valid local and global user interactive namespaces.
822 """Return a valid local and global user interactive namespaces.
822
823
823 This builds a dict with the minimal information needed to operate as a
824 This builds a dict with the minimal information needed to operate as a
824 valid IPython user namespace, which you can pass to the various
825 valid IPython user namespace, which you can pass to the various
825 embedding classes in ipython. The default implementation returns the
826 embedding classes in ipython. The default implementation returns the
826 same dict for both the locals and the globals to allow functions to
827 same dict for both the locals and the globals to allow functions to
827 refer to variables in the namespace. Customized implementations can
828 refer to variables in the namespace. Customized implementations can
828 return different dicts. The locals dictionary can actually be anything
829 return different dicts. The locals dictionary can actually be anything
829 following the basic mapping protocol of a dict, but the globals dict
830 following the basic mapping protocol of a dict, but the globals dict
830 must be a true dict, not even a subclass. It is recommended that any
831 must be a true dict, not even a subclass. It is recommended that any
831 custom object for the locals namespace synchronize with the globals
832 custom object for the locals namespace synchronize with the globals
832 dict somehow.
833 dict somehow.
833
834
834 Raises TypeError if the provided globals namespace is not a true dict.
835 Raises TypeError if the provided globals namespace is not a true dict.
835
836
836 Parameters
837 Parameters
837 ----------
838 ----------
838 user_ns : dict-like, optional
839 user_ns : dict-like, optional
839 The current user namespace. The items in this namespace should
840 The current user namespace. The items in this namespace should
840 be included in the output. If None, an appropriate blank
841 be included in the output. If None, an appropriate blank
841 namespace should be created.
842 namespace should be created.
842 user_global_ns : dict, optional
843 user_global_ns : dict, optional
843 The current user global namespace. The items in this namespace
844 The current user global namespace. The items in this namespace
844 should be included in the output. If None, an appropriate
845 should be included in the output. If None, an appropriate
845 blank namespace should be created.
846 blank namespace should be created.
846
847
847 Returns
848 Returns
848 -------
849 -------
849 A pair of dictionary-like object to be used as the local namespace
850 A pair of dictionary-like object to be used as the local namespace
850 of the interpreter and a dict to be used as the global namespace.
851 of the interpreter and a dict to be used as the global namespace.
851 """
852 """
852
853
853
854
854 # We must ensure that __builtin__ (without the final 's') is always
855 # We must ensure that __builtin__ (without the final 's') is always
855 # available and pointing to the __builtin__ *module*. For more details:
856 # available and pointing to the __builtin__ *module*. For more details:
856 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
857 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
857
858
858 if user_ns is None:
859 if user_ns is None:
859 # Set __name__ to __main__ to better match the behavior of the
860 # Set __name__ to __main__ to better match the behavior of the
860 # normal interpreter.
861 # normal interpreter.
861 user_ns = {'__name__' :'__main__',
862 user_ns = {'__name__' :'__main__',
862 '__builtin__' : __builtin__,
863 '__builtin__' : __builtin__,
863 '__builtins__' : __builtin__,
864 '__builtins__' : __builtin__,
864 }
865 }
865 else:
866 else:
866 user_ns.setdefault('__name__','__main__')
867 user_ns.setdefault('__name__','__main__')
867 user_ns.setdefault('__builtin__',__builtin__)
868 user_ns.setdefault('__builtin__',__builtin__)
868 user_ns.setdefault('__builtins__',__builtin__)
869 user_ns.setdefault('__builtins__',__builtin__)
869
870
870 if user_global_ns is None:
871 if user_global_ns is None:
871 user_global_ns = user_ns
872 user_global_ns = user_ns
872 if type(user_global_ns) is not dict:
873 if type(user_global_ns) is not dict:
873 raise TypeError("user_global_ns must be a true dict; got %r"
874 raise TypeError("user_global_ns must be a true dict; got %r"
874 % type(user_global_ns))
875 % type(user_global_ns))
875
876
876 return user_ns, user_global_ns
877 return user_ns, user_global_ns
877
878
878 def init_sys_modules(self):
879 def init_sys_modules(self):
879 # We need to insert into sys.modules something that looks like a
880 # We need to insert into sys.modules something that looks like a
880 # module but which accesses the IPython namespace, for shelve and
881 # module but which accesses the IPython namespace, for shelve and
881 # pickle to work interactively. Normally they rely on getting
882 # pickle to work interactively. Normally they rely on getting
882 # everything out of __main__, but for embedding purposes each IPython
883 # everything out of __main__, but for embedding purposes each IPython
883 # instance has its own private namespace, so we can't go shoving
884 # instance has its own private namespace, so we can't go shoving
884 # everything into __main__.
885 # everything into __main__.
885
886
886 # note, however, that we should only do this for non-embedded
887 # note, however, that we should only do this for non-embedded
887 # ipythons, which really mimic the __main__.__dict__ with their own
888 # ipythons, which really mimic the __main__.__dict__ with their own
888 # namespace. Embedded instances, on the other hand, should not do
889 # namespace. Embedded instances, on the other hand, should not do
889 # this because they need to manage the user local/global namespaces
890 # this because they need to manage the user local/global namespaces
890 # only, but they live within a 'normal' __main__ (meaning, they
891 # only, but they live within a 'normal' __main__ (meaning, they
891 # shouldn't overtake the execution environment of the script they're
892 # shouldn't overtake the execution environment of the script they're
892 # embedded in).
893 # embedded in).
893
894
894 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
895 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
895
896
896 try:
897 try:
897 main_name = self.user_ns['__name__']
898 main_name = self.user_ns['__name__']
898 except KeyError:
899 except KeyError:
899 raise KeyError('user_ns dictionary MUST have a "__name__" key')
900 raise KeyError('user_ns dictionary MUST have a "__name__" key')
900 else:
901 else:
901 sys.modules[main_name] = FakeModule(self.user_ns)
902 sys.modules[main_name] = FakeModule(self.user_ns)
902
903
903 def init_user_ns(self):
904 def init_user_ns(self):
904 """Initialize all user-visible namespaces to their minimum defaults.
905 """Initialize all user-visible namespaces to their minimum defaults.
905
906
906 Certain history lists are also initialized here, as they effectively
907 Certain history lists are also initialized here, as they effectively
907 act as user namespaces.
908 act as user namespaces.
908
909
909 Notes
910 Notes
910 -----
911 -----
911 All data structures here are only filled in, they are NOT reset by this
912 All data structures here are only filled in, they are NOT reset by this
912 method. If they were not empty before, data will simply be added to
913 method. If they were not empty before, data will simply be added to
913 therm.
914 therm.
914 """
915 """
915 # This function works in two parts: first we put a few things in
916 # This function works in two parts: first we put a few things in
916 # user_ns, and we sync that contents into user_ns_hidden so that these
917 # user_ns, and we sync that contents into user_ns_hidden so that these
917 # initial variables aren't shown by %who. After the sync, we add the
918 # initial variables aren't shown by %who. After the sync, we add the
918 # rest of what we *do* want the user to see with %who even on a new
919 # rest of what we *do* want the user to see with %who even on a new
919 # session (probably nothing, so theye really only see their own stuff)
920 # session (probably nothing, so theye really only see their own stuff)
920
921
921 # The user dict must *always* have a __builtin__ reference to the
922 # The user dict must *always* have a __builtin__ reference to the
922 # Python standard __builtin__ namespace, which must be imported.
923 # Python standard __builtin__ namespace, which must be imported.
923 # This is so that certain operations in prompt evaluation can be
924 # This is so that certain operations in prompt evaluation can be
924 # reliably executed with builtins. Note that we can NOT use
925 # reliably executed with builtins. Note that we can NOT use
925 # __builtins__ (note the 's'), because that can either be a dict or a
926 # __builtins__ (note the 's'), because that can either be a dict or a
926 # module, and can even mutate at runtime, depending on the context
927 # module, and can even mutate at runtime, depending on the context
927 # (Python makes no guarantees on it). In contrast, __builtin__ is
928 # (Python makes no guarantees on it). In contrast, __builtin__ is
928 # always a module object, though it must be explicitly imported.
929 # always a module object, though it must be explicitly imported.
929
930
930 # For more details:
931 # For more details:
931 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
932 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
932 ns = dict(__builtin__ = __builtin__)
933 ns = dict(__builtin__ = __builtin__)
933
934
934 # Put 'help' in the user namespace
935 # Put 'help' in the user namespace
935 try:
936 try:
936 from site import _Helper
937 from site import _Helper
937 ns['help'] = _Helper()
938 ns['help'] = _Helper()
938 except ImportError:
939 except ImportError:
939 warn('help() not available - check site.py')
940 warn('help() not available - check site.py')
940
941
941 # make global variables for user access to the histories
942 # make global variables for user access to the histories
942 ns['_ih'] = self.input_hist
943 ns['_ih'] = self.input_hist
943 ns['_oh'] = self.output_hist
944 ns['_oh'] = self.output_hist
944 ns['_dh'] = self.dir_hist
945 ns['_dh'] = self.dir_hist
945
946
946 ns['_sh'] = shadowns
947 ns['_sh'] = shadowns
947
948
948 # user aliases to input and output histories. These shouldn't show up
949 # user aliases to input and output histories. These shouldn't show up
949 # in %who, as they can have very large reprs.
950 # in %who, as they can have very large reprs.
950 ns['In'] = self.input_hist
951 ns['In'] = self.input_hist
951 ns['Out'] = self.output_hist
952 ns['Out'] = self.output_hist
952
953
953 # Store myself as the public api!!!
954 # Store myself as the public api!!!
954 ns['get_ipython'] = self.get_ipython
955 ns['get_ipython'] = self.get_ipython
955
956
956 # Sync what we've added so far to user_ns_hidden so these aren't seen
957 # Sync what we've added so far to user_ns_hidden so these aren't seen
957 # by %who
958 # by %who
958 self.user_ns_hidden.update(ns)
959 self.user_ns_hidden.update(ns)
959
960
960 # Anything put into ns now would show up in %who. Think twice before
961 # Anything put into ns now would show up in %who. Think twice before
961 # putting anything here, as we really want %who to show the user their
962 # putting anything here, as we really want %who to show the user their
962 # stuff, not our variables.
963 # stuff, not our variables.
963
964
964 # Finally, update the real user's namespace
965 # Finally, update the real user's namespace
965 self.user_ns.update(ns)
966 self.user_ns.update(ns)
966
967
967
968
968 def reset(self):
969 def reset(self):
969 """Clear all internal namespaces.
970 """Clear all internal namespaces.
970
971
971 Note that this is much more aggressive than %reset, since it clears
972 Note that this is much more aggressive than %reset, since it clears
972 fully all namespaces, as well as all input/output lists.
973 fully all namespaces, as well as all input/output lists.
973 """
974 """
974 for ns in self.ns_refs_table:
975 for ns in self.ns_refs_table:
975 ns.clear()
976 ns.clear()
976
977
977 self.alias_manager.clear_aliases()
978 self.alias_manager.clear_aliases()
978
979
979 # Clear input and output histories
980 # Clear input and output histories
980 self.input_hist[:] = []
981 self.input_hist[:] = []
981 self.input_hist_raw[:] = []
982 self.input_hist_raw[:] = []
982 self.output_hist.clear()
983 self.output_hist.clear()
983
984
984 # Reset counter used to index all histories
985 # Reset counter used to index all histories
985 self.execution_count = 0
986 self.execution_count = 0
986
987
987 # Restore the user namespaces to minimal usability
988 # Restore the user namespaces to minimal usability
988 self.init_user_ns()
989 self.init_user_ns()
989
990
990 # Restore the default and user aliases
991 # Restore the default and user aliases
991 self.alias_manager.init_aliases()
992 self.alias_manager.init_aliases()
992
993
993 def reset_selective(self, regex=None):
994 def reset_selective(self, regex=None):
994 """Clear selective variables from internal namespaces based on a
995 """Clear selective variables from internal namespaces based on a
995 specified regular expression.
996 specified regular expression.
996
997
997 Parameters
998 Parameters
998 ----------
999 ----------
999 regex : string or compiled pattern, optional
1000 regex : string or compiled pattern, optional
1000 A regular expression pattern that will be used in searching
1001 A regular expression pattern that will be used in searching
1001 variable names in the users namespaces.
1002 variable names in the users namespaces.
1002 """
1003 """
1003 if regex is not None:
1004 if regex is not None:
1004 try:
1005 try:
1005 m = re.compile(regex)
1006 m = re.compile(regex)
1006 except TypeError:
1007 except TypeError:
1007 raise TypeError('regex must be a string or compiled pattern')
1008 raise TypeError('regex must be a string or compiled pattern')
1008 # Search for keys in each namespace that match the given regex
1009 # Search for keys in each namespace that match the given regex
1009 # If a match is found, delete the key/value pair.
1010 # If a match is found, delete the key/value pair.
1010 for ns in self.ns_refs_table:
1011 for ns in self.ns_refs_table:
1011 for var in ns:
1012 for var in ns:
1012 if m.search(var):
1013 if m.search(var):
1013 del ns[var]
1014 del ns[var]
1014
1015
1015 def push(self, variables, interactive=True):
1016 def push(self, variables, interactive=True):
1016 """Inject a group of variables into the IPython user namespace.
1017 """Inject a group of variables into the IPython user namespace.
1017
1018
1018 Parameters
1019 Parameters
1019 ----------
1020 ----------
1020 variables : dict, str or list/tuple of str
1021 variables : dict, str or list/tuple of str
1021 The variables to inject into the user's namespace. If a dict, a
1022 The variables to inject into the user's namespace. If a dict, a
1022 simple update is done. If a str, the string is assumed to have
1023 simple update is done. If a str, the string is assumed to have
1023 variable names separated by spaces. A list/tuple of str can also
1024 variable names separated by spaces. A list/tuple of str can also
1024 be used to give the variable names. If just the variable names are
1025 be used to give the variable names. If just the variable names are
1025 give (list/tuple/str) then the variable values looked up in the
1026 give (list/tuple/str) then the variable values looked up in the
1026 callers frame.
1027 callers frame.
1027 interactive : bool
1028 interactive : bool
1028 If True (default), the variables will be listed with the ``who``
1029 If True (default), the variables will be listed with the ``who``
1029 magic.
1030 magic.
1030 """
1031 """
1031 vdict = None
1032 vdict = None
1032
1033
1033 # We need a dict of name/value pairs to do namespace updates.
1034 # We need a dict of name/value pairs to do namespace updates.
1034 if isinstance(variables, dict):
1035 if isinstance(variables, dict):
1035 vdict = variables
1036 vdict = variables
1036 elif isinstance(variables, (basestring, list, tuple)):
1037 elif isinstance(variables, (basestring, list, tuple)):
1037 if isinstance(variables, basestring):
1038 if isinstance(variables, basestring):
1038 vlist = variables.split()
1039 vlist = variables.split()
1039 else:
1040 else:
1040 vlist = variables
1041 vlist = variables
1041 vdict = {}
1042 vdict = {}
1042 cf = sys._getframe(1)
1043 cf = sys._getframe(1)
1043 for name in vlist:
1044 for name in vlist:
1044 try:
1045 try:
1045 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1046 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1046 except:
1047 except:
1047 print ('Could not get variable %s from %s' %
1048 print ('Could not get variable %s from %s' %
1048 (name,cf.f_code.co_name))
1049 (name,cf.f_code.co_name))
1049 else:
1050 else:
1050 raise ValueError('variables must be a dict/str/list/tuple')
1051 raise ValueError('variables must be a dict/str/list/tuple')
1051
1052
1052 # Propagate variables to user namespace
1053 # Propagate variables to user namespace
1053 self.user_ns.update(vdict)
1054 self.user_ns.update(vdict)
1054
1055
1055 # And configure interactive visibility
1056 # And configure interactive visibility
1056 config_ns = self.user_ns_hidden
1057 config_ns = self.user_ns_hidden
1057 if interactive:
1058 if interactive:
1058 for name, val in vdict.iteritems():
1059 for name, val in vdict.iteritems():
1059 config_ns.pop(name, None)
1060 config_ns.pop(name, None)
1060 else:
1061 else:
1061 for name,val in vdict.iteritems():
1062 for name,val in vdict.iteritems():
1062 config_ns[name] = val
1063 config_ns[name] = val
1063
1064
1064 #-------------------------------------------------------------------------
1065 #-------------------------------------------------------------------------
1065 # Things related to object introspection
1066 # Things related to object introspection
1066 #-------------------------------------------------------------------------
1067 #-------------------------------------------------------------------------
1067
1068
1068 def _ofind(self, oname, namespaces=None):
1069 def _ofind(self, oname, namespaces=None):
1069 """Find an object in the available namespaces.
1070 """Find an object in the available namespaces.
1070
1071
1071 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1072 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1072
1073
1073 Has special code to detect magic functions.
1074 Has special code to detect magic functions.
1074 """
1075 """
1075 #oname = oname.strip()
1076 #oname = oname.strip()
1076 #print '1- oname: <%r>' % oname # dbg
1077 #print '1- oname: <%r>' % oname # dbg
1077 try:
1078 try:
1078 oname = oname.strip().encode('ascii')
1079 oname = oname.strip().encode('ascii')
1079 #print '2- oname: <%r>' % oname # dbg
1080 #print '2- oname: <%r>' % oname # dbg
1080 except UnicodeEncodeError:
1081 except UnicodeEncodeError:
1081 print 'Python identifiers can only contain ascii characters.'
1082 print 'Python identifiers can only contain ascii characters.'
1082 return dict(found=False)
1083 return dict(found=False)
1083
1084
1084 alias_ns = None
1085 alias_ns = None
1085 if namespaces is None:
1086 if namespaces is None:
1086 # Namespaces to search in:
1087 # Namespaces to search in:
1087 # Put them in a list. The order is important so that we
1088 # Put them in a list. The order is important so that we
1088 # find things in the same order that Python finds them.
1089 # find things in the same order that Python finds them.
1089 namespaces = [ ('Interactive', self.user_ns),
1090 namespaces = [ ('Interactive', self.user_ns),
1090 ('IPython internal', self.internal_ns),
1091 ('IPython internal', self.internal_ns),
1091 ('Python builtin', __builtin__.__dict__),
1092 ('Python builtin', __builtin__.__dict__),
1092 ('Alias', self.alias_manager.alias_table),
1093 ('Alias', self.alias_manager.alias_table),
1093 ]
1094 ]
1094 alias_ns = self.alias_manager.alias_table
1095 alias_ns = self.alias_manager.alias_table
1095
1096
1096 # initialize results to 'null'
1097 # initialize results to 'null'
1097 found = False; obj = None; ospace = None; ds = None;
1098 found = False; obj = None; ospace = None; ds = None;
1098 ismagic = False; isalias = False; parent = None
1099 ismagic = False; isalias = False; parent = None
1099
1100
1100 # We need to special-case 'print', which as of python2.6 registers as a
1101 # We need to special-case 'print', which as of python2.6 registers as a
1101 # function but should only be treated as one if print_function was
1102 # function but should only be treated as one if print_function was
1102 # loaded with a future import. In this case, just bail.
1103 # loaded with a future import. In this case, just bail.
1103 if (oname == 'print' and not (self.compile.compiler.flags &
1104 if (oname == 'print' and not (self.compile.compiler.flags &
1104 __future__.CO_FUTURE_PRINT_FUNCTION)):
1105 __future__.CO_FUTURE_PRINT_FUNCTION)):
1105 return {'found':found, 'obj':obj, 'namespace':ospace,
1106 return {'found':found, 'obj':obj, 'namespace':ospace,
1106 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1107 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1107
1108
1108 # Look for the given name by splitting it in parts. If the head is
1109 # Look for the given name by splitting it in parts. If the head is
1109 # found, then we look for all the remaining parts as members, and only
1110 # found, then we look for all the remaining parts as members, and only
1110 # declare success if we can find them all.
1111 # declare success if we can find them all.
1111 oname_parts = oname.split('.')
1112 oname_parts = oname.split('.')
1112 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1113 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1113 for nsname,ns in namespaces:
1114 for nsname,ns in namespaces:
1114 try:
1115 try:
1115 obj = ns[oname_head]
1116 obj = ns[oname_head]
1116 except KeyError:
1117 except KeyError:
1117 continue
1118 continue
1118 else:
1119 else:
1119 #print 'oname_rest:', oname_rest # dbg
1120 #print 'oname_rest:', oname_rest # dbg
1120 for part in oname_rest:
1121 for part in oname_rest:
1121 try:
1122 try:
1122 parent = obj
1123 parent = obj
1123 obj = getattr(obj,part)
1124 obj = getattr(obj,part)
1124 except:
1125 except:
1125 # Blanket except b/c some badly implemented objects
1126 # Blanket except b/c some badly implemented objects
1126 # allow __getattr__ to raise exceptions other than
1127 # allow __getattr__ to raise exceptions other than
1127 # AttributeError, which then crashes IPython.
1128 # AttributeError, which then crashes IPython.
1128 break
1129 break
1129 else:
1130 else:
1130 # If we finish the for loop (no break), we got all members
1131 # If we finish the for loop (no break), we got all members
1131 found = True
1132 found = True
1132 ospace = nsname
1133 ospace = nsname
1133 if ns == alias_ns:
1134 if ns == alias_ns:
1134 isalias = True
1135 isalias = True
1135 break # namespace loop
1136 break # namespace loop
1136
1137
1137 # Try to see if it's magic
1138 # Try to see if it's magic
1138 if not found:
1139 if not found:
1139 if oname.startswith(ESC_MAGIC):
1140 if oname.startswith(ESC_MAGIC):
1140 oname = oname[1:]
1141 oname = oname[1:]
1141 obj = getattr(self,'magic_'+oname,None)
1142 obj = getattr(self,'magic_'+oname,None)
1142 if obj is not None:
1143 if obj is not None:
1143 found = True
1144 found = True
1144 ospace = 'IPython internal'
1145 ospace = 'IPython internal'
1145 ismagic = True
1146 ismagic = True
1146
1147
1147 # Last try: special-case some literals like '', [], {}, etc:
1148 # Last try: special-case some literals like '', [], {}, etc:
1148 if not found and oname_head in ["''",'""','[]','{}','()']:
1149 if not found and oname_head in ["''",'""','[]','{}','()']:
1149 obj = eval(oname_head)
1150 obj = eval(oname_head)
1150 found = True
1151 found = True
1151 ospace = 'Interactive'
1152 ospace = 'Interactive'
1152
1153
1153 return {'found':found, 'obj':obj, 'namespace':ospace,
1154 return {'found':found, 'obj':obj, 'namespace':ospace,
1154 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1155 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1155
1156
1156 def _ofind_property(self, oname, info):
1157 def _ofind_property(self, oname, info):
1157 """Second part of object finding, to look for property details."""
1158 """Second part of object finding, to look for property details."""
1158 if info.found:
1159 if info.found:
1159 # Get the docstring of the class property if it exists.
1160 # Get the docstring of the class property if it exists.
1160 path = oname.split('.')
1161 path = oname.split('.')
1161 root = '.'.join(path[:-1])
1162 root = '.'.join(path[:-1])
1162 if info.parent is not None:
1163 if info.parent is not None:
1163 try:
1164 try:
1164 target = getattr(info.parent, '__class__')
1165 target = getattr(info.parent, '__class__')
1165 # The object belongs to a class instance.
1166 # The object belongs to a class instance.
1166 try:
1167 try:
1167 target = getattr(target, path[-1])
1168 target = getattr(target, path[-1])
1168 # The class defines the object.
1169 # The class defines the object.
1169 if isinstance(target, property):
1170 if isinstance(target, property):
1170 oname = root + '.__class__.' + path[-1]
1171 oname = root + '.__class__.' + path[-1]
1171 info = Struct(self._ofind(oname))
1172 info = Struct(self._ofind(oname))
1172 except AttributeError: pass
1173 except AttributeError: pass
1173 except AttributeError: pass
1174 except AttributeError: pass
1174
1175
1175 # We return either the new info or the unmodified input if the object
1176 # We return either the new info or the unmodified input if the object
1176 # hadn't been found
1177 # hadn't been found
1177 return info
1178 return info
1178
1179
1179 def _object_find(self, oname, namespaces=None):
1180 def _object_find(self, oname, namespaces=None):
1180 """Find an object and return a struct with info about it."""
1181 """Find an object and return a struct with info about it."""
1181 inf = Struct(self._ofind(oname, namespaces))
1182 inf = Struct(self._ofind(oname, namespaces))
1182 return Struct(self._ofind_property(oname, inf))
1183 return Struct(self._ofind_property(oname, inf))
1183
1184
1184 def _inspect(self, meth, oname, namespaces=None, **kw):
1185 def _inspect(self, meth, oname, namespaces=None, **kw):
1185 """Generic interface to the inspector system.
1186 """Generic interface to the inspector system.
1186
1187
1187 This function is meant to be called by pdef, pdoc & friends."""
1188 This function is meant to be called by pdef, pdoc & friends."""
1188 info = self._object_find(oname)
1189 info = self._object_find(oname)
1189 if info.found:
1190 if info.found:
1190 pmethod = getattr(self.inspector, meth)
1191 pmethod = getattr(self.inspector, meth)
1191 formatter = format_screen if info.ismagic else None
1192 formatter = format_screen if info.ismagic else None
1192 if meth == 'pdoc':
1193 if meth == 'pdoc':
1193 pmethod(info.obj, oname, formatter)
1194 pmethod(info.obj, oname, formatter)
1194 elif meth == 'pinfo':
1195 elif meth == 'pinfo':
1195 pmethod(info.obj, oname, formatter, info, **kw)
1196 pmethod(info.obj, oname, formatter, info, **kw)
1196 else:
1197 else:
1197 pmethod(info.obj, oname)
1198 pmethod(info.obj, oname)
1198 else:
1199 else:
1199 print 'Object `%s` not found.' % oname
1200 print 'Object `%s` not found.' % oname
1200 return 'not found' # so callers can take other action
1201 return 'not found' # so callers can take other action
1201
1202
1202 def object_inspect(self, oname):
1203 def object_inspect(self, oname):
1203 info = self._object_find(oname)
1204 info = self._object_find(oname)
1204 if info.found:
1205 if info.found:
1205 return self.inspector.info(info.obj, oname, info=info)
1206 return self.inspector.info(info.obj, oname, info=info)
1206 else:
1207 else:
1207 return oinspect.object_info(name=oname, found=False)
1208 return oinspect.object_info(name=oname, found=False)
1208
1209
1209 #-------------------------------------------------------------------------
1210 #-------------------------------------------------------------------------
1210 # Things related to history management
1211 # Things related to history management
1211 #-------------------------------------------------------------------------
1212 #-------------------------------------------------------------------------
1212
1213
1213 def init_history(self):
1214 def init_history(self):
1214 # List of input with multi-line handling.
1215 self.history_manager = HistoryManager(shell=self)
1215 self.input_hist = InputList()
1216 # This one will hold the 'raw' input history, without any
1217 # pre-processing. This will allow users to retrieve the input just as
1218 # it was exactly typed in by the user, with %hist -r.
1219 self.input_hist_raw = InputList()
1220
1221 # list of visited directories
1222 try:
1223 self.dir_hist = [os.getcwd()]
1224 except OSError:
1225 self.dir_hist = []
1226
1227 # dict of output history
1228 self.output_hist = {}
1229
1230 # Now the history file
1231 if self.profile:
1232 histfname = 'history-%s' % self.profile
1233 else:
1234 histfname = 'history'
1235 self.histfile = os.path.join(self.ipython_dir, histfname)
1236
1237 # Fill the history zero entry, user counter starts at 1
1238 self.input_hist.append('\n')
1239 self.input_hist_raw.append('\n')
1240
1241 def init_shadow_hist(self):
1242 try:
1243 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1244 except exceptions.UnicodeDecodeError:
1245 print "Your ipython_dir can't be decoded to unicode!"
1246 print "Please set HOME environment variable to something that"
1247 print r"only has ASCII characters, e.g. c:\home"
1248 print "Now it is", self.ipython_dir
1249 sys.exit()
1250 self.shadowhist = ipcorehist.ShadowHist(self.db)
1251
1216
1252 def savehist(self):
1217 def savehist(self):
1253 """Save input history to a file (via readline library)."""
1218 """Save input history to a file (via readline library)."""
1254
1219 self.history_manager.save_hist()
1255 try:
1220
1256 self.readline.write_history_file(self.histfile)
1257 except:
1258 print 'Unable to save IPython command history to file: ' + \
1259 `self.histfile`
1260
1261 def reloadhist(self):
1221 def reloadhist(self):
1262 """Reload the input history from disk file."""
1222 """Reload the input history from disk file."""
1263
1223 self.history_manager.reload_hist()
1264 try:
1265 self.readline.clear_history()
1266 self.readline.read_history_file(self.shell.histfile)
1267 except AttributeError:
1268 pass
1269
1224
1270 def history_saving_wrapper(self, func):
1225 def history_saving_wrapper(self, func):
1271 """ Wrap func for readline history saving
1226 """ Wrap func for readline history saving
1272
1227
1273 Convert func into callable that saves & restores
1228 Convert func into callable that saves & restores
1274 history around the call """
1229 history around the call """
1275
1230
1276 if self.has_readline:
1231 if self.has_readline:
1277 from IPython.utils import rlineimpl as readline
1232 from IPython.utils import rlineimpl as readline
1278 else:
1233 else:
1279 return func
1234 return func
1280
1235
1281 def wrapper():
1236 def wrapper():
1282 self.savehist()
1237 self.savehist()
1283 try:
1238 try:
1284 func()
1239 func()
1285 finally:
1240 finally:
1286 readline.read_history_file(self.histfile)
1241 readline.read_history_file(self.histfile)
1287 return wrapper
1242 return wrapper
1288
1243
1289 def get_history(self, index=None, raw=False, output=True):
1290 """Get the history list.
1291
1292 Get the input and output history.
1293
1294 Parameters
1295 ----------
1296 index : n or (n1, n2) or None
1297 If n, then the last entries. If a tuple, then all in
1298 range(n1, n2). If None, then all entries. Raises IndexError if
1299 the format of index is incorrect.
1300 raw : bool
1301 If True, return the raw input.
1302 output : bool
1303 If True, then return the output as well.
1304
1305 Returns
1306 -------
1307 If output is True, then return a dict of tuples, keyed by the prompt
1308 numbers and with values of (input, output). If output is False, then
1309 a dict, keyed by the prompt number with the values of input. Raises
1310 IndexError if no history is found.
1311 """
1312 if raw:
1313 input_hist = self.input_hist_raw
1314 else:
1315 input_hist = self.input_hist
1316 if output:
1317 output_hist = self.user_ns['Out']
1318 n = len(input_hist)
1319 if index is None:
1320 start=0; stop=n
1321 elif isinstance(index, int):
1322 start=n-index; stop=n
1323 elif isinstance(index, tuple) and len(index) == 2:
1324 start=index[0]; stop=index[1]
1325 else:
1326 raise IndexError('Not a valid index for the input history: %r'
1327 % index)
1328 hist = {}
1329 for i in range(start, stop):
1330 if output:
1331 hist[i] = (input_hist[i], output_hist.get(i))
1332 else:
1333 hist[i] = input_hist[i]
1334 if len(hist)==0:
1335 raise IndexError('No history for range of indices: %r' % index)
1336 return hist
1337
1338 #-------------------------------------------------------------------------
1244 #-------------------------------------------------------------------------
1339 # Things related to exception handling and tracebacks (not debugging)
1245 # Things related to exception handling and tracebacks (not debugging)
1340 #-------------------------------------------------------------------------
1246 #-------------------------------------------------------------------------
1341
1247
1342 def init_traceback_handlers(self, custom_exceptions):
1248 def init_traceback_handlers(self, custom_exceptions):
1343 # Syntax error handler.
1249 # Syntax error handler.
1344 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1250 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1345
1251
1346 # The interactive one is initialized with an offset, meaning we always
1252 # The interactive one is initialized with an offset, meaning we always
1347 # want to remove the topmost item in the traceback, which is our own
1253 # want to remove the topmost item in the traceback, which is our own
1348 # internal code. Valid modes: ['Plain','Context','Verbose']
1254 # internal code. Valid modes: ['Plain','Context','Verbose']
1349 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1255 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1350 color_scheme='NoColor',
1256 color_scheme='NoColor',
1351 tb_offset = 1)
1257 tb_offset = 1)
1352
1258
1353 # The instance will store a pointer to the system-wide exception hook,
1259 # The instance will store a pointer to the system-wide exception hook,
1354 # so that runtime code (such as magics) can access it. This is because
1260 # so that runtime code (such as magics) can access it. This is because
1355 # during the read-eval loop, it may get temporarily overwritten.
1261 # during the read-eval loop, it may get temporarily overwritten.
1356 self.sys_excepthook = sys.excepthook
1262 self.sys_excepthook = sys.excepthook
1357
1263
1358 # and add any custom exception handlers the user may have specified
1264 # and add any custom exception handlers the user may have specified
1359 self.set_custom_exc(*custom_exceptions)
1265 self.set_custom_exc(*custom_exceptions)
1360
1266
1361 # Set the exception mode
1267 # Set the exception mode
1362 self.InteractiveTB.set_mode(mode=self.xmode)
1268 self.InteractiveTB.set_mode(mode=self.xmode)
1363
1269
1364 def set_custom_exc(self, exc_tuple, handler):
1270 def set_custom_exc(self, exc_tuple, handler):
1365 """set_custom_exc(exc_tuple,handler)
1271 """set_custom_exc(exc_tuple,handler)
1366
1272
1367 Set a custom exception handler, which will be called if any of the
1273 Set a custom exception handler, which will be called if any of the
1368 exceptions in exc_tuple occur in the mainloop (specifically, in the
1274 exceptions in exc_tuple occur in the mainloop (specifically, in the
1369 runcode() method.
1275 runcode() method.
1370
1276
1371 Inputs:
1277 Inputs:
1372
1278
1373 - exc_tuple: a *tuple* of valid exceptions to call the defined
1279 - exc_tuple: a *tuple* of valid exceptions to call the defined
1374 handler for. It is very important that you use a tuple, and NOT A
1280 handler for. It is very important that you use a tuple, and NOT A
1375 LIST here, because of the way Python's except statement works. If
1281 LIST here, because of the way Python's except statement works. If
1376 you only want to trap a single exception, use a singleton tuple:
1282 you only want to trap a single exception, use a singleton tuple:
1377
1283
1378 exc_tuple == (MyCustomException,)
1284 exc_tuple == (MyCustomException,)
1379
1285
1380 - handler: this must be defined as a function with the following
1286 - handler: this must be defined as a function with the following
1381 basic interface::
1287 basic interface::
1382
1288
1383 def my_handler(self, etype, value, tb, tb_offset=None)
1289 def my_handler(self, etype, value, tb, tb_offset=None)
1384 ...
1290 ...
1385 # The return value must be
1291 # The return value must be
1386 return structured_traceback
1292 return structured_traceback
1387
1293
1388 This will be made into an instance method (via new.instancemethod)
1294 This will be made into an instance method (via new.instancemethod)
1389 of IPython itself, and it will be called if any of the exceptions
1295 of IPython itself, and it will be called if any of the exceptions
1390 listed in the exc_tuple are caught. If the handler is None, an
1296 listed in the exc_tuple are caught. If the handler is None, an
1391 internal basic one is used, which just prints basic info.
1297 internal basic one is used, which just prints basic info.
1392
1298
1393 WARNING: by putting in your own exception handler into IPython's main
1299 WARNING: by putting in your own exception handler into IPython's main
1394 execution loop, you run a very good chance of nasty crashes. This
1300 execution loop, you run a very good chance of nasty crashes. This
1395 facility should only be used if you really know what you are doing."""
1301 facility should only be used if you really know what you are doing."""
1396
1302
1397 assert type(exc_tuple)==type(()) , \
1303 assert type(exc_tuple)==type(()) , \
1398 "The custom exceptions must be given AS A TUPLE."
1304 "The custom exceptions must be given AS A TUPLE."
1399
1305
1400 def dummy_handler(self,etype,value,tb):
1306 def dummy_handler(self,etype,value,tb):
1401 print '*** Simple custom exception handler ***'
1307 print '*** Simple custom exception handler ***'
1402 print 'Exception type :',etype
1308 print 'Exception type :',etype
1403 print 'Exception value:',value
1309 print 'Exception value:',value
1404 print 'Traceback :',tb
1310 print 'Traceback :',tb
1405 print 'Source code :','\n'.join(self.buffer)
1311 print 'Source code :','\n'.join(self.buffer)
1406
1312
1407 if handler is None: handler = dummy_handler
1313 if handler is None: handler = dummy_handler
1408
1314
1409 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1315 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1410 self.custom_exceptions = exc_tuple
1316 self.custom_exceptions = exc_tuple
1411
1317
1412 def excepthook(self, etype, value, tb):
1318 def excepthook(self, etype, value, tb):
1413 """One more defense for GUI apps that call sys.excepthook.
1319 """One more defense for GUI apps that call sys.excepthook.
1414
1320
1415 GUI frameworks like wxPython trap exceptions and call
1321 GUI frameworks like wxPython trap exceptions and call
1416 sys.excepthook themselves. I guess this is a feature that
1322 sys.excepthook themselves. I guess this is a feature that
1417 enables them to keep running after exceptions that would
1323 enables them to keep running after exceptions that would
1418 otherwise kill their mainloop. This is a bother for IPython
1324 otherwise kill their mainloop. This is a bother for IPython
1419 which excepts to catch all of the program exceptions with a try:
1325 which excepts to catch all of the program exceptions with a try:
1420 except: statement.
1326 except: statement.
1421
1327
1422 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1328 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1423 any app directly invokes sys.excepthook, it will look to the user like
1329 any app directly invokes sys.excepthook, it will look to the user like
1424 IPython crashed. In order to work around this, we can disable the
1330 IPython crashed. In order to work around this, we can disable the
1425 CrashHandler and replace it with this excepthook instead, which prints a
1331 CrashHandler and replace it with this excepthook instead, which prints a
1426 regular traceback using our InteractiveTB. In this fashion, apps which
1332 regular traceback using our InteractiveTB. In this fashion, apps which
1427 call sys.excepthook will generate a regular-looking exception from
1333 call sys.excepthook will generate a regular-looking exception from
1428 IPython, and the CrashHandler will only be triggered by real IPython
1334 IPython, and the CrashHandler will only be triggered by real IPython
1429 crashes.
1335 crashes.
1430
1336
1431 This hook should be used sparingly, only in places which are not likely
1337 This hook should be used sparingly, only in places which are not likely
1432 to be true IPython errors.
1338 to be true IPython errors.
1433 """
1339 """
1434 self.showtraceback((etype,value,tb),tb_offset=0)
1340 self.showtraceback((etype,value,tb),tb_offset=0)
1435
1341
1436 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1342 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1437 exception_only=False):
1343 exception_only=False):
1438 """Display the exception that just occurred.
1344 """Display the exception that just occurred.
1439
1345
1440 If nothing is known about the exception, this is the method which
1346 If nothing is known about the exception, this is the method which
1441 should be used throughout the code for presenting user tracebacks,
1347 should be used throughout the code for presenting user tracebacks,
1442 rather than directly invoking the InteractiveTB object.
1348 rather than directly invoking the InteractiveTB object.
1443
1349
1444 A specific showsyntaxerror() also exists, but this method can take
1350 A specific showsyntaxerror() also exists, but this method can take
1445 care of calling it if needed, so unless you are explicitly catching a
1351 care of calling it if needed, so unless you are explicitly catching a
1446 SyntaxError exception, don't try to analyze the stack manually and
1352 SyntaxError exception, don't try to analyze the stack manually and
1447 simply call this method."""
1353 simply call this method."""
1448
1354
1449 try:
1355 try:
1450 if exc_tuple is None:
1356 if exc_tuple is None:
1451 etype, value, tb = sys.exc_info()
1357 etype, value, tb = sys.exc_info()
1452 else:
1358 else:
1453 etype, value, tb = exc_tuple
1359 etype, value, tb = exc_tuple
1454
1360
1455 if etype is None:
1361 if etype is None:
1456 if hasattr(sys, 'last_type'):
1362 if hasattr(sys, 'last_type'):
1457 etype, value, tb = sys.last_type, sys.last_value, \
1363 etype, value, tb = sys.last_type, sys.last_value, \
1458 sys.last_traceback
1364 sys.last_traceback
1459 else:
1365 else:
1460 self.write_err('No traceback available to show.\n')
1366 self.write_err('No traceback available to show.\n')
1461 return
1367 return
1462
1368
1463 if etype is SyntaxError:
1369 if etype is SyntaxError:
1464 # Though this won't be called by syntax errors in the input
1370 # Though this won't be called by syntax errors in the input
1465 # line, there may be SyntaxError cases whith imported code.
1371 # line, there may be SyntaxError cases whith imported code.
1466 self.showsyntaxerror(filename)
1372 self.showsyntaxerror(filename)
1467 elif etype is UsageError:
1373 elif etype is UsageError:
1468 print "UsageError:", value
1374 print "UsageError:", value
1469 else:
1375 else:
1470 # WARNING: these variables are somewhat deprecated and not
1376 # WARNING: these variables are somewhat deprecated and not
1471 # necessarily safe to use in a threaded environment, but tools
1377 # necessarily safe to use in a threaded environment, but tools
1472 # like pdb depend on their existence, so let's set them. If we
1378 # like pdb depend on their existence, so let's set them. If we
1473 # find problems in the field, we'll need to revisit their use.
1379 # find problems in the field, we'll need to revisit their use.
1474 sys.last_type = etype
1380 sys.last_type = etype
1475 sys.last_value = value
1381 sys.last_value = value
1476 sys.last_traceback = tb
1382 sys.last_traceback = tb
1477
1383
1478 if etype in self.custom_exceptions:
1384 if etype in self.custom_exceptions:
1479 # FIXME: Old custom traceback objects may just return a
1385 # FIXME: Old custom traceback objects may just return a
1480 # string, in that case we just put it into a list
1386 # string, in that case we just put it into a list
1481 stb = self.CustomTB(etype, value, tb, tb_offset)
1387 stb = self.CustomTB(etype, value, tb, tb_offset)
1482 if isinstance(ctb, basestring):
1388 if isinstance(ctb, basestring):
1483 stb = [stb]
1389 stb = [stb]
1484 else:
1390 else:
1485 if exception_only:
1391 if exception_only:
1486 stb = ['An exception has occurred, use %tb to see '
1392 stb = ['An exception has occurred, use %tb to see '
1487 'the full traceback.\n']
1393 'the full traceback.\n']
1488 stb.extend(self.InteractiveTB.get_exception_only(etype,
1394 stb.extend(self.InteractiveTB.get_exception_only(etype,
1489 value))
1395 value))
1490 else:
1396 else:
1491 stb = self.InteractiveTB.structured_traceback(etype,
1397 stb = self.InteractiveTB.structured_traceback(etype,
1492 value, tb, tb_offset=tb_offset)
1398 value, tb, tb_offset=tb_offset)
1493 # FIXME: the pdb calling should be done by us, not by
1399 # FIXME: the pdb calling should be done by us, not by
1494 # the code computing the traceback.
1400 # the code computing the traceback.
1495 if self.InteractiveTB.call_pdb:
1401 if self.InteractiveTB.call_pdb:
1496 # pdb mucks up readline, fix it back
1402 # pdb mucks up readline, fix it back
1497 self.set_readline_completer()
1403 self.set_readline_completer()
1498
1404
1499 # Actually show the traceback
1405 # Actually show the traceback
1500 self._showtraceback(etype, value, stb)
1406 self._showtraceback(etype, value, stb)
1501
1407
1502 except KeyboardInterrupt:
1408 except KeyboardInterrupt:
1503 self.write_err("\nKeyboardInterrupt\n")
1409 self.write_err("\nKeyboardInterrupt\n")
1504
1410
1505 def _showtraceback(self, etype, evalue, stb):
1411 def _showtraceback(self, etype, evalue, stb):
1506 """Actually show a traceback.
1412 """Actually show a traceback.
1507
1413
1508 Subclasses may override this method to put the traceback on a different
1414 Subclasses may override this method to put the traceback on a different
1509 place, like a side channel.
1415 place, like a side channel.
1510 """
1416 """
1511 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1417 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1512
1418
1513 def showsyntaxerror(self, filename=None):
1419 def showsyntaxerror(self, filename=None):
1514 """Display the syntax error that just occurred.
1420 """Display the syntax error that just occurred.
1515
1421
1516 This doesn't display a stack trace because there isn't one.
1422 This doesn't display a stack trace because there isn't one.
1517
1423
1518 If a filename is given, it is stuffed in the exception instead
1424 If a filename is given, it is stuffed in the exception instead
1519 of what was there before (because Python's parser always uses
1425 of what was there before (because Python's parser always uses
1520 "<string>" when reading from a string).
1426 "<string>" when reading from a string).
1521 """
1427 """
1522 etype, value, last_traceback = sys.exc_info()
1428 etype, value, last_traceback = sys.exc_info()
1523
1429
1524 # See note about these variables in showtraceback() above
1430 # See note about these variables in showtraceback() above
1525 sys.last_type = etype
1431 sys.last_type = etype
1526 sys.last_value = value
1432 sys.last_value = value
1527 sys.last_traceback = last_traceback
1433 sys.last_traceback = last_traceback
1528
1434
1529 if filename and etype is SyntaxError:
1435 if filename and etype is SyntaxError:
1530 # Work hard to stuff the correct filename in the exception
1436 # Work hard to stuff the correct filename in the exception
1531 try:
1437 try:
1532 msg, (dummy_filename, lineno, offset, line) = value
1438 msg, (dummy_filename, lineno, offset, line) = value
1533 except:
1439 except:
1534 # Not the format we expect; leave it alone
1440 # Not the format we expect; leave it alone
1535 pass
1441 pass
1536 else:
1442 else:
1537 # Stuff in the right filename
1443 # Stuff in the right filename
1538 try:
1444 try:
1539 # Assume SyntaxError is a class exception
1445 # Assume SyntaxError is a class exception
1540 value = SyntaxError(msg, (filename, lineno, offset, line))
1446 value = SyntaxError(msg, (filename, lineno, offset, line))
1541 except:
1447 except:
1542 # If that failed, assume SyntaxError is a string
1448 # If that failed, assume SyntaxError is a string
1543 value = msg, (filename, lineno, offset, line)
1449 value = msg, (filename, lineno, offset, line)
1544 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1450 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1545 self._showtraceback(etype, value, stb)
1451 self._showtraceback(etype, value, stb)
1546
1452
1547 #-------------------------------------------------------------------------
1453 #-------------------------------------------------------------------------
1548 # Things related to readline
1454 # Things related to readline
1549 #-------------------------------------------------------------------------
1455 #-------------------------------------------------------------------------
1550
1456
1551 def init_readline(self):
1457 def init_readline(self):
1552 """Command history completion/saving/reloading."""
1458 """Command history completion/saving/reloading."""
1553
1459
1554 if self.readline_use:
1460 if self.readline_use:
1555 import IPython.utils.rlineimpl as readline
1461 import IPython.utils.rlineimpl as readline
1556
1462
1557 self.rl_next_input = None
1463 self.rl_next_input = None
1558 self.rl_do_indent = False
1464 self.rl_do_indent = False
1559
1465
1560 if not self.readline_use or not readline.have_readline:
1466 if not self.readline_use or not readline.have_readline:
1561 self.has_readline = False
1467 self.has_readline = False
1562 self.readline = None
1468 self.readline = None
1563 # Set a number of methods that depend on readline to be no-op
1469 # Set a number of methods that depend on readline to be no-op
1564 self.savehist = no_op
1470 self.savehist = no_op
1565 self.reloadhist = no_op
1471 self.reloadhist = no_op
1566 self.set_readline_completer = no_op
1472 self.set_readline_completer = no_op
1567 self.set_custom_completer = no_op
1473 self.set_custom_completer = no_op
1568 self.set_completer_frame = no_op
1474 self.set_completer_frame = no_op
1569 warn('Readline services not available or not loaded.')
1475 warn('Readline services not available or not loaded.')
1570 else:
1476 else:
1571 self.has_readline = True
1477 self.has_readline = True
1572 self.readline = readline
1478 self.readline = readline
1573 sys.modules['readline'] = readline
1479 sys.modules['readline'] = readline
1574
1480
1575 # Platform-specific configuration
1481 # Platform-specific configuration
1576 if os.name == 'nt':
1482 if os.name == 'nt':
1577 # FIXME - check with Frederick to see if we can harmonize
1483 # FIXME - check with Frederick to see if we can harmonize
1578 # naming conventions with pyreadline to avoid this
1484 # naming conventions with pyreadline to avoid this
1579 # platform-dependent check
1485 # platform-dependent check
1580 self.readline_startup_hook = readline.set_pre_input_hook
1486 self.readline_startup_hook = readline.set_pre_input_hook
1581 else:
1487 else:
1582 self.readline_startup_hook = readline.set_startup_hook
1488 self.readline_startup_hook = readline.set_startup_hook
1583
1489
1584 # Load user's initrc file (readline config)
1490 # Load user's initrc file (readline config)
1585 # Or if libedit is used, load editrc.
1491 # Or if libedit is used, load editrc.
1586 inputrc_name = os.environ.get('INPUTRC')
1492 inputrc_name = os.environ.get('INPUTRC')
1587 if inputrc_name is None:
1493 if inputrc_name is None:
1588 home_dir = get_home_dir()
1494 home_dir = get_home_dir()
1589 if home_dir is not None:
1495 if home_dir is not None:
1590 inputrc_name = '.inputrc'
1496 inputrc_name = '.inputrc'
1591 if readline.uses_libedit:
1497 if readline.uses_libedit:
1592 inputrc_name = '.editrc'
1498 inputrc_name = '.editrc'
1593 inputrc_name = os.path.join(home_dir, inputrc_name)
1499 inputrc_name = os.path.join(home_dir, inputrc_name)
1594 if os.path.isfile(inputrc_name):
1500 if os.path.isfile(inputrc_name):
1595 try:
1501 try:
1596 readline.read_init_file(inputrc_name)
1502 readline.read_init_file(inputrc_name)
1597 except:
1503 except:
1598 warn('Problems reading readline initialization file <%s>'
1504 warn('Problems reading readline initialization file <%s>'
1599 % inputrc_name)
1505 % inputrc_name)
1600
1506
1601 # Configure readline according to user's prefs
1507 # Configure readline according to user's prefs
1602 # This is only done if GNU readline is being used. If libedit
1508 # This is only done if GNU readline is being used. If libedit
1603 # is being used (as on Leopard) the readline config is
1509 # is being used (as on Leopard) the readline config is
1604 # not run as the syntax for libedit is different.
1510 # not run as the syntax for libedit is different.
1605 if not readline.uses_libedit:
1511 if not readline.uses_libedit:
1606 for rlcommand in self.readline_parse_and_bind:
1512 for rlcommand in self.readline_parse_and_bind:
1607 #print "loading rl:",rlcommand # dbg
1513 #print "loading rl:",rlcommand # dbg
1608 readline.parse_and_bind(rlcommand)
1514 readline.parse_and_bind(rlcommand)
1609
1515
1610 # Remove some chars from the delimiters list. If we encounter
1516 # Remove some chars from the delimiters list. If we encounter
1611 # unicode chars, discard them.
1517 # unicode chars, discard them.
1612 delims = readline.get_completer_delims().encode("ascii", "ignore")
1518 delims = readline.get_completer_delims().encode("ascii", "ignore")
1613 delims = delims.translate(string._idmap,
1519 delims = delims.translate(string._idmap,
1614 self.readline_remove_delims)
1520 self.readline_remove_delims)
1615 delims = delims.replace(ESC_MAGIC, '')
1521 delims = delims.replace(ESC_MAGIC, '')
1616 readline.set_completer_delims(delims)
1522 readline.set_completer_delims(delims)
1617 # otherwise we end up with a monster history after a while:
1523 # otherwise we end up with a monster history after a while:
1618 readline.set_history_length(1000)
1524 readline.set_history_length(1000)
1619 try:
1525 try:
1620 #print '*** Reading readline history' # dbg
1526 #print '*** Reading readline history' # dbg
1621 readline.read_history_file(self.histfile)
1527 readline.read_history_file(self.histfile)
1622 except IOError:
1528 except IOError:
1623 pass # It doesn't exist yet.
1529 pass # It doesn't exist yet.
1624
1530
1625 # If we have readline, we want our history saved upon ipython
1531 # If we have readline, we want our history saved upon ipython
1626 # exiting.
1532 # exiting.
1627 atexit.register(self.savehist)
1533 atexit.register(self.savehist)
1628
1534
1629 # Configure auto-indent for all platforms
1535 # Configure auto-indent for all platforms
1630 self.set_autoindent(self.autoindent)
1536 self.set_autoindent(self.autoindent)
1631
1537
1632 def set_next_input(self, s):
1538 def set_next_input(self, s):
1633 """ Sets the 'default' input string for the next command line.
1539 """ Sets the 'default' input string for the next command line.
1634
1540
1635 Requires readline.
1541 Requires readline.
1636
1542
1637 Example:
1543 Example:
1638
1544
1639 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1545 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1640 [D:\ipython]|2> Hello Word_ # cursor is here
1546 [D:\ipython]|2> Hello Word_ # cursor is here
1641 """
1547 """
1642
1548
1643 self.rl_next_input = s
1549 self.rl_next_input = s
1644
1550
1645 # Maybe move this to the terminal subclass?
1551 # Maybe move this to the terminal subclass?
1646 def pre_readline(self):
1552 def pre_readline(self):
1647 """readline hook to be used at the start of each line.
1553 """readline hook to be used at the start of each line.
1648
1554
1649 Currently it handles auto-indent only."""
1555 Currently it handles auto-indent only."""
1650
1556
1651 if self.rl_do_indent:
1557 if self.rl_do_indent:
1652 self.readline.insert_text(self._indent_current_str())
1558 self.readline.insert_text(self._indent_current_str())
1653 if self.rl_next_input is not None:
1559 if self.rl_next_input is not None:
1654 self.readline.insert_text(self.rl_next_input)
1560 self.readline.insert_text(self.rl_next_input)
1655 self.rl_next_input = None
1561 self.rl_next_input = None
1656
1562
1657 def _indent_current_str(self):
1563 def _indent_current_str(self):
1658 """return the current level of indentation as a string"""
1564 """return the current level of indentation as a string"""
1659 return self.indent_current_nsp * ' '
1565 return self.indent_current_nsp * ' '
1660
1566
1661 #-------------------------------------------------------------------------
1567 #-------------------------------------------------------------------------
1662 # Things related to text completion
1568 # Things related to text completion
1663 #-------------------------------------------------------------------------
1569 #-------------------------------------------------------------------------
1664
1570
1665 def init_completer(self):
1571 def init_completer(self):
1666 """Initialize the completion machinery.
1572 """Initialize the completion machinery.
1667
1573
1668 This creates completion machinery that can be used by client code,
1574 This creates completion machinery that can be used by client code,
1669 either interactively in-process (typically triggered by the readline
1575 either interactively in-process (typically triggered by the readline
1670 library), programatically (such as in test suites) or out-of-prcess
1576 library), programatically (such as in test suites) or out-of-prcess
1671 (typically over the network by remote frontends).
1577 (typically over the network by remote frontends).
1672 """
1578 """
1673 from IPython.core.completer import IPCompleter
1579 from IPython.core.completer import IPCompleter
1674 from IPython.core.completerlib import (module_completer,
1580 from IPython.core.completerlib import (module_completer,
1675 magic_run_completer, cd_completer)
1581 magic_run_completer, cd_completer)
1676
1582
1677 self.Completer = IPCompleter(self,
1583 self.Completer = IPCompleter(self,
1678 self.user_ns,
1584 self.user_ns,
1679 self.user_global_ns,
1585 self.user_global_ns,
1680 self.readline_omit__names,
1586 self.readline_omit__names,
1681 self.alias_manager.alias_table,
1587 self.alias_manager.alias_table,
1682 self.has_readline)
1588 self.has_readline)
1683
1589
1684 # Add custom completers to the basic ones built into IPCompleter
1590 # Add custom completers to the basic ones built into IPCompleter
1685 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1591 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1686 self.strdispatchers['complete_command'] = sdisp
1592 self.strdispatchers['complete_command'] = sdisp
1687 self.Completer.custom_completers = sdisp
1593 self.Completer.custom_completers = sdisp
1688
1594
1689 self.set_hook('complete_command', module_completer, str_key = 'import')
1595 self.set_hook('complete_command', module_completer, str_key = 'import')
1690 self.set_hook('complete_command', module_completer, str_key = 'from')
1596 self.set_hook('complete_command', module_completer, str_key = 'from')
1691 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1597 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1692 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1598 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1693
1599
1694 # Only configure readline if we truly are using readline. IPython can
1600 # Only configure readline if we truly are using readline. IPython can
1695 # do tab-completion over the network, in GUIs, etc, where readline
1601 # do tab-completion over the network, in GUIs, etc, where readline
1696 # itself may be absent
1602 # itself may be absent
1697 if self.has_readline:
1603 if self.has_readline:
1698 self.set_readline_completer()
1604 self.set_readline_completer()
1699
1605
1700 def complete(self, text, line=None, cursor_pos=None):
1606 def complete(self, text, line=None, cursor_pos=None):
1701 """Return the completed text and a list of completions.
1607 """Return the completed text and a list of completions.
1702
1608
1703 Parameters
1609 Parameters
1704 ----------
1610 ----------
1705
1611
1706 text : string
1612 text : string
1707 A string of text to be completed on. It can be given as empty and
1613 A string of text to be completed on. It can be given as empty and
1708 instead a line/position pair are given. In this case, the
1614 instead a line/position pair are given. In this case, the
1709 completer itself will split the line like readline does.
1615 completer itself will split the line like readline does.
1710
1616
1711 line : string, optional
1617 line : string, optional
1712 The complete line that text is part of.
1618 The complete line that text is part of.
1713
1619
1714 cursor_pos : int, optional
1620 cursor_pos : int, optional
1715 The position of the cursor on the input line.
1621 The position of the cursor on the input line.
1716
1622
1717 Returns
1623 Returns
1718 -------
1624 -------
1719 text : string
1625 text : string
1720 The actual text that was completed.
1626 The actual text that was completed.
1721
1627
1722 matches : list
1628 matches : list
1723 A sorted list with all possible completions.
1629 A sorted list with all possible completions.
1724
1630
1725 The optional arguments allow the completion to take more context into
1631 The optional arguments allow the completion to take more context into
1726 account, and are part of the low-level completion API.
1632 account, and are part of the low-level completion API.
1727
1633
1728 This is a wrapper around the completion mechanism, similar to what
1634 This is a wrapper around the completion mechanism, similar to what
1729 readline does at the command line when the TAB key is hit. By
1635 readline does at the command line when the TAB key is hit. By
1730 exposing it as a method, it can be used by other non-readline
1636 exposing it as a method, it can be used by other non-readline
1731 environments (such as GUIs) for text completion.
1637 environments (such as GUIs) for text completion.
1732
1638
1733 Simple usage example:
1639 Simple usage example:
1734
1640
1735 In [1]: x = 'hello'
1641 In [1]: x = 'hello'
1736
1642
1737 In [2]: _ip.complete('x.l')
1643 In [2]: _ip.complete('x.l')
1738 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1644 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1739 """
1645 """
1740
1646
1741 # Inject names into __builtin__ so we can complete on the added names.
1647 # Inject names into __builtin__ so we can complete on the added names.
1742 with self.builtin_trap:
1648 with self.builtin_trap:
1743 return self.Completer.complete(text, line, cursor_pos)
1649 return self.Completer.complete(text, line, cursor_pos)
1744
1650
1745 def set_custom_completer(self, completer, pos=0):
1651 def set_custom_completer(self, completer, pos=0):
1746 """Adds a new custom completer function.
1652 """Adds a new custom completer function.
1747
1653
1748 The position argument (defaults to 0) is the index in the completers
1654 The position argument (defaults to 0) is the index in the completers
1749 list where you want the completer to be inserted."""
1655 list where you want the completer to be inserted."""
1750
1656
1751 newcomp = new.instancemethod(completer,self.Completer,
1657 newcomp = new.instancemethod(completer,self.Completer,
1752 self.Completer.__class__)
1658 self.Completer.__class__)
1753 self.Completer.matchers.insert(pos,newcomp)
1659 self.Completer.matchers.insert(pos,newcomp)
1754
1660
1755 def set_readline_completer(self):
1661 def set_readline_completer(self):
1756 """Reset readline's completer to be our own."""
1662 """Reset readline's completer to be our own."""
1757 self.readline.set_completer(self.Completer.rlcomplete)
1663 self.readline.set_completer(self.Completer.rlcomplete)
1758
1664
1759 def set_completer_frame(self, frame=None):
1665 def set_completer_frame(self, frame=None):
1760 """Set the frame of the completer."""
1666 """Set the frame of the completer."""
1761 if frame:
1667 if frame:
1762 self.Completer.namespace = frame.f_locals
1668 self.Completer.namespace = frame.f_locals
1763 self.Completer.global_namespace = frame.f_globals
1669 self.Completer.global_namespace = frame.f_globals
1764 else:
1670 else:
1765 self.Completer.namespace = self.user_ns
1671 self.Completer.namespace = self.user_ns
1766 self.Completer.global_namespace = self.user_global_ns
1672 self.Completer.global_namespace = self.user_global_ns
1767
1673
1768 #-------------------------------------------------------------------------
1674 #-------------------------------------------------------------------------
1769 # Things related to magics
1675 # Things related to magics
1770 #-------------------------------------------------------------------------
1676 #-------------------------------------------------------------------------
1771
1677
1772 def init_magics(self):
1678 def init_magics(self):
1773 # FIXME: Move the color initialization to the DisplayHook, which
1679 # FIXME: Move the color initialization to the DisplayHook, which
1774 # should be split into a prompt manager and displayhook. We probably
1680 # should be split into a prompt manager and displayhook. We probably
1775 # even need a centralize colors management object.
1681 # even need a centralize colors management object.
1776 self.magic_colors(self.colors)
1682 self.magic_colors(self.colors)
1777 # History was moved to a separate module
1683 # History was moved to a separate module
1778 from . import history
1684 from . import history
1779 history.init_ipython(self)
1685 history.init_ipython(self)
1780
1686
1781 def magic(self,arg_s):
1687 def magic(self,arg_s):
1782 """Call a magic function by name.
1688 """Call a magic function by name.
1783
1689
1784 Input: a string containing the name of the magic function to call and
1690 Input: a string containing the name of the magic function to call and
1785 any additional arguments to be passed to the magic.
1691 any additional arguments to be passed to the magic.
1786
1692
1787 magic('name -opt foo bar') is equivalent to typing at the ipython
1693 magic('name -opt foo bar') is equivalent to typing at the ipython
1788 prompt:
1694 prompt:
1789
1695
1790 In[1]: %name -opt foo bar
1696 In[1]: %name -opt foo bar
1791
1697
1792 To call a magic without arguments, simply use magic('name').
1698 To call a magic without arguments, simply use magic('name').
1793
1699
1794 This provides a proper Python function to call IPython's magics in any
1700 This provides a proper Python function to call IPython's magics in any
1795 valid Python code you can type at the interpreter, including loops and
1701 valid Python code you can type at the interpreter, including loops and
1796 compound statements.
1702 compound statements.
1797 """
1703 """
1798 args = arg_s.split(' ',1)
1704 args = arg_s.split(' ',1)
1799 magic_name = args[0]
1705 magic_name = args[0]
1800 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1706 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1801
1707
1802 try:
1708 try:
1803 magic_args = args[1]
1709 magic_args = args[1]
1804 except IndexError:
1710 except IndexError:
1805 magic_args = ''
1711 magic_args = ''
1806 fn = getattr(self,'magic_'+magic_name,None)
1712 fn = getattr(self,'magic_'+magic_name,None)
1807 if fn is None:
1713 if fn is None:
1808 error("Magic function `%s` not found." % magic_name)
1714 error("Magic function `%s` not found." % magic_name)
1809 else:
1715 else:
1810 magic_args = self.var_expand(magic_args,1)
1716 magic_args = self.var_expand(magic_args,1)
1811 with nested(self.builtin_trap,):
1717 with nested(self.builtin_trap,):
1812 result = fn(magic_args)
1718 result = fn(magic_args)
1813 return result
1719 return result
1814
1720
1815 def define_magic(self, magicname, func):
1721 def define_magic(self, magicname, func):
1816 """Expose own function as magic function for ipython
1722 """Expose own function as magic function for ipython
1817
1723
1818 def foo_impl(self,parameter_s=''):
1724 def foo_impl(self,parameter_s=''):
1819 'My very own magic!. (Use docstrings, IPython reads them).'
1725 'My very own magic!. (Use docstrings, IPython reads them).'
1820 print 'Magic function. Passed parameter is between < >:'
1726 print 'Magic function. Passed parameter is between < >:'
1821 print '<%s>' % parameter_s
1727 print '<%s>' % parameter_s
1822 print 'The self object is:',self
1728 print 'The self object is:',self
1823
1729
1824 self.define_magic('foo',foo_impl)
1730 self.define_magic('foo',foo_impl)
1825 """
1731 """
1826
1732
1827 import new
1733 import new
1828 im = new.instancemethod(func,self, self.__class__)
1734 im = new.instancemethod(func,self, self.__class__)
1829 old = getattr(self, "magic_" + magicname, None)
1735 old = getattr(self, "magic_" + magicname, None)
1830 setattr(self, "magic_" + magicname, im)
1736 setattr(self, "magic_" + magicname, im)
1831 return old
1737 return old
1832
1738
1833 #-------------------------------------------------------------------------
1739 #-------------------------------------------------------------------------
1834 # Things related to macros
1740 # Things related to macros
1835 #-------------------------------------------------------------------------
1741 #-------------------------------------------------------------------------
1836
1742
1837 def define_macro(self, name, themacro):
1743 def define_macro(self, name, themacro):
1838 """Define a new macro
1744 """Define a new macro
1839
1745
1840 Parameters
1746 Parameters
1841 ----------
1747 ----------
1842 name : str
1748 name : str
1843 The name of the macro.
1749 The name of the macro.
1844 themacro : str or Macro
1750 themacro : str or Macro
1845 The action to do upon invoking the macro. If a string, a new
1751 The action to do upon invoking the macro. If a string, a new
1846 Macro object is created by passing the string to it.
1752 Macro object is created by passing the string to it.
1847 """
1753 """
1848
1754
1849 from IPython.core import macro
1755 from IPython.core import macro
1850
1756
1851 if isinstance(themacro, basestring):
1757 if isinstance(themacro, basestring):
1852 themacro = macro.Macro(themacro)
1758 themacro = macro.Macro(themacro)
1853 if not isinstance(themacro, macro.Macro):
1759 if not isinstance(themacro, macro.Macro):
1854 raise ValueError('A macro must be a string or a Macro instance.')
1760 raise ValueError('A macro must be a string or a Macro instance.')
1855 self.user_ns[name] = themacro
1761 self.user_ns[name] = themacro
1856
1762
1857 #-------------------------------------------------------------------------
1763 #-------------------------------------------------------------------------
1858 # Things related to the running of system commands
1764 # Things related to the running of system commands
1859 #-------------------------------------------------------------------------
1765 #-------------------------------------------------------------------------
1860
1766
1861 def system(self, cmd):
1767 def system(self, cmd):
1862 """Call the given cmd in a subprocess.
1768 """Call the given cmd in a subprocess.
1863
1769
1864 Parameters
1770 Parameters
1865 ----------
1771 ----------
1866 cmd : str
1772 cmd : str
1867 Command to execute (can not end in '&', as bacground processes are
1773 Command to execute (can not end in '&', as bacground processes are
1868 not supported.
1774 not supported.
1869 """
1775 """
1870 # We do not support backgrounding processes because we either use
1776 # We do not support backgrounding processes because we either use
1871 # pexpect or pipes to read from. Users can always just call
1777 # pexpect or pipes to read from. Users can always just call
1872 # os.system() if they really want a background process.
1778 # os.system() if they really want a background process.
1873 if cmd.endswith('&'):
1779 if cmd.endswith('&'):
1874 raise OSError("Background processes not supported.")
1780 raise OSError("Background processes not supported.")
1875
1781
1876 return system(self.var_expand(cmd, depth=2))
1782 return system(self.var_expand(cmd, depth=2))
1877
1783
1878 def getoutput(self, cmd, split=True):
1784 def getoutput(self, cmd, split=True):
1879 """Get output (possibly including stderr) from a subprocess.
1785 """Get output (possibly including stderr) from a subprocess.
1880
1786
1881 Parameters
1787 Parameters
1882 ----------
1788 ----------
1883 cmd : str
1789 cmd : str
1884 Command to execute (can not end in '&', as background processes are
1790 Command to execute (can not end in '&', as background processes are
1885 not supported.
1791 not supported.
1886 split : bool, optional
1792 split : bool, optional
1887
1793
1888 If True, split the output into an IPython SList. Otherwise, an
1794 If True, split the output into an IPython SList. Otherwise, an
1889 IPython LSString is returned. These are objects similar to normal
1795 IPython LSString is returned. These are objects similar to normal
1890 lists and strings, with a few convenience attributes for easier
1796 lists and strings, with a few convenience attributes for easier
1891 manipulation of line-based output. You can use '?' on them for
1797 manipulation of line-based output. You can use '?' on them for
1892 details.
1798 details.
1893 """
1799 """
1894 if cmd.endswith('&'):
1800 if cmd.endswith('&'):
1895 raise OSError("Background processes not supported.")
1801 raise OSError("Background processes not supported.")
1896 out = getoutput(self.var_expand(cmd, depth=2))
1802 out = getoutput(self.var_expand(cmd, depth=2))
1897 if split:
1803 if split:
1898 out = SList(out.splitlines())
1804 out = SList(out.splitlines())
1899 else:
1805 else:
1900 out = LSString(out)
1806 out = LSString(out)
1901 return out
1807 return out
1902
1808
1903 #-------------------------------------------------------------------------
1809 #-------------------------------------------------------------------------
1904 # Things related to aliases
1810 # Things related to aliases
1905 #-------------------------------------------------------------------------
1811 #-------------------------------------------------------------------------
1906
1812
1907 def init_alias(self):
1813 def init_alias(self):
1908 self.alias_manager = AliasManager(shell=self, config=self.config)
1814 self.alias_manager = AliasManager(shell=self, config=self.config)
1909 self.ns_table['alias'] = self.alias_manager.alias_table,
1815 self.ns_table['alias'] = self.alias_manager.alias_table,
1910
1816
1911 #-------------------------------------------------------------------------
1817 #-------------------------------------------------------------------------
1912 # Things related to extensions and plugins
1818 # Things related to extensions and plugins
1913 #-------------------------------------------------------------------------
1819 #-------------------------------------------------------------------------
1914
1820
1915 def init_extension_manager(self):
1821 def init_extension_manager(self):
1916 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1822 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1917
1823
1918 def init_plugin_manager(self):
1824 def init_plugin_manager(self):
1919 self.plugin_manager = PluginManager(config=self.config)
1825 self.plugin_manager = PluginManager(config=self.config)
1920
1826
1921 #-------------------------------------------------------------------------
1827 #-------------------------------------------------------------------------
1922 # Things related to payloads
1828 # Things related to payloads
1923 #-------------------------------------------------------------------------
1829 #-------------------------------------------------------------------------
1924
1830
1925 def init_payload(self):
1831 def init_payload(self):
1926 self.payload_manager = PayloadManager(config=self.config)
1832 self.payload_manager = PayloadManager(config=self.config)
1927
1833
1928 #-------------------------------------------------------------------------
1834 #-------------------------------------------------------------------------
1929 # Things related to the prefilter
1835 # Things related to the prefilter
1930 #-------------------------------------------------------------------------
1836 #-------------------------------------------------------------------------
1931
1837
1932 def init_prefilter(self):
1838 def init_prefilter(self):
1933 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1839 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1934 # Ultimately this will be refactored in the new interpreter code, but
1840 # Ultimately this will be refactored in the new interpreter code, but
1935 # for now, we should expose the main prefilter method (there's legacy
1841 # for now, we should expose the main prefilter method (there's legacy
1936 # code out there that may rely on this).
1842 # code out there that may rely on this).
1937 self.prefilter = self.prefilter_manager.prefilter_lines
1843 self.prefilter = self.prefilter_manager.prefilter_lines
1938
1844
1939
1845
1940 def auto_rewrite_input(self, cmd):
1846 def auto_rewrite_input(self, cmd):
1941 """Print to the screen the rewritten form of the user's command.
1847 """Print to the screen the rewritten form of the user's command.
1942
1848
1943 This shows visual feedback by rewriting input lines that cause
1849 This shows visual feedback by rewriting input lines that cause
1944 automatic calling to kick in, like::
1850 automatic calling to kick in, like::
1945
1851
1946 /f x
1852 /f x
1947
1853
1948 into::
1854 into::
1949
1855
1950 ------> f(x)
1856 ------> f(x)
1951
1857
1952 after the user's input prompt. This helps the user understand that the
1858 after the user's input prompt. This helps the user understand that the
1953 input line was transformed automatically by IPython.
1859 input line was transformed automatically by IPython.
1954 """
1860 """
1955 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1861 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1956
1862
1957 try:
1863 try:
1958 # plain ascii works better w/ pyreadline, on some machines, so
1864 # plain ascii works better w/ pyreadline, on some machines, so
1959 # we use it and only print uncolored rewrite if we have unicode
1865 # we use it and only print uncolored rewrite if we have unicode
1960 rw = str(rw)
1866 rw = str(rw)
1961 print >> IPython.utils.io.Term.cout, rw
1867 print >> IPython.utils.io.Term.cout, rw
1962 except UnicodeEncodeError:
1868 except UnicodeEncodeError:
1963 print "------> " + cmd
1869 print "------> " + cmd
1964
1870
1965 #-------------------------------------------------------------------------
1871 #-------------------------------------------------------------------------
1966 # Things related to extracting values/expressions from kernel and user_ns
1872 # Things related to extracting values/expressions from kernel and user_ns
1967 #-------------------------------------------------------------------------
1873 #-------------------------------------------------------------------------
1968
1874
1969 def _simple_error(self):
1875 def _simple_error(self):
1970 etype, value = sys.exc_info()[:2]
1876 etype, value = sys.exc_info()[:2]
1971 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1877 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1972
1878
1973 def user_variables(self, names):
1879 def user_variables(self, names):
1974 """Get a list of variable names from the user's namespace.
1880 """Get a list of variable names from the user's namespace.
1975
1881
1976 Parameters
1882 Parameters
1977 ----------
1883 ----------
1978 names : list of strings
1884 names : list of strings
1979 A list of names of variables to be read from the user namespace.
1885 A list of names of variables to be read from the user namespace.
1980
1886
1981 Returns
1887 Returns
1982 -------
1888 -------
1983 A dict, keyed by the input names and with the repr() of each value.
1889 A dict, keyed by the input names and with the repr() of each value.
1984 """
1890 """
1985 out = {}
1891 out = {}
1986 user_ns = self.user_ns
1892 user_ns = self.user_ns
1987 for varname in names:
1893 for varname in names:
1988 try:
1894 try:
1989 value = repr(user_ns[varname])
1895 value = repr(user_ns[varname])
1990 except:
1896 except:
1991 value = self._simple_error()
1897 value = self._simple_error()
1992 out[varname] = value
1898 out[varname] = value
1993 return out
1899 return out
1994
1900
1995 def user_expressions(self, expressions):
1901 def user_expressions(self, expressions):
1996 """Evaluate a dict of expressions in the user's namespace.
1902 """Evaluate a dict of expressions in the user's namespace.
1997
1903
1998 Parameters
1904 Parameters
1999 ----------
1905 ----------
2000 expressions : dict
1906 expressions : dict
2001 A dict with string keys and string values. The expression values
1907 A dict with string keys and string values. The expression values
2002 should be valid Python expressions, each of which will be evaluated
1908 should be valid Python expressions, each of which will be evaluated
2003 in the user namespace.
1909 in the user namespace.
2004
1910
2005 Returns
1911 Returns
2006 -------
1912 -------
2007 A dict, keyed like the input expressions dict, with the repr() of each
1913 A dict, keyed like the input expressions dict, with the repr() of each
2008 value.
1914 value.
2009 """
1915 """
2010 out = {}
1916 out = {}
2011 user_ns = self.user_ns
1917 user_ns = self.user_ns
2012 global_ns = self.user_global_ns
1918 global_ns = self.user_global_ns
2013 for key, expr in expressions.iteritems():
1919 for key, expr in expressions.iteritems():
2014 try:
1920 try:
2015 value = repr(eval(expr, global_ns, user_ns))
1921 value = repr(eval(expr, global_ns, user_ns))
2016 except:
1922 except:
2017 value = self._simple_error()
1923 value = self._simple_error()
2018 out[key] = value
1924 out[key] = value
2019 return out
1925 return out
2020
1926
2021 #-------------------------------------------------------------------------
1927 #-------------------------------------------------------------------------
2022 # Things related to the running of code
1928 # Things related to the running of code
2023 #-------------------------------------------------------------------------
1929 #-------------------------------------------------------------------------
2024
1930
2025 def ex(self, cmd):
1931 def ex(self, cmd):
2026 """Execute a normal python statement in user namespace."""
1932 """Execute a normal python statement in user namespace."""
2027 with nested(self.builtin_trap,):
1933 with nested(self.builtin_trap,):
2028 exec cmd in self.user_global_ns, self.user_ns
1934 exec cmd in self.user_global_ns, self.user_ns
2029
1935
2030 def ev(self, expr):
1936 def ev(self, expr):
2031 """Evaluate python expression expr in user namespace.
1937 """Evaluate python expression expr in user namespace.
2032
1938
2033 Returns the result of evaluation
1939 Returns the result of evaluation
2034 """
1940 """
2035 with nested(self.builtin_trap,):
1941 with nested(self.builtin_trap,):
2036 return eval(expr, self.user_global_ns, self.user_ns)
1942 return eval(expr, self.user_global_ns, self.user_ns)
2037
1943
2038 def safe_execfile(self, fname, *where, **kw):
1944 def safe_execfile(self, fname, *where, **kw):
2039 """A safe version of the builtin execfile().
1945 """A safe version of the builtin execfile().
2040
1946
2041 This version will never throw an exception, but instead print
1947 This version will never throw an exception, but instead print
2042 helpful error messages to the screen. This only works on pure
1948 helpful error messages to the screen. This only works on pure
2043 Python files with the .py extension.
1949 Python files with the .py extension.
2044
1950
2045 Parameters
1951 Parameters
2046 ----------
1952 ----------
2047 fname : string
1953 fname : string
2048 The name of the file to be executed.
1954 The name of the file to be executed.
2049 where : tuple
1955 where : tuple
2050 One or two namespaces, passed to execfile() as (globals,locals).
1956 One or two namespaces, passed to execfile() as (globals,locals).
2051 If only one is given, it is passed as both.
1957 If only one is given, it is passed as both.
2052 exit_ignore : bool (False)
1958 exit_ignore : bool (False)
2053 If True, then silence SystemExit for non-zero status (it is always
1959 If True, then silence SystemExit for non-zero status (it is always
2054 silenced for zero status, as it is so common).
1960 silenced for zero status, as it is so common).
2055 """
1961 """
2056 kw.setdefault('exit_ignore', False)
1962 kw.setdefault('exit_ignore', False)
2057
1963
2058 fname = os.path.abspath(os.path.expanduser(fname))
1964 fname = os.path.abspath(os.path.expanduser(fname))
2059
1965
2060 # Make sure we have a .py file
1966 # Make sure we have a .py file
2061 if not fname.endswith('.py'):
1967 if not fname.endswith('.py'):
2062 warn('File must end with .py to be run using execfile: <%s>' % fname)
1968 warn('File must end with .py to be run using execfile: <%s>' % fname)
2063
1969
2064 # Make sure we can open the file
1970 # Make sure we can open the file
2065 try:
1971 try:
2066 with open(fname) as thefile:
1972 with open(fname) as thefile:
2067 pass
1973 pass
2068 except:
1974 except:
2069 warn('Could not open file <%s> for safe execution.' % fname)
1975 warn('Could not open file <%s> for safe execution.' % fname)
2070 return
1976 return
2071
1977
2072 # Find things also in current directory. This is needed to mimic the
1978 # Find things also in current directory. This is needed to mimic the
2073 # behavior of running a script from the system command line, where
1979 # behavior of running a script from the system command line, where
2074 # Python inserts the script's directory into sys.path
1980 # Python inserts the script's directory into sys.path
2075 dname = os.path.dirname(fname)
1981 dname = os.path.dirname(fname)
2076
1982
2077 with prepended_to_syspath(dname):
1983 with prepended_to_syspath(dname):
2078 try:
1984 try:
2079 execfile(fname,*where)
1985 execfile(fname,*where)
2080 except SystemExit, status:
1986 except SystemExit, status:
2081 # If the call was made with 0 or None exit status (sys.exit(0)
1987 # If the call was made with 0 or None exit status (sys.exit(0)
2082 # or sys.exit() ), don't bother showing a traceback, as both of
1988 # or sys.exit() ), don't bother showing a traceback, as both of
2083 # these are considered normal by the OS:
1989 # these are considered normal by the OS:
2084 # > python -c'import sys;sys.exit(0)'; echo $?
1990 # > python -c'import sys;sys.exit(0)'; echo $?
2085 # 0
1991 # 0
2086 # > python -c'import sys;sys.exit()'; echo $?
1992 # > python -c'import sys;sys.exit()'; echo $?
2087 # 0
1993 # 0
2088 # For other exit status, we show the exception unless
1994 # For other exit status, we show the exception unless
2089 # explicitly silenced, but only in short form.
1995 # explicitly silenced, but only in short form.
2090 if status.code not in (0, None) and not kw['exit_ignore']:
1996 if status.code not in (0, None) and not kw['exit_ignore']:
2091 self.showtraceback(exception_only=True)
1997 self.showtraceback(exception_only=True)
2092 except:
1998 except:
2093 self.showtraceback()
1999 self.showtraceback()
2094
2000
2095 def safe_execfile_ipy(self, fname):
2001 def safe_execfile_ipy(self, fname):
2096 """Like safe_execfile, but for .ipy files with IPython syntax.
2002 """Like safe_execfile, but for .ipy files with IPython syntax.
2097
2003
2098 Parameters
2004 Parameters
2099 ----------
2005 ----------
2100 fname : str
2006 fname : str
2101 The name of the file to execute. The filename must have a
2007 The name of the file to execute. The filename must have a
2102 .ipy extension.
2008 .ipy extension.
2103 """
2009 """
2104 fname = os.path.abspath(os.path.expanduser(fname))
2010 fname = os.path.abspath(os.path.expanduser(fname))
2105
2011
2106 # Make sure we have a .py file
2012 # Make sure we have a .py file
2107 if not fname.endswith('.ipy'):
2013 if not fname.endswith('.ipy'):
2108 warn('File must end with .py to be run using execfile: <%s>' % fname)
2014 warn('File must end with .py to be run using execfile: <%s>' % fname)
2109
2015
2110 # Make sure we can open the file
2016 # Make sure we can open the file
2111 try:
2017 try:
2112 with open(fname) as thefile:
2018 with open(fname) as thefile:
2113 pass
2019 pass
2114 except:
2020 except:
2115 warn('Could not open file <%s> for safe execution.' % fname)
2021 warn('Could not open file <%s> for safe execution.' % fname)
2116 return
2022 return
2117
2023
2118 # Find things also in current directory. This is needed to mimic the
2024 # Find things also in current directory. This is needed to mimic the
2119 # behavior of running a script from the system command line, where
2025 # behavior of running a script from the system command line, where
2120 # Python inserts the script's directory into sys.path
2026 # Python inserts the script's directory into sys.path
2121 dname = os.path.dirname(fname)
2027 dname = os.path.dirname(fname)
2122
2028
2123 with prepended_to_syspath(dname):
2029 with prepended_to_syspath(dname):
2124 try:
2030 try:
2125 with open(fname) as thefile:
2031 with open(fname) as thefile:
2126 script = thefile.read()
2032 script = thefile.read()
2127 # self.runlines currently captures all exceptions
2033 # self.runlines currently captures all exceptions
2128 # raise in user code. It would be nice if there were
2034 # raise in user code. It would be nice if there were
2129 # versions of runlines, execfile that did raise, so
2035 # versions of runlines, execfile that did raise, so
2130 # we could catch the errors.
2036 # we could catch the errors.
2131 self.runlines(script, clean=True)
2037 self.runlines(script, clean=True)
2132 except:
2038 except:
2133 self.showtraceback()
2039 self.showtraceback()
2134 warn('Unknown failure executing file: <%s>' % fname)
2040 warn('Unknown failure executing file: <%s>' % fname)
2135
2041
2136 def run_cell(self, cell):
2042 def run_cell(self, cell):
2137 """Run the contents of an entire multiline 'cell' of code.
2043 """Run the contents of an entire multiline 'cell' of code.
2138
2044
2139 The cell is split into separate blocks which can be executed
2045 The cell is split into separate blocks which can be executed
2140 individually. Then, based on how many blocks there are, they are
2046 individually. Then, based on how many blocks there are, they are
2141 executed as follows:
2047 executed as follows:
2142
2048
2143 - A single block: 'single' mode.
2049 - A single block: 'single' mode.
2144
2050
2145 If there's more than one block, it depends:
2051 If there's more than one block, it depends:
2146
2052
2147 - if the last one is no more than two lines long, run all but the last
2053 - if the last one is no more than two lines long, run all but the last
2148 in 'exec' mode and the very last one in 'single' mode. This makes it
2054 in 'exec' mode and the very last one in 'single' mode. This makes it
2149 easy to type simple expressions at the end to see computed values. -
2055 easy to type simple expressions at the end to see computed values. -
2150 otherwise (last one is also multiline), run all in 'exec' mode
2056 otherwise (last one is also multiline), run all in 'exec' mode
2151
2057
2152 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2058 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2153 results are displayed and output prompts are computed. In 'exec' mode,
2059 results are displayed and output prompts are computed. In 'exec' mode,
2154 no results are displayed unless :func:`print` is called explicitly;
2060 no results are displayed unless :func:`print` is called explicitly;
2155 this mode is more akin to running a script.
2061 this mode is more akin to running a script.
2156
2062
2157 Parameters
2063 Parameters
2158 ----------
2064 ----------
2159 cell : str
2065 cell : str
2160 A single or multiline string.
2066 A single or multiline string.
2161 """
2067 """
2162 #################################################################
2068 #################################################################
2163 # FIXME
2069 # FIXME
2164 # =====
2070 # =====
2165 # This execution logic should stop calling runlines altogether, and
2071 # This execution logic should stop calling runlines altogether, and
2166 # instead we should do what runlines does, in a controlled manner, here
2072 # instead we should do what runlines does, in a controlled manner, here
2167 # (runlines mutates lots of state as it goes calling sub-methods that
2073 # (runlines mutates lots of state as it goes calling sub-methods that
2168 # also mutate state). Basically we should:
2074 # also mutate state). Basically we should:
2169 # - apply dynamic transforms for single-line input (the ones that
2075 # - apply dynamic transforms for single-line input (the ones that
2170 # split_blocks won't apply since they need context).
2076 # split_blocks won't apply since they need context).
2171 # - increment the global execution counter (we need to pull that out
2077 # - increment the global execution counter (we need to pull that out
2172 # from outputcache's control; outputcache should instead read it from
2078 # from outputcache's control; outputcache should instead read it from
2173 # the main object).
2079 # the main object).
2174 # - do any logging of input
2080 # - do any logging of input
2175 # - update histories (raw/translated)
2081 # - update histories (raw/translated)
2176 # - then, call plain runsource (for single blocks, so displayhook is
2082 # - then, call plain runsource (for single blocks, so displayhook is
2177 # triggered) or runcode (for multiline blocks in exec mode).
2083 # triggered) or runcode (for multiline blocks in exec mode).
2178 #
2084 #
2179 # Once this is done, we'll be able to stop using runlines and we'll
2085 # Once this is done, we'll be able to stop using runlines and we'll
2180 # also have a much cleaner separation of logging, input history and
2086 # also have a much cleaner separation of logging, input history and
2181 # output cache management.
2087 # output cache management.
2182 #################################################################
2088 #################################################################
2183
2089
2184 # We need to break up the input into executable blocks that can be run
2090 # We need to break up the input into executable blocks that can be run
2185 # in 'single' mode, to provide comfortable user behavior.
2091 # in 'single' mode, to provide comfortable user behavior.
2186 blocks = self.input_splitter.split_blocks(cell)
2092 blocks = self.input_splitter.split_blocks(cell)
2187
2093
2188 if not blocks:
2094 if not blocks:
2189 return
2095 return
2190
2096
2191 # Store the 'ipython' version of the cell as well, since that's what
2097 # Store the 'ipython' version of the cell as well, since that's what
2192 # needs to go into the translated history and get executed (the
2098 # needs to go into the translated history and get executed (the
2193 # original cell may contain non-python syntax).
2099 # original cell may contain non-python syntax).
2194 ipy_cell = ''.join(blocks)
2100 ipy_cell = ''.join(blocks)
2195
2101
2196 # Each cell is a *single* input, regardless of how many lines it has
2102 # Each cell is a *single* input, regardless of how many lines it has
2197 self.execution_count += 1
2103 self.execution_count += 1
2198
2104
2199 # Store raw and processed history
2105 # Store raw and processed history
2200 self.input_hist_raw.append(cell)
2106 self.input_hist_raw.append(cell)
2201 self.input_hist.append(ipy_cell)
2107 self.input_hist.append(ipy_cell)
2202
2108
2109
2110 # dbg code!!!
2111 def myapp(self, val): # dbg
2112 import traceback as tb
2113 stack = ''.join(tb.format_stack())
2114 print 'Value:', val
2115 print 'Stack:\n', stack
2116 list.append(self, val)
2117
2118 import new
2119 self.input_hist.append = new.instancemethod(myapp, self.input_hist,
2120 list)
2121 # End dbg
2122
2203 # All user code execution must happen with our context managers active
2123 # All user code execution must happen with our context managers active
2204 with nested(self.builtin_trap, self.display_trap):
2124 with nested(self.builtin_trap, self.display_trap):
2205 # Single-block input should behave like an interactive prompt
2125 # Single-block input should behave like an interactive prompt
2206 if len(blocks) == 1:
2126 if len(blocks) == 1:
2207 return self.run_one_block(blocks[0])
2127 return self.run_one_block(blocks[0])
2208
2128
2209 # In multi-block input, if the last block is a simple (one-two
2129 # In multi-block input, if the last block is a simple (one-two
2210 # lines) expression, run it in single mode so it produces output.
2130 # lines) expression, run it in single mode so it produces output.
2211 # Otherwise just feed the whole thing to runcode. This seems like
2131 # Otherwise just feed the whole thing to runcode. This seems like
2212 # a reasonable usability design.
2132 # a reasonable usability design.
2213 last = blocks[-1]
2133 last = blocks[-1]
2214 last_nlines = len(last.splitlines())
2134 last_nlines = len(last.splitlines())
2215
2135
2216 # Note: below, whenever we call runcode, we must sync history
2136 # Note: below, whenever we call runcode, we must sync history
2217 # ourselves, because runcode is NOT meant to manage history at all.
2137 # ourselves, because runcode is NOT meant to manage history at all.
2218 if last_nlines < 2:
2138 if last_nlines < 2:
2219 # Here we consider the cell split between 'body' and 'last',
2139 # Here we consider the cell split between 'body' and 'last',
2220 # store all history and execute 'body', and if successful, then
2140 # store all history and execute 'body', and if successful, then
2221 # proceed to execute 'last'.
2141 # proceed to execute 'last'.
2222
2142
2223 # Get the main body to run as a cell
2143 # Get the main body to run as a cell
2224 ipy_body = ''.join(blocks[:-1])
2144 ipy_body = ''.join(blocks[:-1])
2225 retcode = self.runcode(ipy_body, post_execute=False)
2145 retcode = self.runcode(ipy_body, post_execute=False)
2226 if retcode==0:
2146 if retcode==0:
2227 # And the last expression via runlines so it produces output
2147 # And the last expression via runlines so it produces output
2228 self.run_one_block(last)
2148 self.run_one_block(last)
2229 else:
2149 else:
2230 # Run the whole cell as one entity, storing both raw and
2150 # Run the whole cell as one entity, storing both raw and
2231 # processed input in history
2151 # processed input in history
2232 self.runcode(ipy_cell)
2152 self.runcode(ipy_cell)
2233
2153
2234 def run_one_block(self, block):
2154 def run_one_block(self, block):
2235 """Run a single interactive block.
2155 """Run a single interactive block.
2236
2156
2237 If the block is single-line, dynamic transformations are applied to it
2157 If the block is single-line, dynamic transformations are applied to it
2238 (like automagics, autocall and alias recognition).
2158 (like automagics, autocall and alias recognition).
2239 """
2159 """
2240 if len(block.splitlines()) <= 1:
2160 if len(block.splitlines()) <= 1:
2241 out = self.run_single_line(block)
2161 out = self.run_single_line(block)
2242 else:
2162 else:
2243 out = self.runcode(block)
2163 out = self.runcode(block)
2244 return out
2164 return out
2245
2165
2246 def run_single_line(self, line):
2166 def run_single_line(self, line):
2247 """Run a single-line interactive statement.
2167 """Run a single-line interactive statement.
2248
2168
2249 This assumes the input has been transformed to IPython syntax by
2169 This assumes the input has been transformed to IPython syntax by
2250 applying all static transformations (those with an explicit prefix like
2170 applying all static transformations (those with an explicit prefix like
2251 % or !), but it will further try to apply the dynamic ones.
2171 % or !), but it will further try to apply the dynamic ones.
2252
2172
2253 It does not update history.
2173 It does not update history.
2254 """
2174 """
2255 tline = self.prefilter_manager.prefilter_line(line)
2175 tline = self.prefilter_manager.prefilter_line(line)
2256 return self.runsource(tline)
2176 return self.runsource(tline)
2257
2177
2258 def runlines(self, lines, clean=False):
2178 def runlines(self, lines, clean=False):
2259 """Run a string of one or more lines of source.
2179 """Run a string of one or more lines of source.
2260
2180
2261 This method is capable of running a string containing multiple source
2181 This method is capable of running a string containing multiple source
2262 lines, as if they had been entered at the IPython prompt. Since it
2182 lines, as if they had been entered at the IPython prompt. Since it
2263 exposes IPython's processing machinery, the given strings can contain
2183 exposes IPython's processing machinery, the given strings can contain
2264 magic calls (%magic), special shell access (!cmd), etc.
2184 magic calls (%magic), special shell access (!cmd), etc.
2265 """
2185 """
2266
2186
2267 if isinstance(lines, (list, tuple)):
2187 if isinstance(lines, (list, tuple)):
2268 lines = '\n'.join(lines)
2188 lines = '\n'.join(lines)
2269
2189
2270 if clean:
2190 if clean:
2271 lines = self._cleanup_ipy_script(lines)
2191 lines = self._cleanup_ipy_script(lines)
2272
2192
2273 # We must start with a clean buffer, in case this is run from an
2193 # We must start with a clean buffer, in case this is run from an
2274 # interactive IPython session (via a magic, for example).
2194 # interactive IPython session (via a magic, for example).
2275 self.resetbuffer()
2195 self.resetbuffer()
2276 lines = lines.splitlines()
2196 lines = lines.splitlines()
2277 more = 0
2197 more = 0
2278 with nested(self.builtin_trap, self.display_trap):
2198 with nested(self.builtin_trap, self.display_trap):
2279 for line in lines:
2199 for line in lines:
2280 # skip blank lines so we don't mess up the prompt counter, but
2200 # skip blank lines so we don't mess up the prompt counter, but
2281 # do NOT skip even a blank line if we are in a code block (more
2201 # do NOT skip even a blank line if we are in a code block (more
2282 # is true)
2202 # is true)
2283
2203
2284 if line or more:
2204 if line or more:
2285 # push to raw history, so hist line numbers stay in sync
2205 # push to raw history, so hist line numbers stay in sync
2286 self.input_hist_raw.append(line + '\n')
2206 self.input_hist_raw.append(line + '\n')
2287 prefiltered = self.prefilter_manager.prefilter_lines(line,
2207 prefiltered = self.prefilter_manager.prefilter_lines(line,
2288 more)
2208 more)
2289 more = self.push_line(prefiltered)
2209 more = self.push_line(prefiltered)
2290 # IPython's runsource returns None if there was an error
2210 # IPython's runsource returns None if there was an error
2291 # compiling the code. This allows us to stop processing
2211 # compiling the code. This allows us to stop processing
2292 # right away, so the user gets the error message at the
2212 # right away, so the user gets the error message at the
2293 # right place.
2213 # right place.
2294 if more is None:
2214 if more is None:
2295 break
2215 break
2296 else:
2216 else:
2297 self.input_hist_raw.append("\n")
2217 self.input_hist_raw.append("\n")
2298 # final newline in case the input didn't have it, so that the code
2218 # final newline in case the input didn't have it, so that the code
2299 # actually does get executed
2219 # actually does get executed
2300 if more:
2220 if more:
2301 self.push_line('\n')
2221 self.push_line('\n')
2302
2222
2303 def runsource(self, source, filename='<input>', symbol='single'):
2223 def runsource(self, source, filename='<input>', symbol='single'):
2304 """Compile and run some source in the interpreter.
2224 """Compile and run some source in the interpreter.
2305
2225
2306 Arguments are as for compile_command().
2226 Arguments are as for compile_command().
2307
2227
2308 One several things can happen:
2228 One several things can happen:
2309
2229
2310 1) The input is incorrect; compile_command() raised an
2230 1) The input is incorrect; compile_command() raised an
2311 exception (SyntaxError or OverflowError). A syntax traceback
2231 exception (SyntaxError or OverflowError). A syntax traceback
2312 will be printed by calling the showsyntaxerror() method.
2232 will be printed by calling the showsyntaxerror() method.
2313
2233
2314 2) The input is incomplete, and more input is required;
2234 2) The input is incomplete, and more input is required;
2315 compile_command() returned None. Nothing happens.
2235 compile_command() returned None. Nothing happens.
2316
2236
2317 3) The input is complete; compile_command() returned a code
2237 3) The input is complete; compile_command() returned a code
2318 object. The code is executed by calling self.runcode() (which
2238 object. The code is executed by calling self.runcode() (which
2319 also handles run-time exceptions, except for SystemExit).
2239 also handles run-time exceptions, except for SystemExit).
2320
2240
2321 The return value is:
2241 The return value is:
2322
2242
2323 - True in case 2
2243 - True in case 2
2324
2244
2325 - False in the other cases, unless an exception is raised, where
2245 - False in the other cases, unless an exception is raised, where
2326 None is returned instead. This can be used by external callers to
2246 None is returned instead. This can be used by external callers to
2327 know whether to continue feeding input or not.
2247 know whether to continue feeding input or not.
2328
2248
2329 The return value can be used to decide whether to use sys.ps1 or
2249 The return value can be used to decide whether to use sys.ps1 or
2330 sys.ps2 to prompt the next line."""
2250 sys.ps2 to prompt the next line."""
2331
2251
2332 # We need to ensure that the source is unicode from here on.
2252 # We need to ensure that the source is unicode from here on.
2333 if type(source)==str:
2253 if type(source)==str:
2334 source = source.decode(self.stdin_encoding)
2254 source = source.decode(self.stdin_encoding)
2335
2255
2336 # if the source code has leading blanks, add 'if 1:\n' to it
2256 # if the source code has leading blanks, add 'if 1:\n' to it
2337 # this allows execution of indented pasted code. It is tempting
2257 # this allows execution of indented pasted code. It is tempting
2338 # to add '\n' at the end of source to run commands like ' a=1'
2258 # to add '\n' at the end of source to run commands like ' a=1'
2339 # directly, but this fails for more complicated scenarios
2259 # directly, but this fails for more complicated scenarios
2340
2260
2341 if source[:1] in [' ', '\t']:
2261 if source[:1] in [' ', '\t']:
2342 source = u'if 1:\n%s' % source
2262 source = u'if 1:\n%s' % source
2343
2263
2344 try:
2264 try:
2345 code = self.compile(source,filename,symbol)
2265 code = self.compile(source,filename,symbol)
2346 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2266 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2347 # Case 1
2267 # Case 1
2348 self.showsyntaxerror(filename)
2268 self.showsyntaxerror(filename)
2349 return None
2269 return None
2350
2270
2351 if code is None:
2271 if code is None:
2352 # Case 2
2272 # Case 2
2353 return True
2273 return True
2354
2274
2355 # Case 3
2275 # Case 3
2356 # We store the code object so that threaded shells and
2276 # We store the code object so that threaded shells and
2357 # custom exception handlers can access all this info if needed.
2277 # custom exception handlers can access all this info if needed.
2358 # The source corresponding to this can be obtained from the
2278 # The source corresponding to this can be obtained from the
2359 # buffer attribute as '\n'.join(self.buffer).
2279 # buffer attribute as '\n'.join(self.buffer).
2360 self.code_to_run = code
2280 self.code_to_run = code
2361 # now actually execute the code object
2281 # now actually execute the code object
2362 if self.runcode(code) == 0:
2282 if self.runcode(code) == 0:
2363 return False
2283 return False
2364 else:
2284 else:
2365 return None
2285 return None
2366
2286
2367 def runcode(self, code_obj, post_execute=True):
2287 def runcode(self, code_obj, post_execute=True):
2368 """Execute a code object.
2288 """Execute a code object.
2369
2289
2370 When an exception occurs, self.showtraceback() is called to display a
2290 When an exception occurs, self.showtraceback() is called to display a
2371 traceback.
2291 traceback.
2372
2292
2373 Return value: a flag indicating whether the code to be run completed
2293 Return value: a flag indicating whether the code to be run completed
2374 successfully:
2294 successfully:
2375
2295
2376 - 0: successful execution.
2296 - 0: successful execution.
2377 - 1: an error occurred.
2297 - 1: an error occurred.
2378 """
2298 """
2379
2299
2380 # Set our own excepthook in case the user code tries to call it
2300 # Set our own excepthook in case the user code tries to call it
2381 # directly, so that the IPython crash handler doesn't get triggered
2301 # directly, so that the IPython crash handler doesn't get triggered
2382 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2302 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2383
2303
2384 # we save the original sys.excepthook in the instance, in case config
2304 # we save the original sys.excepthook in the instance, in case config
2385 # code (such as magics) needs access to it.
2305 # code (such as magics) needs access to it.
2386 self.sys_excepthook = old_excepthook
2306 self.sys_excepthook = old_excepthook
2387 outflag = 1 # happens in more places, so it's easier as default
2307 outflag = 1 # happens in more places, so it's easier as default
2388 try:
2308 try:
2389 try:
2309 try:
2390 self.hooks.pre_runcode_hook()
2310 self.hooks.pre_runcode_hook()
2391 #rprint('Running code') # dbg
2311 #rprint('Running code') # dbg
2392 exec code_obj in self.user_global_ns, self.user_ns
2312 exec code_obj in self.user_global_ns, self.user_ns
2393 finally:
2313 finally:
2394 # Reset our crash handler in place
2314 # Reset our crash handler in place
2395 sys.excepthook = old_excepthook
2315 sys.excepthook = old_excepthook
2396 except SystemExit:
2316 except SystemExit:
2397 self.resetbuffer()
2317 self.resetbuffer()
2398 self.showtraceback(exception_only=True)
2318 self.showtraceback(exception_only=True)
2399 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2319 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2400 except self.custom_exceptions:
2320 except self.custom_exceptions:
2401 etype,value,tb = sys.exc_info()
2321 etype,value,tb = sys.exc_info()
2402 self.CustomTB(etype,value,tb)
2322 self.CustomTB(etype,value,tb)
2403 except:
2323 except:
2404 self.showtraceback()
2324 self.showtraceback()
2405 else:
2325 else:
2406 outflag = 0
2326 outflag = 0
2407 if softspace(sys.stdout, 0):
2327 if softspace(sys.stdout, 0):
2408 print
2328 print
2409
2329
2410 # Execute any registered post-execution functions. Here, any errors
2330 # Execute any registered post-execution functions. Here, any errors
2411 # are reported only minimally and just on the terminal, because the
2331 # are reported only minimally and just on the terminal, because the
2412 # main exception channel may be occupied with a user traceback.
2332 # main exception channel may be occupied with a user traceback.
2413 # FIXME: we need to think this mechanism a little more carefully.
2333 # FIXME: we need to think this mechanism a little more carefully.
2414 if post_execute:
2334 if post_execute:
2415 for func in self._post_execute:
2335 for func in self._post_execute:
2416 try:
2336 try:
2417 func()
2337 func()
2418 except:
2338 except:
2419 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2339 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2420 func
2340 func
2421 print >> io.Term.cout, head
2341 print >> io.Term.cout, head
2422 print >> io.Term.cout, self._simple_error()
2342 print >> io.Term.cout, self._simple_error()
2423 print >> io.Term.cout, 'Removing from post_execute'
2343 print >> io.Term.cout, 'Removing from post_execute'
2424 self._post_execute.remove(func)
2344 self._post_execute.remove(func)
2425
2345
2426 # Flush out code object which has been run (and source)
2346 # Flush out code object which has been run (and source)
2427 self.code_to_run = None
2347 self.code_to_run = None
2428 return outflag
2348 return outflag
2429
2349
2430 def push_line(self, line):
2350 def push_line(self, line):
2431 """Push a line to the interpreter.
2351 """Push a line to the interpreter.
2432
2352
2433 The line should not have a trailing newline; it may have
2353 The line should not have a trailing newline; it may have
2434 internal newlines. The line is appended to a buffer and the
2354 internal newlines. The line is appended to a buffer and the
2435 interpreter's runsource() method is called with the
2355 interpreter's runsource() method is called with the
2436 concatenated contents of the buffer as source. If this
2356 concatenated contents of the buffer as source. If this
2437 indicates that the command was executed or invalid, the buffer
2357 indicates that the command was executed or invalid, the buffer
2438 is reset; otherwise, the command is incomplete, and the buffer
2358 is reset; otherwise, the command is incomplete, and the buffer
2439 is left as it was after the line was appended. The return
2359 is left as it was after the line was appended. The return
2440 value is 1 if more input is required, 0 if the line was dealt
2360 value is 1 if more input is required, 0 if the line was dealt
2441 with in some way (this is the same as runsource()).
2361 with in some way (this is the same as runsource()).
2442 """
2362 """
2443
2363
2444 # autoindent management should be done here, and not in the
2364 # autoindent management should be done here, and not in the
2445 # interactive loop, since that one is only seen by keyboard input. We
2365 # interactive loop, since that one is only seen by keyboard input. We
2446 # need this done correctly even for code run via runlines (which uses
2366 # need this done correctly even for code run via runlines (which uses
2447 # push).
2367 # push).
2448
2368
2449 #print 'push line: <%s>' % line # dbg
2369 #print 'push line: <%s>' % line # dbg
2450 for subline in line.splitlines():
2370 for subline in line.splitlines():
2451 self._autoindent_update(subline)
2371 self._autoindent_update(subline)
2452 self.buffer.append(line)
2372 self.buffer.append(line)
2453 more = self.runsource('\n'.join(self.buffer), self.filename)
2373 more = self.runsource('\n'.join(self.buffer), self.filename)
2454 if not more:
2374 if not more:
2455 self.resetbuffer()
2375 self.resetbuffer()
2456 self.execution_count += 1
2376 self.execution_count += 1
2457 return more
2377 return more
2458
2378
2459 def resetbuffer(self):
2379 def resetbuffer(self):
2460 """Reset the input buffer."""
2380 """Reset the input buffer."""
2461 self.buffer[:] = []
2381 self.buffer[:] = []
2462
2382
2463 def _is_secondary_block_start(self, s):
2383 def _is_secondary_block_start(self, s):
2464 if not s.endswith(':'):
2384 if not s.endswith(':'):
2465 return False
2385 return False
2466 if (s.startswith('elif') or
2386 if (s.startswith('elif') or
2467 s.startswith('else') or
2387 s.startswith('else') or
2468 s.startswith('except') or
2388 s.startswith('except') or
2469 s.startswith('finally')):
2389 s.startswith('finally')):
2470 return True
2390 return True
2471
2391
2472 def _cleanup_ipy_script(self, script):
2392 def _cleanup_ipy_script(self, script):
2473 """Make a script safe for self.runlines()
2393 """Make a script safe for self.runlines()
2474
2394
2475 Currently, IPython is lines based, with blocks being detected by
2395 Currently, IPython is lines based, with blocks being detected by
2476 empty lines. This is a problem for block based scripts that may
2396 empty lines. This is a problem for block based scripts that may
2477 not have empty lines after blocks. This script adds those empty
2397 not have empty lines after blocks. This script adds those empty
2478 lines to make scripts safe for running in the current line based
2398 lines to make scripts safe for running in the current line based
2479 IPython.
2399 IPython.
2480 """
2400 """
2481 res = []
2401 res = []
2482 lines = script.splitlines()
2402 lines = script.splitlines()
2483 level = 0
2403 level = 0
2484
2404
2485 for l in lines:
2405 for l in lines:
2486 lstripped = l.lstrip()
2406 lstripped = l.lstrip()
2487 stripped = l.strip()
2407 stripped = l.strip()
2488 if not stripped:
2408 if not stripped:
2489 continue
2409 continue
2490 newlevel = len(l) - len(lstripped)
2410 newlevel = len(l) - len(lstripped)
2491 if level > 0 and newlevel == 0 and \
2411 if level > 0 and newlevel == 0 and \
2492 not self._is_secondary_block_start(stripped):
2412 not self._is_secondary_block_start(stripped):
2493 # add empty line
2413 # add empty line
2494 res.append('')
2414 res.append('')
2495 res.append(l)
2415 res.append(l)
2496 level = newlevel
2416 level = newlevel
2497
2417
2498 return '\n'.join(res) + '\n'
2418 return '\n'.join(res) + '\n'
2499
2419
2500 def _autoindent_update(self,line):
2420 def _autoindent_update(self,line):
2501 """Keep track of the indent level."""
2421 """Keep track of the indent level."""
2502
2422
2503 #debugx('line')
2423 #debugx('line')
2504 #debugx('self.indent_current_nsp')
2424 #debugx('self.indent_current_nsp')
2505 if self.autoindent:
2425 if self.autoindent:
2506 if line:
2426 if line:
2507 inisp = num_ini_spaces(line)
2427 inisp = num_ini_spaces(line)
2508 if inisp < self.indent_current_nsp:
2428 if inisp < self.indent_current_nsp:
2509 self.indent_current_nsp = inisp
2429 self.indent_current_nsp = inisp
2510
2430
2511 if line[-1] == ':':
2431 if line[-1] == ':':
2512 self.indent_current_nsp += 4
2432 self.indent_current_nsp += 4
2513 elif dedent_re.match(line):
2433 elif dedent_re.match(line):
2514 self.indent_current_nsp -= 4
2434 self.indent_current_nsp -= 4
2515 else:
2435 else:
2516 self.indent_current_nsp = 0
2436 self.indent_current_nsp = 0
2517
2437
2518 #-------------------------------------------------------------------------
2438 #-------------------------------------------------------------------------
2519 # Things related to GUI support and pylab
2439 # Things related to GUI support and pylab
2520 #-------------------------------------------------------------------------
2440 #-------------------------------------------------------------------------
2521
2441
2522 def enable_pylab(self, gui=None):
2442 def enable_pylab(self, gui=None):
2523 raise NotImplementedError('Implement enable_pylab in a subclass')
2443 raise NotImplementedError('Implement enable_pylab in a subclass')
2524
2444
2525 #-------------------------------------------------------------------------
2445 #-------------------------------------------------------------------------
2526 # Utilities
2446 # Utilities
2527 #-------------------------------------------------------------------------
2447 #-------------------------------------------------------------------------
2528
2448
2529 def var_expand(self,cmd,depth=0):
2449 def var_expand(self,cmd,depth=0):
2530 """Expand python variables in a string.
2450 """Expand python variables in a string.
2531
2451
2532 The depth argument indicates how many frames above the caller should
2452 The depth argument indicates how many frames above the caller should
2533 be walked to look for the local namespace where to expand variables.
2453 be walked to look for the local namespace where to expand variables.
2534
2454
2535 The global namespace for expansion is always the user's interactive
2455 The global namespace for expansion is always the user's interactive
2536 namespace.
2456 namespace.
2537 """
2457 """
2538
2458
2539 return str(ItplNS(cmd,
2459 return str(ItplNS(cmd,
2540 self.user_ns, # globals
2460 self.user_ns, # globals
2541 # Skip our own frame in searching for locals:
2461 # Skip our own frame in searching for locals:
2542 sys._getframe(depth+1).f_locals # locals
2462 sys._getframe(depth+1).f_locals # locals
2543 ))
2463 ))
2544
2464
2545 def mktempfile(self,data=None):
2465 def mktempfile(self,data=None):
2546 """Make a new tempfile and return its filename.
2466 """Make a new tempfile and return its filename.
2547
2467
2548 This makes a call to tempfile.mktemp, but it registers the created
2468 This makes a call to tempfile.mktemp, but it registers the created
2549 filename internally so ipython cleans it up at exit time.
2469 filename internally so ipython cleans it up at exit time.
2550
2470
2551 Optional inputs:
2471 Optional inputs:
2552
2472
2553 - data(None): if data is given, it gets written out to the temp file
2473 - data(None): if data is given, it gets written out to the temp file
2554 immediately, and the file is closed again."""
2474 immediately, and the file is closed again."""
2555
2475
2556 filename = tempfile.mktemp('.py','ipython_edit_')
2476 filename = tempfile.mktemp('.py','ipython_edit_')
2557 self.tempfiles.append(filename)
2477 self.tempfiles.append(filename)
2558
2478
2559 if data:
2479 if data:
2560 tmp_file = open(filename,'w')
2480 tmp_file = open(filename,'w')
2561 tmp_file.write(data)
2481 tmp_file.write(data)
2562 tmp_file.close()
2482 tmp_file.close()
2563 return filename
2483 return filename
2564
2484
2565 # TODO: This should be removed when Term is refactored.
2485 # TODO: This should be removed when Term is refactored.
2566 def write(self,data):
2486 def write(self,data):
2567 """Write a string to the default output"""
2487 """Write a string to the default output"""
2568 io.Term.cout.write(data)
2488 io.Term.cout.write(data)
2569
2489
2570 # TODO: This should be removed when Term is refactored.
2490 # TODO: This should be removed when Term is refactored.
2571 def write_err(self,data):
2491 def write_err(self,data):
2572 """Write a string to the default error output"""
2492 """Write a string to the default error output"""
2573 io.Term.cerr.write(data)
2493 io.Term.cerr.write(data)
2574
2494
2575 def ask_yes_no(self,prompt,default=True):
2495 def ask_yes_no(self,prompt,default=True):
2576 if self.quiet:
2496 if self.quiet:
2577 return True
2497 return True
2578 return ask_yes_no(prompt,default)
2498 return ask_yes_no(prompt,default)
2579
2499
2580 def show_usage(self):
2500 def show_usage(self):
2581 """Show a usage message"""
2501 """Show a usage message"""
2582 page.page(IPython.core.usage.interactive_usage)
2502 page.page(IPython.core.usage.interactive_usage)
2583
2503
2584 #-------------------------------------------------------------------------
2504 #-------------------------------------------------------------------------
2585 # Things related to IPython exiting
2505 # Things related to IPython exiting
2586 #-------------------------------------------------------------------------
2506 #-------------------------------------------------------------------------
2587 def atexit_operations(self):
2507 def atexit_operations(self):
2588 """This will be executed at the time of exit.
2508 """This will be executed at the time of exit.
2589
2509
2590 Cleanup operations and saving of persistent data that is done
2510 Cleanup operations and saving of persistent data that is done
2591 unconditionally by IPython should be performed here.
2511 unconditionally by IPython should be performed here.
2592
2512
2593 For things that may depend on startup flags or platform specifics (such
2513 For things that may depend on startup flags or platform specifics (such
2594 as having readline or not), register a separate atexit function in the
2514 as having readline or not), register a separate atexit function in the
2595 code that has the appropriate information, rather than trying to
2515 code that has the appropriate information, rather than trying to
2596 clutter
2516 clutter
2597 """
2517 """
2598 # Cleanup all tempfiles left around
2518 # Cleanup all tempfiles left around
2599 for tfile in self.tempfiles:
2519 for tfile in self.tempfiles:
2600 try:
2520 try:
2601 os.unlink(tfile)
2521 os.unlink(tfile)
2602 except OSError:
2522 except OSError:
2603 pass
2523 pass
2604
2524
2605 # Clear all user namespaces to release all references cleanly.
2525 # Clear all user namespaces to release all references cleanly.
2606 self.reset()
2526 self.reset()
2607
2527
2608 # Run user hooks
2528 # Run user hooks
2609 self.hooks.shutdown_hook()
2529 self.hooks.shutdown_hook()
2610
2530
2611 def cleanup(self):
2531 def cleanup(self):
2612 self.restore_sys_module_state()
2532 self.restore_sys_module_state()
2613
2533
2614
2534
2615 class InteractiveShellABC(object):
2535 class InteractiveShellABC(object):
2616 """An abstract base class for InteractiveShell."""
2536 """An abstract base class for InteractiveShell."""
2617 __metaclass__ = abc.ABCMeta
2537 __metaclass__ = abc.ABCMeta
2618
2538
2619 InteractiveShellABC.register(InteractiveShell)
2539 InteractiveShellABC.register(InteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now