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