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