##// END OF EJS Templates
Work again on bug 269966....
Fernando Perez -
Show More
@@ -0,0 +1,38 b''
1 """Minimal script to reproduce our nasty reference counting bug.
2
3 The problem is related to https://bugs.launchpad.net/ipython/+bug/269966
4
5 The original fix for that appeared to work, but JD Hunter found a matplotlib
6 example which, when run twice in a row, would break. The problem were
7 references held by open figures to internals of Tkinter.
8
9 This code reproduces the problem that John saw, without matplotlib. We can
10 thus use it for our test suite.
11 """
12
13 #-----------------------------------------------------------------------------
14 # Module imports
15 #-----------------------------------------------------------------------------
16 import sys
17
18 from IPython import ipapi
19
20 #-----------------------------------------------------------------------------
21 # Globals
22 #-----------------------------------------------------------------------------
23 ip = ipapi.get()
24
25 if not '_refbug_cache' in ip.user_ns:
26 ip.user_ns['_refbug_cache'] = []
27
28
29 aglobal = 'Hello'
30 def f():
31 return aglobal
32
33 cache = ip.user_ns['_refbug_cache']
34 cache.append(f)
35
36 def call_f():
37 for func in cache:
38 print 'lowercased:',func().lower()
@@ -0,0 +1,17 b''
1 """Tests for the FakeModule objects.
2 """
3
4 import nose.tools as nt
5
6 from IPython.FakeModule import FakeModule, init_fakemod_dict
7
8 # Make a fakemod and check a few properties
9 def test_mk_fakemod():
10 fm = FakeModule()
11 yield nt.assert_true,fm
12 yield nt.assert_true,lambda : hasattr(fm,'__file__')
13
14 def test_mk_fakemod_fromdict():
15 """Test making a FakeModule object with initial data"""
16 fm = FakeModule(dict(hello=True))
17 nt.assert_true(fm.hello)
@@ -1,42 +1,66 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Class which mimics a module.
4 4
5 5 Needed to allow pickle to correctly resolve namespaces during IPython
6 6 sessions.
7 7 """
8 8
9 9 #*****************************************************************************
10 10 # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu>
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #*****************************************************************************
15 15
16 16 import types
17 17
18 def init_fakemod_dict(fm,adict=None):
19 """Initialize a FakeModule instance __dict__.
20
21 Kept as a standalone function and not a method so the FakeModule API can
22 remain basically empty.
23
24 This should be considered for private IPython use, used in managing
25 namespaces for %run.
26
27 Parameters
28 ----------
29
30 fm : FakeModule instance
31
32 adict : dict, optional
33 """
34
35 dct = {}
36 # It seems pydoc (and perhaps others) needs any module instance to
37 # implement a __nonzero__ method, so we add it if missing:
38 dct.setdefault('__nonzero__',lambda : True)
39 dct.setdefault('__file__',__file__)
40
41 if adict is not None:
42 dct.update(adict)
43
44 # Hard assignment of the object's __dict__. This is nasty but deliberate.
45 fm.__dict__.clear()
46 fm.__dict__.update(dct)
47
48
18 49 class FakeModule(types.ModuleType):
19 50 """Simple class with attribute access to fake a module.
20 51
21 52 This is not meant to replace a module, but to allow inserting a fake
22 53 module in sys.modules so that systems which rely on run-time module
23 54 importing (like shelve and pickle) work correctly in interactive IPython
24 55 sessions.
25 56
26 57 Do NOT use this code for anything other than this IPython private hack."""
27 58
28 59 def __init__(self,adict=None):
29 60
30 61 # tmp to force __dict__ instance creation, else self.__dict__ fails
31 62 self.__iptmp = None
32
33 # It seems pydoc (and perhaps others) needs any module instance to
34 # implement a __nonzero__ method, so we add it if missing:
35 self.__dict__.setdefault('__nonzero__',lambda : True)
36 self.__dict__.setdefault('__file__',__file__)
37
38 63 # cleanup our temp trick
39 64 del self.__iptmp
40
41 if adict is not None:
42 self.__dict__.update(adict)
65 # Now, initialize the actual data in the instance dict.
66 init_fakemod_dict(self,adict)
@@ -1,3442 +1,3447 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #*****************************************************************************
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
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 # Modules and globals
15 15
16 16 # Python standard modules
17 17 import __builtin__
18 18 import bdb
19 19 import inspect
20 20 import os
21 21 import pdb
22 22 import pydoc
23 23 import sys
24 24 import re
25 25 import tempfile
26 26 import time
27 27 import cPickle as pickle
28 28 import textwrap
29 29 from cStringIO import StringIO
30 30 from getopt import getopt,GetoptError
31 31 from pprint import pprint, pformat
32 32
33 33 # cProfile was added in Python2.5
34 34 try:
35 35 import cProfile as profile
36 36 import pstats
37 37 except ImportError:
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 # Homebrewed
45 45 import IPython
46 46 from IPython import Debugger, OInspect, wildcard
47 47 from IPython.FakeModule import FakeModule
48 48 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 49 from IPython.PyColorize import Parser
50 50 from IPython.ipstruct import Struct
51 51 from IPython.macro import Macro
52 52 from IPython.genutils import *
53 53 from IPython import platutils
54 54 import IPython.generics
55 55 import IPython.ipapi
56 56 from IPython.ipapi import UsageError
57 57 from IPython.testing import decorators as testdec
58 58
59 59 #***************************************************************************
60 60 # Utility functions
61 61 def on_off(tag):
62 62 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
63 63 return ['OFF','ON'][tag]
64 64
65 65 class Bunch: pass
66 66
67 67 def compress_dhist(dh):
68 68 head, tail = dh[:-10], dh[-10:]
69 69
70 70 newhead = []
71 71 done = set()
72 72 for h in head:
73 73 if h in done:
74 74 continue
75 75 newhead.append(h)
76 76 done.add(h)
77 77
78 78 return newhead + tail
79 79
80 80
81 81 #***************************************************************************
82 82 # Main class implementing Magic functionality
83 83 class Magic:
84 84 """Magic functions for InteractiveShell.
85 85
86 86 Shell functions which can be reached as %function_name. All magic
87 87 functions should accept a string, which they can parse for their own
88 88 needs. This can make some functions easier to type, eg `%cd ../`
89 89 vs. `%cd("../")`
90 90
91 91 ALL definitions MUST begin with the prefix magic_. The user won't need it
92 92 at the command line, but it is is needed in the definition. """
93 93
94 94 # class globals
95 95 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
96 96 'Automagic is ON, % prefix NOT needed for magic functions.']
97 97
98 98 #......................................................................
99 99 # some utility functions
100 100
101 101 def __init__(self,shell):
102 102
103 103 self.options_table = {}
104 104 if profile is None:
105 105 self.magic_prun = self.profile_missing_notice
106 106 self.shell = shell
107 107
108 108 # namespace for holding state we may need
109 109 self._magic_state = Bunch()
110 110
111 111 def profile_missing_notice(self, *args, **kwargs):
112 112 error("""\
113 113 The profile module could not be found. It has been removed from the standard
114 114 python packages because of its non-free license. To use profiling, install the
115 115 python-profiler package from non-free.""")
116 116
117 117 def default_option(self,fn,optstr):
118 118 """Make an entry in the options_table for fn, with value optstr"""
119 119
120 120 if fn not in self.lsmagic():
121 121 error("%s is not a magic function" % fn)
122 122 self.options_table[fn] = optstr
123 123
124 124 def lsmagic(self):
125 125 """Return a list of currently available magic functions.
126 126
127 127 Gives a list of the bare names after mangling (['ls','cd', ...], not
128 128 ['magic_ls','magic_cd',...]"""
129 129
130 130 # FIXME. This needs a cleanup, in the way the magics list is built.
131 131
132 132 # magics in class definition
133 133 class_magic = lambda fn: fn.startswith('magic_') and \
134 134 callable(Magic.__dict__[fn])
135 135 # in instance namespace (run-time user additions)
136 136 inst_magic = lambda fn: fn.startswith('magic_') and \
137 137 callable(self.__dict__[fn])
138 138 # and bound magics by user (so they can access self):
139 139 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
140 140 callable(self.__class__.__dict__[fn])
141 141 magics = filter(class_magic,Magic.__dict__.keys()) + \
142 142 filter(inst_magic,self.__dict__.keys()) + \
143 143 filter(inst_bound_magic,self.__class__.__dict__.keys())
144 144 out = []
145 145 for fn in set(magics):
146 146 out.append(fn.replace('magic_','',1))
147 147 out.sort()
148 148 return out
149 149
150 150 def extract_input_slices(self,slices,raw=False):
151 151 """Return as a string a set of input history slices.
152 152
153 153 Inputs:
154 154
155 155 - slices: the set of slices is given as a list of strings (like
156 156 ['1','4:8','9'], since this function is for use by magic functions
157 157 which get their arguments as strings.
158 158
159 159 Optional inputs:
160 160
161 161 - raw(False): by default, the processed input is used. If this is
162 162 true, the raw input history is used instead.
163 163
164 164 Note that slices can be called with two notations:
165 165
166 166 N:M -> standard python form, means including items N...(M-1).
167 167
168 168 N-M -> include items N..M (closed endpoint)."""
169 169
170 170 if raw:
171 171 hist = self.shell.input_hist_raw
172 172 else:
173 173 hist = self.shell.input_hist
174 174
175 175 cmds = []
176 176 for chunk in slices:
177 177 if ':' in chunk:
178 178 ini,fin = map(int,chunk.split(':'))
179 179 elif '-' in chunk:
180 180 ini,fin = map(int,chunk.split('-'))
181 181 fin += 1
182 182 else:
183 183 ini = int(chunk)
184 184 fin = ini+1
185 185 cmds.append(hist[ini:fin])
186 186 return cmds
187 187
188 188 def _ofind(self, oname, namespaces=None):
189 189 """Find an object in the available namespaces.
190 190
191 191 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
192 192
193 193 Has special code to detect magic functions.
194 194 """
195 195
196 196 oname = oname.strip()
197 197
198 198 alias_ns = None
199 199 if namespaces is None:
200 200 # Namespaces to search in:
201 201 # Put them in a list. The order is important so that we
202 202 # find things in the same order that Python finds them.
203 203 namespaces = [ ('Interactive', self.shell.user_ns),
204 204 ('IPython internal', self.shell.internal_ns),
205 205 ('Python builtin', __builtin__.__dict__),
206 206 ('Alias', self.shell.alias_table),
207 207 ]
208 208 alias_ns = self.shell.alias_table
209 209
210 210 # initialize results to 'null'
211 211 found = 0; obj = None; ospace = None; ds = None;
212 212 ismagic = 0; isalias = 0; parent = None
213 213
214 214 # Look for the given name by splitting it in parts. If the head is
215 215 # found, then we look for all the remaining parts as members, and only
216 216 # declare success if we can find them all.
217 217 oname_parts = oname.split('.')
218 218 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
219 219 for nsname,ns in namespaces:
220 220 try:
221 221 obj = ns[oname_head]
222 222 except KeyError:
223 223 continue
224 224 else:
225 225 #print 'oname_rest:', oname_rest # dbg
226 226 for part in oname_rest:
227 227 try:
228 228 parent = obj
229 229 obj = getattr(obj,part)
230 230 except:
231 231 # Blanket except b/c some badly implemented objects
232 232 # allow __getattr__ to raise exceptions other than
233 233 # AttributeError, which then crashes IPython.
234 234 break
235 235 else:
236 236 # If we finish the for loop (no break), we got all members
237 237 found = 1
238 238 ospace = nsname
239 239 if ns == alias_ns:
240 240 isalias = 1
241 241 break # namespace loop
242 242
243 243 # Try to see if it's magic
244 244 if not found:
245 245 if oname.startswith(self.shell.ESC_MAGIC):
246 246 oname = oname[1:]
247 247 obj = getattr(self,'magic_'+oname,None)
248 248 if obj is not None:
249 249 found = 1
250 250 ospace = 'IPython internal'
251 251 ismagic = 1
252 252
253 253 # Last try: special-case some literals like '', [], {}, etc:
254 254 if not found and oname_head in ["''",'""','[]','{}','()']:
255 255 obj = eval(oname_head)
256 256 found = 1
257 257 ospace = 'Interactive'
258 258
259 259 return {'found':found, 'obj':obj, 'namespace':ospace,
260 260 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
261 261
262 262 def arg_err(self,func):
263 263 """Print docstring if incorrect arguments were passed"""
264 264 print 'Error in arguments:'
265 265 print OInspect.getdoc(func)
266 266
267 267 def format_latex(self,strng):
268 268 """Format a string for latex inclusion."""
269 269
270 270 # Characters that need to be escaped for latex:
271 271 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
272 272 # Magic command names as headers:
273 273 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
274 274 re.MULTILINE)
275 275 # Magic commands
276 276 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
277 277 re.MULTILINE)
278 278 # Paragraph continue
279 279 par_re = re.compile(r'\\$',re.MULTILINE)
280 280
281 281 # The "\n" symbol
282 282 newline_re = re.compile(r'\\n')
283 283
284 284 # Now build the string for output:
285 285 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
286 286 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
287 287 strng)
288 288 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
289 289 strng = par_re.sub(r'\\\\',strng)
290 290 strng = escape_re.sub(r'\\\1',strng)
291 291 strng = newline_re.sub(r'\\textbackslash{}n',strng)
292 292 return strng
293 293
294 294 def format_screen(self,strng):
295 295 """Format a string for screen printing.
296 296
297 297 This removes some latex-type format codes."""
298 298 # Paragraph continue
299 299 par_re = re.compile(r'\\$',re.MULTILINE)
300 300 strng = par_re.sub('',strng)
301 301 return strng
302 302
303 303 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
304 304 """Parse options passed to an argument string.
305 305
306 306 The interface is similar to that of getopt(), but it returns back a
307 307 Struct with the options as keys and the stripped argument string still
308 308 as a string.
309 309
310 310 arg_str is quoted as a true sys.argv vector by using shlex.split.
311 311 This allows us to easily expand variables, glob files, quote
312 312 arguments, etc.
313 313
314 314 Options:
315 315 -mode: default 'string'. If given as 'list', the argument string is
316 316 returned as a list (split on whitespace) instead of a string.
317 317
318 318 -list_all: put all option values in lists. Normally only options
319 319 appearing more than once are put in a list.
320 320
321 321 -posix (True): whether to split the input line in POSIX mode or not,
322 322 as per the conventions outlined in the shlex module from the
323 323 standard library."""
324 324
325 325 # inject default options at the beginning of the input line
326 326 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
327 327 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
328 328
329 329 mode = kw.get('mode','string')
330 330 if mode not in ['string','list']:
331 331 raise ValueError,'incorrect mode given: %s' % mode
332 332 # Get options
333 333 list_all = kw.get('list_all',0)
334 334 posix = kw.get('posix',True)
335 335
336 336 # Check if we have more than one argument to warrant extra processing:
337 337 odict = {} # Dictionary with options
338 338 args = arg_str.split()
339 339 if len(args) >= 1:
340 340 # If the list of inputs only has 0 or 1 thing in it, there's no
341 341 # need to look for options
342 342 argv = arg_split(arg_str,posix)
343 343 # Do regular option processing
344 344 try:
345 345 opts,args = getopt(argv,opt_str,*long_opts)
346 346 except GetoptError,e:
347 347 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
348 348 " ".join(long_opts)))
349 349 for o,a in opts:
350 350 if o.startswith('--'):
351 351 o = o[2:]
352 352 else:
353 353 o = o[1:]
354 354 try:
355 355 odict[o].append(a)
356 356 except AttributeError:
357 357 odict[o] = [odict[o],a]
358 358 except KeyError:
359 359 if list_all:
360 360 odict[o] = [a]
361 361 else:
362 362 odict[o] = a
363 363
364 364 # Prepare opts,args for return
365 365 opts = Struct(odict)
366 366 if mode == 'string':
367 367 args = ' '.join(args)
368 368
369 369 return opts,args
370 370
371 371 #......................................................................
372 372 # And now the actual magic functions
373 373
374 374 # Functions for IPython shell work (vars,funcs, config, etc)
375 375 def magic_lsmagic(self, parameter_s = ''):
376 376 """List currently available magic functions."""
377 377 mesc = self.shell.ESC_MAGIC
378 378 print 'Available magic functions:\n'+mesc+\
379 379 (' '+mesc).join(self.lsmagic())
380 380 print '\n' + Magic.auto_status[self.shell.rc.automagic]
381 381 return None
382 382
383 383 def magic_magic(self, parameter_s = ''):
384 384 """Print information about the magic function system.
385 385
386 386 Supported formats: -latex, -brief, -rest
387 387 """
388 388
389 389 mode = ''
390 390 try:
391 391 if parameter_s.split()[0] == '-latex':
392 392 mode = 'latex'
393 393 if parameter_s.split()[0] == '-brief':
394 394 mode = 'brief'
395 395 if parameter_s.split()[0] == '-rest':
396 396 mode = 'rest'
397 397 rest_docs = []
398 398 except:
399 399 pass
400 400
401 401 magic_docs = []
402 402 for fname in self.lsmagic():
403 403 mname = 'magic_' + fname
404 404 for space in (Magic,self,self.__class__):
405 405 try:
406 406 fn = space.__dict__[mname]
407 407 except KeyError:
408 408 pass
409 409 else:
410 410 break
411 411 if mode == 'brief':
412 412 # only first line
413 413 if fn.__doc__:
414 414 fndoc = fn.__doc__.split('\n',1)[0]
415 415 else:
416 416 fndoc = 'No documentation'
417 417 else:
418 418 if fn.__doc__:
419 419 fndoc = fn.__doc__.rstrip()
420 420 else:
421 421 fndoc = 'No documentation'
422 422
423 423
424 424 if mode == 'rest':
425 425 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
426 426 fname,fndoc))
427 427
428 428 else:
429 429 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
430 430 fname,fndoc))
431 431
432 432 magic_docs = ''.join(magic_docs)
433 433
434 434 if mode == 'rest':
435 435 return "".join(rest_docs)
436 436
437 437 if mode == 'latex':
438 438 print self.format_latex(magic_docs)
439 439 return
440 440 else:
441 441 magic_docs = self.format_screen(magic_docs)
442 442 if mode == 'brief':
443 443 return magic_docs
444 444
445 445 outmsg = """
446 446 IPython's 'magic' functions
447 447 ===========================
448 448
449 449 The magic function system provides a series of functions which allow you to
450 450 control the behavior of IPython itself, plus a lot of system-type
451 451 features. All these functions are prefixed with a % character, but parameters
452 452 are given without parentheses or quotes.
453 453
454 454 NOTE: If you have 'automagic' enabled (via the command line option or with the
455 455 %automagic function), you don't need to type in the % explicitly. By default,
456 456 IPython ships with automagic on, so you should only rarely need the % escape.
457 457
458 458 Example: typing '%cd mydir' (without the quotes) changes you working directory
459 459 to 'mydir', if it exists.
460 460
461 461 You can define your own magic functions to extend the system. See the supplied
462 462 ipythonrc and example-magic.py files for details (in your ipython
463 463 configuration directory, typically $HOME/.ipython/).
464 464
465 465 You can also define your own aliased names for magic functions. In your
466 466 ipythonrc file, placing a line like:
467 467
468 468 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
469 469
470 470 will define %pf as a new name for %profile.
471 471
472 472 You can also call magics in code using the ipmagic() function, which IPython
473 473 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
474 474
475 475 For a list of the available magic functions, use %lsmagic. For a description
476 476 of any of them, type %magic_name?, e.g. '%cd?'.
477 477
478 478 Currently the magic system has the following functions:\n"""
479 479
480 480 mesc = self.shell.ESC_MAGIC
481 481 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
482 482 "\n\n%s%s\n\n%s" % (outmsg,
483 483 magic_docs,mesc,mesc,
484 484 (' '+mesc).join(self.lsmagic()),
485 485 Magic.auto_status[self.shell.rc.automagic] ) )
486 486
487 487 page(outmsg,screen_lines=self.shell.rc.screen_length)
488 488
489 489
490 490 def magic_autoindent(self, parameter_s = ''):
491 491 """Toggle autoindent on/off (if available)."""
492 492
493 493 self.shell.set_autoindent()
494 494 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
495 495
496 496
497 497 def magic_automagic(self, parameter_s = ''):
498 498 """Make magic functions callable without having to type the initial %.
499 499
500 500 Without argumentsl toggles on/off (when off, you must call it as
501 501 %automagic, of course). With arguments it sets the value, and you can
502 502 use any of (case insensitive):
503 503
504 504 - on,1,True: to activate
505 505
506 506 - off,0,False: to deactivate.
507 507
508 508 Note that magic functions have lowest priority, so if there's a
509 509 variable whose name collides with that of a magic fn, automagic won't
510 510 work for that function (you get the variable instead). However, if you
511 511 delete the variable (del var), the previously shadowed magic function
512 512 becomes visible to automagic again."""
513 513
514 514 rc = self.shell.rc
515 515 arg = parameter_s.lower()
516 516 if parameter_s in ('on','1','true'):
517 517 rc.automagic = True
518 518 elif parameter_s in ('off','0','false'):
519 519 rc.automagic = False
520 520 else:
521 521 rc.automagic = not rc.automagic
522 522 print '\n' + Magic.auto_status[rc.automagic]
523 523
524 524 @testdec.skip_doctest
525 525 def magic_autocall(self, parameter_s = ''):
526 526 """Make functions callable without having to type parentheses.
527 527
528 528 Usage:
529 529
530 530 %autocall [mode]
531 531
532 532 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
533 533 value is toggled on and off (remembering the previous state).
534 534
535 535 In more detail, these values mean:
536 536
537 537 0 -> fully disabled
538 538
539 539 1 -> active, but do not apply if there are no arguments on the line.
540 540
541 541 In this mode, you get:
542 542
543 543 In [1]: callable
544 544 Out[1]: <built-in function callable>
545 545
546 546 In [2]: callable 'hello'
547 547 ------> callable('hello')
548 548 Out[2]: False
549 549
550 550 2 -> Active always. Even if no arguments are present, the callable
551 551 object is called:
552 552
553 553 In [2]: float
554 554 ------> float()
555 555 Out[2]: 0.0
556 556
557 557 Note that even with autocall off, you can still use '/' at the start of
558 558 a line to treat the first argument on the command line as a function
559 559 and add parentheses to it:
560 560
561 561 In [8]: /str 43
562 562 ------> str(43)
563 563 Out[8]: '43'
564 564
565 565 # all-random (note for auto-testing)
566 566 """
567 567
568 568 rc = self.shell.rc
569 569
570 570 if parameter_s:
571 571 arg = int(parameter_s)
572 572 else:
573 573 arg = 'toggle'
574 574
575 575 if not arg in (0,1,2,'toggle'):
576 576 error('Valid modes: (0->Off, 1->Smart, 2->Full')
577 577 return
578 578
579 579 if arg in (0,1,2):
580 580 rc.autocall = arg
581 581 else: # toggle
582 582 if rc.autocall:
583 583 self._magic_state.autocall_save = rc.autocall
584 584 rc.autocall = 0
585 585 else:
586 586 try:
587 587 rc.autocall = self._magic_state.autocall_save
588 588 except AttributeError:
589 589 rc.autocall = self._magic_state.autocall_save = 1
590 590
591 591 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
592 592
593 593 def magic_system_verbose(self, parameter_s = ''):
594 594 """Set verbose printing of system calls.
595 595
596 596 If called without an argument, act as a toggle"""
597 597
598 598 if parameter_s:
599 599 val = bool(eval(parameter_s))
600 600 else:
601 601 val = None
602 602
603 603 self.shell.rc_set_toggle('system_verbose',val)
604 604 print "System verbose printing is:",\
605 605 ['OFF','ON'][self.shell.rc.system_verbose]
606 606
607 607
608 608 def magic_page(self, parameter_s=''):
609 609 """Pretty print the object and display it through a pager.
610 610
611 611 %page [options] OBJECT
612 612
613 613 If no object is given, use _ (last output).
614 614
615 615 Options:
616 616
617 617 -r: page str(object), don't pretty-print it."""
618 618
619 619 # After a function contributed by Olivier Aubert, slightly modified.
620 620
621 621 # Process options/args
622 622 opts,args = self.parse_options(parameter_s,'r')
623 623 raw = 'r' in opts
624 624
625 625 oname = args and args or '_'
626 626 info = self._ofind(oname)
627 627 if info['found']:
628 628 txt = (raw and str or pformat)( info['obj'] )
629 629 page(txt)
630 630 else:
631 631 print 'Object `%s` not found' % oname
632 632
633 633 def magic_profile(self, parameter_s=''):
634 634 """Print your currently active IPyhton profile."""
635 635 if self.shell.rc.profile:
636 636 printpl('Current IPython profile: $self.shell.rc.profile.')
637 637 else:
638 638 print 'No profile active.'
639 639
640 640 def magic_pinfo(self, parameter_s='', namespaces=None):
641 641 """Provide detailed information about an object.
642 642
643 643 '%pinfo object' is just a synonym for object? or ?object."""
644 644
645 645 #print 'pinfo par: <%s>' % parameter_s # dbg
646 646
647 647
648 648 # detail_level: 0 -> obj? , 1 -> obj??
649 649 detail_level = 0
650 650 # We need to detect if we got called as 'pinfo pinfo foo', which can
651 651 # happen if the user types 'pinfo foo?' at the cmd line.
652 652 pinfo,qmark1,oname,qmark2 = \
653 653 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
654 654 if pinfo or qmark1 or qmark2:
655 655 detail_level = 1
656 656 if "*" in oname:
657 657 self.magic_psearch(oname)
658 658 else:
659 659 self._inspect('pinfo', oname, detail_level=detail_level,
660 660 namespaces=namespaces)
661 661
662 662 def magic_pdef(self, parameter_s='', namespaces=None):
663 663 """Print the definition header for any callable object.
664 664
665 665 If the object is a class, print the constructor information."""
666 666 self._inspect('pdef',parameter_s, namespaces)
667 667
668 668 def magic_pdoc(self, parameter_s='', namespaces=None):
669 669 """Print the docstring for an object.
670 670
671 671 If the given object is a class, it will print both the class and the
672 672 constructor docstrings."""
673 673 self._inspect('pdoc',parameter_s, namespaces)
674 674
675 675 def magic_psource(self, parameter_s='', namespaces=None):
676 676 """Print (or run through pager) the source code for an object."""
677 677 self._inspect('psource',parameter_s, namespaces)
678 678
679 679 def magic_pfile(self, parameter_s=''):
680 680 """Print (or run through pager) the file where an object is defined.
681 681
682 682 The file opens at the line where the object definition begins. IPython
683 683 will honor the environment variable PAGER if set, and otherwise will
684 684 do its best to print the file in a convenient form.
685 685
686 686 If the given argument is not an object currently defined, IPython will
687 687 try to interpret it as a filename (automatically adding a .py extension
688 688 if needed). You can thus use %pfile as a syntax highlighting code
689 689 viewer."""
690 690
691 691 # first interpret argument as an object name
692 692 out = self._inspect('pfile',parameter_s)
693 693 # if not, try the input as a filename
694 694 if out == 'not found':
695 695 try:
696 696 filename = get_py_filename(parameter_s)
697 697 except IOError,msg:
698 698 print msg
699 699 return
700 700 page(self.shell.inspector.format(file(filename).read()))
701 701
702 702 def _inspect(self,meth,oname,namespaces=None,**kw):
703 703 """Generic interface to the inspector system.
704 704
705 705 This function is meant to be called by pdef, pdoc & friends."""
706 706
707 707 #oname = oname.strip()
708 708 #print '1- oname: <%r>' % oname # dbg
709 709 try:
710 710 oname = oname.strip().encode('ascii')
711 711 #print '2- oname: <%r>' % oname # dbg
712 712 except UnicodeEncodeError:
713 713 print 'Python identifiers can only contain ascii characters.'
714 714 return 'not found'
715 715
716 716 info = Struct(self._ofind(oname, namespaces))
717 717
718 718 if info.found:
719 719 try:
720 720 IPython.generics.inspect_object(info.obj)
721 721 return
722 722 except IPython.ipapi.TryNext:
723 723 pass
724 724 # Get the docstring of the class property if it exists.
725 725 path = oname.split('.')
726 726 root = '.'.join(path[:-1])
727 727 if info.parent is not None:
728 728 try:
729 729 target = getattr(info.parent, '__class__')
730 730 # The object belongs to a class instance.
731 731 try:
732 732 target = getattr(target, path[-1])
733 733 # The class defines the object.
734 734 if isinstance(target, property):
735 735 oname = root + '.__class__.' + path[-1]
736 736 info = Struct(self._ofind(oname))
737 737 except AttributeError: pass
738 738 except AttributeError: pass
739 739
740 740 pmethod = getattr(self.shell.inspector,meth)
741 741 formatter = info.ismagic and self.format_screen or None
742 742 if meth == 'pdoc':
743 743 pmethod(info.obj,oname,formatter)
744 744 elif meth == 'pinfo':
745 745 pmethod(info.obj,oname,formatter,info,**kw)
746 746 else:
747 747 pmethod(info.obj,oname)
748 748 else:
749 749 print 'Object `%s` not found.' % oname
750 750 return 'not found' # so callers can take other action
751 751
752 752 def magic_psearch(self, parameter_s=''):
753 753 """Search for object in namespaces by wildcard.
754 754
755 755 %psearch [options] PATTERN [OBJECT TYPE]
756 756
757 757 Note: ? can be used as a synonym for %psearch, at the beginning or at
758 758 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
759 759 rest of the command line must be unchanged (options come first), so
760 760 for example the following forms are equivalent
761 761
762 762 %psearch -i a* function
763 763 -i a* function?
764 764 ?-i a* function
765 765
766 766 Arguments:
767 767
768 768 PATTERN
769 769
770 770 where PATTERN is a string containing * as a wildcard similar to its
771 771 use in a shell. The pattern is matched in all namespaces on the
772 772 search path. By default objects starting with a single _ are not
773 773 matched, many IPython generated objects have a single
774 774 underscore. The default is case insensitive matching. Matching is
775 775 also done on the attributes of objects and not only on the objects
776 776 in a module.
777 777
778 778 [OBJECT TYPE]
779 779
780 780 Is the name of a python type from the types module. The name is
781 781 given in lowercase without the ending type, ex. StringType is
782 782 written string. By adding a type here only objects matching the
783 783 given type are matched. Using all here makes the pattern match all
784 784 types (this is the default).
785 785
786 786 Options:
787 787
788 788 -a: makes the pattern match even objects whose names start with a
789 789 single underscore. These names are normally ommitted from the
790 790 search.
791 791
792 792 -i/-c: make the pattern case insensitive/sensitive. If neither of
793 793 these options is given, the default is read from your ipythonrc
794 794 file. The option name which sets this value is
795 795 'wildcards_case_sensitive'. If this option is not specified in your
796 796 ipythonrc file, IPython's internal default is to do a case sensitive
797 797 search.
798 798
799 799 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
800 800 specifiy can be searched in any of the following namespaces:
801 801 'builtin', 'user', 'user_global','internal', 'alias', where
802 802 'builtin' and 'user' are the search defaults. Note that you should
803 803 not use quotes when specifying namespaces.
804 804
805 805 'Builtin' contains the python module builtin, 'user' contains all
806 806 user data, 'alias' only contain the shell aliases and no python
807 807 objects, 'internal' contains objects used by IPython. The
808 808 'user_global' namespace is only used by embedded IPython instances,
809 809 and it contains module-level globals. You can add namespaces to the
810 810 search with -s or exclude them with -e (these options can be given
811 811 more than once).
812 812
813 813 Examples:
814 814
815 815 %psearch a* -> objects beginning with an a
816 816 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
817 817 %psearch a* function -> all functions beginning with an a
818 818 %psearch re.e* -> objects beginning with an e in module re
819 819 %psearch r*.e* -> objects that start with e in modules starting in r
820 820 %psearch r*.* string -> all strings in modules beginning with r
821 821
822 822 Case sensitve search:
823 823
824 824 %psearch -c a* list all object beginning with lower case a
825 825
826 826 Show objects beginning with a single _:
827 827
828 828 %psearch -a _* list objects beginning with a single underscore"""
829 829 try:
830 830 parameter_s = parameter_s.encode('ascii')
831 831 except UnicodeEncodeError:
832 832 print 'Python identifiers can only contain ascii characters.'
833 833 return
834 834
835 835 # default namespaces to be searched
836 836 def_search = ['user','builtin']
837 837
838 838 # Process options/args
839 839 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
840 840 opt = opts.get
841 841 shell = self.shell
842 842 psearch = shell.inspector.psearch
843 843
844 844 # select case options
845 845 if opts.has_key('i'):
846 846 ignore_case = True
847 847 elif opts.has_key('c'):
848 848 ignore_case = False
849 849 else:
850 850 ignore_case = not shell.rc.wildcards_case_sensitive
851 851
852 852 # Build list of namespaces to search from user options
853 853 def_search.extend(opt('s',[]))
854 854 ns_exclude = ns_exclude=opt('e',[])
855 855 ns_search = [nm for nm in def_search if nm not in ns_exclude]
856 856
857 857 # Call the actual search
858 858 try:
859 859 psearch(args,shell.ns_table,ns_search,
860 860 show_all=opt('a'),ignore_case=ignore_case)
861 861 except:
862 862 shell.showtraceback()
863 863
864 864 def magic_who_ls(self, parameter_s=''):
865 865 """Return a sorted list of all interactive variables.
866 866
867 867 If arguments are given, only variables of types matching these
868 868 arguments are returned."""
869 869
870 870 user_ns = self.shell.user_ns
871 871 internal_ns = self.shell.internal_ns
872 872 user_config_ns = self.shell.user_config_ns
873 873 out = []
874 874 typelist = parameter_s.split()
875 875
876 876 for i in user_ns:
877 877 if not (i.startswith('_') or i.startswith('_i')) \
878 878 and not (i in internal_ns or i in user_config_ns):
879 879 if typelist:
880 880 if type(user_ns[i]).__name__ in typelist:
881 881 out.append(i)
882 882 else:
883 883 out.append(i)
884 884 out.sort()
885 885 return out
886 886
887 887 def magic_who(self, parameter_s=''):
888 888 """Print all interactive variables, with some minimal formatting.
889 889
890 890 If any arguments are given, only variables whose type matches one of
891 891 these are printed. For example:
892 892
893 893 %who function str
894 894
895 895 will only list functions and strings, excluding all other types of
896 896 variables. To find the proper type names, simply use type(var) at a
897 897 command line to see how python prints type names. For example:
898 898
899 899 In [1]: type('hello')\\
900 900 Out[1]: <type 'str'>
901 901
902 902 indicates that the type name for strings is 'str'.
903 903
904 904 %who always excludes executed names loaded through your configuration
905 905 file and things which are internal to IPython.
906 906
907 907 This is deliberate, as typically you may load many modules and the
908 908 purpose of %who is to show you only what you've manually defined."""
909 909
910 910 varlist = self.magic_who_ls(parameter_s)
911 911 if not varlist:
912 912 if parameter_s:
913 913 print 'No variables match your requested type.'
914 914 else:
915 915 print 'Interactive namespace is empty.'
916 916 return
917 917
918 918 # if we have variables, move on...
919 919 count = 0
920 920 for i in varlist:
921 921 print i+'\t',
922 922 count += 1
923 923 if count > 8:
924 924 count = 0
925 925 print
926 926 print
927 927
928 928 def magic_whos(self, parameter_s=''):
929 929 """Like %who, but gives some extra information about each variable.
930 930
931 931 The same type filtering of %who can be applied here.
932 932
933 933 For all variables, the type is printed. Additionally it prints:
934 934
935 935 - For {},[],(): their length.
936 936
937 937 - For numpy and Numeric arrays, a summary with shape, number of
938 938 elements, typecode and size in memory.
939 939
940 940 - Everything else: a string representation, snipping their middle if
941 941 too long."""
942 942
943 943 varnames = self.magic_who_ls(parameter_s)
944 944 if not varnames:
945 945 if parameter_s:
946 946 print 'No variables match your requested type.'
947 947 else:
948 948 print 'Interactive namespace is empty.'
949 949 return
950 950
951 951 # if we have variables, move on...
952 952
953 953 # for these types, show len() instead of data:
954 954 seq_types = [types.DictType,types.ListType,types.TupleType]
955 955
956 956 # for numpy/Numeric arrays, display summary info
957 957 try:
958 958 import numpy
959 959 except ImportError:
960 960 ndarray_type = None
961 961 else:
962 962 ndarray_type = numpy.ndarray.__name__
963 963 try:
964 964 import Numeric
965 965 except ImportError:
966 966 array_type = None
967 967 else:
968 968 array_type = Numeric.ArrayType.__name__
969 969
970 970 # Find all variable names and types so we can figure out column sizes
971 971 def get_vars(i):
972 972 return self.shell.user_ns[i]
973 973
974 974 # some types are well known and can be shorter
975 975 abbrevs = {'IPython.macro.Macro' : 'Macro'}
976 976 def type_name(v):
977 977 tn = type(v).__name__
978 978 return abbrevs.get(tn,tn)
979 979
980 980 varlist = map(get_vars,varnames)
981 981
982 982 typelist = []
983 983 for vv in varlist:
984 984 tt = type_name(vv)
985 985
986 986 if tt=='instance':
987 987 typelist.append( abbrevs.get(str(vv.__class__),
988 988 str(vv.__class__)))
989 989 else:
990 990 typelist.append(tt)
991 991
992 992 # column labels and # of spaces as separator
993 993 varlabel = 'Variable'
994 994 typelabel = 'Type'
995 995 datalabel = 'Data/Info'
996 996 colsep = 3
997 997 # variable format strings
998 998 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
999 999 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1000 1000 aformat = "%s: %s elems, type `%s`, %s bytes"
1001 1001 # find the size of the columns to format the output nicely
1002 1002 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1003 1003 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1004 1004 # table header
1005 1005 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1006 1006 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1007 1007 # and the table itself
1008 1008 kb = 1024
1009 1009 Mb = 1048576 # kb**2
1010 1010 for vname,var,vtype in zip(varnames,varlist,typelist):
1011 1011 print itpl(vformat),
1012 1012 if vtype in seq_types:
1013 1013 print len(var)
1014 1014 elif vtype in [array_type,ndarray_type]:
1015 1015 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1016 1016 if vtype==ndarray_type:
1017 1017 # numpy
1018 1018 vsize = var.size
1019 1019 vbytes = vsize*var.itemsize
1020 1020 vdtype = var.dtype
1021 1021 else:
1022 1022 # Numeric
1023 1023 vsize = Numeric.size(var)
1024 1024 vbytes = vsize*var.itemsize()
1025 1025 vdtype = var.typecode()
1026 1026
1027 1027 if vbytes < 100000:
1028 1028 print aformat % (vshape,vsize,vdtype,vbytes)
1029 1029 else:
1030 1030 print aformat % (vshape,vsize,vdtype,vbytes),
1031 1031 if vbytes < Mb:
1032 1032 print '(%s kb)' % (vbytes/kb,)
1033 1033 else:
1034 1034 print '(%s Mb)' % (vbytes/Mb,)
1035 1035 else:
1036 1036 try:
1037 1037 vstr = str(var)
1038 1038 except UnicodeEncodeError:
1039 1039 vstr = unicode(var).encode(sys.getdefaultencoding(),
1040 1040 'backslashreplace')
1041 1041 vstr = vstr.replace('\n','\\n')
1042 1042 if len(vstr) < 50:
1043 1043 print vstr
1044 1044 else:
1045 1045 printpl(vfmt_short)
1046 1046
1047 1047 def magic_reset(self, parameter_s=''):
1048 1048 """Resets the namespace by removing all names defined by the user.
1049 1049
1050 1050 Input/Output history are left around in case you need them.
1051 1051
1052 1052 Parameters
1053 1053 ----------
1054 1054 -y : force reset without asking for confirmation.
1055 1055
1056 1056 Examples
1057 1057 --------
1058 1058 In [6]: a = 1
1059 1059
1060 1060 In [7]: a
1061 1061 Out[7]: 1
1062 1062
1063 1063 In [8]: 'a' in _ip.user_ns
1064 1064 Out[8]: True
1065 1065
1066 1066 In [9]: %reset -f
1067 1067
1068 1068 In [10]: 'a' in _ip.user_ns
1069 1069 Out[10]: False
1070 1070 """
1071 1071
1072 1072 if parameter_s == '-f':
1073 1073 ans = True
1074 1074 else:
1075 1075 ans = self.shell.ask_yes_no(
1076 1076 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1077 1077 if not ans:
1078 1078 print 'Nothing done.'
1079 1079 return
1080 1080 user_ns = self.shell.user_ns
1081 1081 for i in self.magic_who_ls():
1082 1082 del(user_ns[i])
1083 1083
1084 1084 # Also flush the private list of module references kept for script
1085 1085 # execution protection
1086 1086 self.shell.clear_main_mod_cache()
1087 1087
1088 1088 def magic_logstart(self,parameter_s=''):
1089 1089 """Start logging anywhere in a session.
1090 1090
1091 1091 %logstart [-o|-r|-t] [log_name [log_mode]]
1092 1092
1093 1093 If no name is given, it defaults to a file named 'ipython_log.py' in your
1094 1094 current directory, in 'rotate' mode (see below).
1095 1095
1096 1096 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1097 1097 history up to that point and then continues logging.
1098 1098
1099 1099 %logstart takes a second optional parameter: logging mode. This can be one
1100 1100 of (note that the modes are given unquoted):\\
1101 1101 append: well, that says it.\\
1102 1102 backup: rename (if exists) to name~ and start name.\\
1103 1103 global: single logfile in your home dir, appended to.\\
1104 1104 over : overwrite existing log.\\
1105 1105 rotate: create rotating logs name.1~, name.2~, etc.
1106 1106
1107 1107 Options:
1108 1108
1109 1109 -o: log also IPython's output. In this mode, all commands which
1110 1110 generate an Out[NN] prompt are recorded to the logfile, right after
1111 1111 their corresponding input line. The output lines are always
1112 1112 prepended with a '#[Out]# ' marker, so that the log remains valid
1113 1113 Python code.
1114 1114
1115 1115 Since this marker is always the same, filtering only the output from
1116 1116 a log is very easy, using for example a simple awk call:
1117 1117
1118 1118 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1119 1119
1120 1120 -r: log 'raw' input. Normally, IPython's logs contain the processed
1121 1121 input, so that user lines are logged in their final form, converted
1122 1122 into valid Python. For example, %Exit is logged as
1123 1123 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1124 1124 exactly as typed, with no transformations applied.
1125 1125
1126 1126 -t: put timestamps before each input line logged (these are put in
1127 1127 comments)."""
1128 1128
1129 1129 opts,par = self.parse_options(parameter_s,'ort')
1130 1130 log_output = 'o' in opts
1131 1131 log_raw_input = 'r' in opts
1132 1132 timestamp = 't' in opts
1133 1133
1134 1134 rc = self.shell.rc
1135 1135 logger = self.shell.logger
1136 1136
1137 1137 # if no args are given, the defaults set in the logger constructor by
1138 1138 # ipytohn remain valid
1139 1139 if par:
1140 1140 try:
1141 1141 logfname,logmode = par.split()
1142 1142 except:
1143 1143 logfname = par
1144 1144 logmode = 'backup'
1145 1145 else:
1146 1146 logfname = logger.logfname
1147 1147 logmode = logger.logmode
1148 1148 # put logfname into rc struct as if it had been called on the command
1149 1149 # line, so it ends up saved in the log header Save it in case we need
1150 1150 # to restore it...
1151 1151 old_logfile = rc.opts.get('logfile','')
1152 1152 if logfname:
1153 1153 logfname = os.path.expanduser(logfname)
1154 1154 rc.opts.logfile = logfname
1155 1155 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1156 1156 try:
1157 1157 started = logger.logstart(logfname,loghead,logmode,
1158 1158 log_output,timestamp,log_raw_input)
1159 1159 except:
1160 1160 rc.opts.logfile = old_logfile
1161 1161 warn("Couldn't start log: %s" % sys.exc_info()[1])
1162 1162 else:
1163 1163 # log input history up to this point, optionally interleaving
1164 1164 # output if requested
1165 1165
1166 1166 if timestamp:
1167 1167 # disable timestamping for the previous history, since we've
1168 1168 # lost those already (no time machine here).
1169 1169 logger.timestamp = False
1170 1170
1171 1171 if log_raw_input:
1172 1172 input_hist = self.shell.input_hist_raw
1173 1173 else:
1174 1174 input_hist = self.shell.input_hist
1175 1175
1176 1176 if log_output:
1177 1177 log_write = logger.log_write
1178 1178 output_hist = self.shell.output_hist
1179 1179 for n in range(1,len(input_hist)-1):
1180 1180 log_write(input_hist[n].rstrip())
1181 1181 if n in output_hist:
1182 1182 log_write(repr(output_hist[n]),'output')
1183 1183 else:
1184 1184 logger.log_write(input_hist[1:])
1185 1185 if timestamp:
1186 1186 # re-enable timestamping
1187 1187 logger.timestamp = True
1188 1188
1189 1189 print ('Activating auto-logging. '
1190 1190 'Current session state plus future input saved.')
1191 1191 logger.logstate()
1192 1192
1193 1193 def magic_logstop(self,parameter_s=''):
1194 1194 """Fully stop logging and close log file.
1195 1195
1196 1196 In order to start logging again, a new %logstart call needs to be made,
1197 1197 possibly (though not necessarily) with a new filename, mode and other
1198 1198 options."""
1199 1199 self.logger.logstop()
1200 1200
1201 1201 def magic_logoff(self,parameter_s=''):
1202 1202 """Temporarily stop logging.
1203 1203
1204 1204 You must have previously started logging."""
1205 1205 self.shell.logger.switch_log(0)
1206 1206
1207 1207 def magic_logon(self,parameter_s=''):
1208 1208 """Restart logging.
1209 1209
1210 1210 This function is for restarting logging which you've temporarily
1211 1211 stopped with %logoff. For starting logging for the first time, you
1212 1212 must use the %logstart function, which allows you to specify an
1213 1213 optional log filename."""
1214 1214
1215 1215 self.shell.logger.switch_log(1)
1216 1216
1217 1217 def magic_logstate(self,parameter_s=''):
1218 1218 """Print the status of the logging system."""
1219 1219
1220 1220 self.shell.logger.logstate()
1221 1221
1222 1222 def magic_pdb(self, parameter_s=''):
1223 1223 """Control the automatic calling of the pdb interactive debugger.
1224 1224
1225 1225 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1226 1226 argument it works as a toggle.
1227 1227
1228 1228 When an exception is triggered, IPython can optionally call the
1229 1229 interactive pdb debugger after the traceback printout. %pdb toggles
1230 1230 this feature on and off.
1231 1231
1232 1232 The initial state of this feature is set in your ipythonrc
1233 1233 configuration file (the variable is called 'pdb').
1234 1234
1235 1235 If you want to just activate the debugger AFTER an exception has fired,
1236 1236 without having to type '%pdb on' and rerunning your code, you can use
1237 1237 the %debug magic."""
1238 1238
1239 1239 par = parameter_s.strip().lower()
1240 1240
1241 1241 if par:
1242 1242 try:
1243 1243 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1244 1244 except KeyError:
1245 1245 print ('Incorrect argument. Use on/1, off/0, '
1246 1246 'or nothing for a toggle.')
1247 1247 return
1248 1248 else:
1249 1249 # toggle
1250 1250 new_pdb = not self.shell.call_pdb
1251 1251
1252 1252 # set on the shell
1253 1253 self.shell.call_pdb = new_pdb
1254 1254 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1255 1255
1256 1256 def magic_debug(self, parameter_s=''):
1257 1257 """Activate the interactive debugger in post-mortem mode.
1258 1258
1259 1259 If an exception has just occurred, this lets you inspect its stack
1260 1260 frames interactively. Note that this will always work only on the last
1261 1261 traceback that occurred, so you must call this quickly after an
1262 1262 exception that you wish to inspect has fired, because if another one
1263 1263 occurs, it clobbers the previous one.
1264 1264
1265 1265 If you want IPython to automatically do this on every exception, see
1266 1266 the %pdb magic for more details.
1267 1267 """
1268 1268
1269 1269 self.shell.debugger(force=True)
1270 1270
1271 1271 @testdec.skip_doctest
1272 1272 def magic_prun(self, parameter_s ='',user_mode=1,
1273 1273 opts=None,arg_lst=None,prog_ns=None):
1274 1274
1275 1275 """Run a statement through the python code profiler.
1276 1276
1277 1277 Usage:
1278 1278 %prun [options] statement
1279 1279
1280 1280 The given statement (which doesn't require quote marks) is run via the
1281 1281 python profiler in a manner similar to the profile.run() function.
1282 1282 Namespaces are internally managed to work correctly; profile.run
1283 1283 cannot be used in IPython because it makes certain assumptions about
1284 1284 namespaces which do not hold under IPython.
1285 1285
1286 1286 Options:
1287 1287
1288 1288 -l <limit>: you can place restrictions on what or how much of the
1289 1289 profile gets printed. The limit value can be:
1290 1290
1291 1291 * A string: only information for function names containing this string
1292 1292 is printed.
1293 1293
1294 1294 * An integer: only these many lines are printed.
1295 1295
1296 1296 * A float (between 0 and 1): this fraction of the report is printed
1297 1297 (for example, use a limit of 0.4 to see the topmost 40% only).
1298 1298
1299 1299 You can combine several limits with repeated use of the option. For
1300 1300 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1301 1301 information about class constructors.
1302 1302
1303 1303 -r: return the pstats.Stats object generated by the profiling. This
1304 1304 object has all the information about the profile in it, and you can
1305 1305 later use it for further analysis or in other functions.
1306 1306
1307 1307 -s <key>: sort profile by given key. You can provide more than one key
1308 1308 by using the option several times: '-s key1 -s key2 -s key3...'. The
1309 1309 default sorting key is 'time'.
1310 1310
1311 1311 The following is copied verbatim from the profile documentation
1312 1312 referenced below:
1313 1313
1314 1314 When more than one key is provided, additional keys are used as
1315 1315 secondary criteria when the there is equality in all keys selected
1316 1316 before them.
1317 1317
1318 1318 Abbreviations can be used for any key names, as long as the
1319 1319 abbreviation is unambiguous. The following are the keys currently
1320 1320 defined:
1321 1321
1322 1322 Valid Arg Meaning
1323 1323 "calls" call count
1324 1324 "cumulative" cumulative time
1325 1325 "file" file name
1326 1326 "module" file name
1327 1327 "pcalls" primitive call count
1328 1328 "line" line number
1329 1329 "name" function name
1330 1330 "nfl" name/file/line
1331 1331 "stdname" standard name
1332 1332 "time" internal time
1333 1333
1334 1334 Note that all sorts on statistics are in descending order (placing
1335 1335 most time consuming items first), where as name, file, and line number
1336 1336 searches are in ascending order (i.e., alphabetical). The subtle
1337 1337 distinction between "nfl" and "stdname" is that the standard name is a
1338 1338 sort of the name as printed, which means that the embedded line
1339 1339 numbers get compared in an odd way. For example, lines 3, 20, and 40
1340 1340 would (if the file names were the same) appear in the string order
1341 1341 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1342 1342 line numbers. In fact, sort_stats("nfl") is the same as
1343 1343 sort_stats("name", "file", "line").
1344 1344
1345 1345 -T <filename>: save profile results as shown on screen to a text
1346 1346 file. The profile is still shown on screen.
1347 1347
1348 1348 -D <filename>: save (via dump_stats) profile statistics to given
1349 1349 filename. This data is in a format understod by the pstats module, and
1350 1350 is generated by a call to the dump_stats() method of profile
1351 1351 objects. The profile is still shown on screen.
1352 1352
1353 1353 If you want to run complete programs under the profiler's control, use
1354 1354 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1355 1355 contains profiler specific options as described here.
1356 1356
1357 1357 You can read the complete documentation for the profile module with::
1358 1358
1359 1359 In [1]: import profile; profile.help()
1360 1360 """
1361 1361
1362 1362 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1363 1363 # protect user quote marks
1364 1364 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1365 1365
1366 1366 if user_mode: # regular user call
1367 1367 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1368 1368 list_all=1)
1369 1369 namespace = self.shell.user_ns
1370 1370 else: # called to run a program by %run -p
1371 1371 try:
1372 1372 filename = get_py_filename(arg_lst[0])
1373 1373 except IOError,msg:
1374 1374 error(msg)
1375 1375 return
1376 1376
1377 1377 arg_str = 'execfile(filename,prog_ns)'
1378 1378 namespace = locals()
1379 1379
1380 1380 opts.merge(opts_def)
1381 1381
1382 1382 prof = profile.Profile()
1383 1383 try:
1384 1384 prof = prof.runctx(arg_str,namespace,namespace)
1385 1385 sys_exit = ''
1386 1386 except SystemExit:
1387 1387 sys_exit = """*** SystemExit exception caught in code being profiled."""
1388 1388
1389 1389 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1390 1390
1391 1391 lims = opts.l
1392 1392 if lims:
1393 1393 lims = [] # rebuild lims with ints/floats/strings
1394 1394 for lim in opts.l:
1395 1395 try:
1396 1396 lims.append(int(lim))
1397 1397 except ValueError:
1398 1398 try:
1399 1399 lims.append(float(lim))
1400 1400 except ValueError:
1401 1401 lims.append(lim)
1402 1402
1403 1403 # Trap output.
1404 1404 stdout_trap = StringIO()
1405 1405
1406 1406 if hasattr(stats,'stream'):
1407 1407 # In newer versions of python, the stats object has a 'stream'
1408 1408 # attribute to write into.
1409 1409 stats.stream = stdout_trap
1410 1410 stats.print_stats(*lims)
1411 1411 else:
1412 1412 # For older versions, we manually redirect stdout during printing
1413 1413 sys_stdout = sys.stdout
1414 1414 try:
1415 1415 sys.stdout = stdout_trap
1416 1416 stats.print_stats(*lims)
1417 1417 finally:
1418 1418 sys.stdout = sys_stdout
1419 1419
1420 1420 output = stdout_trap.getvalue()
1421 1421 output = output.rstrip()
1422 1422
1423 1423 page(output,screen_lines=self.shell.rc.screen_length)
1424 1424 print sys_exit,
1425 1425
1426 1426 dump_file = opts.D[0]
1427 1427 text_file = opts.T[0]
1428 1428 if dump_file:
1429 1429 prof.dump_stats(dump_file)
1430 1430 print '\n*** Profile stats marshalled to file',\
1431 1431 `dump_file`+'.',sys_exit
1432 1432 if text_file:
1433 1433 pfile = file(text_file,'w')
1434 1434 pfile.write(output)
1435 1435 pfile.close()
1436 1436 print '\n*** Profile printout saved to text file',\
1437 1437 `text_file`+'.',sys_exit
1438 1438
1439 1439 if opts.has_key('r'):
1440 1440 return stats
1441 1441 else:
1442 1442 return None
1443 1443
1444 1444 @testdec.skip_doctest
1445 1445 def magic_run(self, parameter_s ='',runner=None,
1446 1446 file_finder=get_py_filename):
1447 1447 """Run the named file inside IPython as a program.
1448 1448
1449 1449 Usage:\\
1450 1450 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1451 1451
1452 1452 Parameters after the filename are passed as command-line arguments to
1453 1453 the program (put in sys.argv). Then, control returns to IPython's
1454 1454 prompt.
1455 1455
1456 1456 This is similar to running at a system prompt:\\
1457 1457 $ python file args\\
1458 1458 but with the advantage of giving you IPython's tracebacks, and of
1459 1459 loading all variables into your interactive namespace for further use
1460 1460 (unless -p is used, see below).
1461 1461
1462 1462 The file is executed in a namespace initially consisting only of
1463 1463 __name__=='__main__' and sys.argv constructed as indicated. It thus
1464 1464 sees its environment as if it were being run as a stand-alone program
1465 1465 (except for sharing global objects such as previously imported
1466 1466 modules). But after execution, the IPython interactive namespace gets
1467 1467 updated with all variables defined in the program (except for __name__
1468 1468 and sys.argv). This allows for very convenient loading of code for
1469 1469 interactive work, while giving each program a 'clean sheet' to run in.
1470 1470
1471 1471 Options:
1472 1472
1473 1473 -n: __name__ is NOT set to '__main__', but to the running file's name
1474 1474 without extension (as python does under import). This allows running
1475 1475 scripts and reloading the definitions in them without calling code
1476 1476 protected by an ' if __name__ == "__main__" ' clause.
1477 1477
1478 1478 -i: run the file in IPython's namespace instead of an empty one. This
1479 1479 is useful if you are experimenting with code written in a text editor
1480 1480 which depends on variables defined interactively.
1481 1481
1482 1482 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1483 1483 being run. This is particularly useful if IPython is being used to
1484 1484 run unittests, which always exit with a sys.exit() call. In such
1485 1485 cases you are interested in the output of the test results, not in
1486 1486 seeing a traceback of the unittest module.
1487 1487
1488 1488 -t: print timing information at the end of the run. IPython will give
1489 1489 you an estimated CPU time consumption for your script, which under
1490 1490 Unix uses the resource module to avoid the wraparound problems of
1491 1491 time.clock(). Under Unix, an estimate of time spent on system tasks
1492 1492 is also given (for Windows platforms this is reported as 0.0).
1493 1493
1494 1494 If -t is given, an additional -N<N> option can be given, where <N>
1495 1495 must be an integer indicating how many times you want the script to
1496 1496 run. The final timing report will include total and per run results.
1497 1497
1498 1498 For example (testing the script uniq_stable.py):
1499 1499
1500 1500 In [1]: run -t uniq_stable
1501 1501
1502 1502 IPython CPU timings (estimated):\\
1503 1503 User : 0.19597 s.\\
1504 1504 System: 0.0 s.\\
1505 1505
1506 1506 In [2]: run -t -N5 uniq_stable
1507 1507
1508 1508 IPython CPU timings (estimated):\\
1509 1509 Total runs performed: 5\\
1510 1510 Times : Total Per run\\
1511 1511 User : 0.910862 s, 0.1821724 s.\\
1512 1512 System: 0.0 s, 0.0 s.
1513 1513
1514 1514 -d: run your program under the control of pdb, the Python debugger.
1515 1515 This allows you to execute your program step by step, watch variables,
1516 1516 etc. Internally, what IPython does is similar to calling:
1517 1517
1518 1518 pdb.run('execfile("YOURFILENAME")')
1519 1519
1520 1520 with a breakpoint set on line 1 of your file. You can change the line
1521 1521 number for this automatic breakpoint to be <N> by using the -bN option
1522 1522 (where N must be an integer). For example:
1523 1523
1524 1524 %run -d -b40 myscript
1525 1525
1526 1526 will set the first breakpoint at line 40 in myscript.py. Note that
1527 1527 the first breakpoint must be set on a line which actually does
1528 1528 something (not a comment or docstring) for it to stop execution.
1529 1529
1530 1530 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1531 1531 first enter 'c' (without qoutes) to start execution up to the first
1532 1532 breakpoint.
1533 1533
1534 1534 Entering 'help' gives information about the use of the debugger. You
1535 1535 can easily see pdb's full documentation with "import pdb;pdb.help()"
1536 1536 at a prompt.
1537 1537
1538 1538 -p: run program under the control of the Python profiler module (which
1539 1539 prints a detailed report of execution times, function calls, etc).
1540 1540
1541 1541 You can pass other options after -p which affect the behavior of the
1542 1542 profiler itself. See the docs for %prun for details.
1543 1543
1544 1544 In this mode, the program's variables do NOT propagate back to the
1545 1545 IPython interactive namespace (because they remain in the namespace
1546 1546 where the profiler executes them).
1547 1547
1548 1548 Internally this triggers a call to %prun, see its documentation for
1549 1549 details on the options available specifically for profiling.
1550 1550
1551 1551 There is one special usage for which the text above doesn't apply:
1552 1552 if the filename ends with .ipy, the file is run as ipython script,
1553 1553 just as if the commands were written on IPython prompt.
1554 1554 """
1555 1555
1556 1556 # get arguments and set sys.argv for program to be run.
1557 1557 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1558 1558 mode='list',list_all=1)
1559 1559
1560 1560 try:
1561 1561 filename = file_finder(arg_lst[0])
1562 1562 except IndexError:
1563 1563 warn('you must provide at least a filename.')
1564 1564 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1565 1565 return
1566 1566 except IOError,msg:
1567 1567 error(msg)
1568 1568 return
1569 1569
1570 1570 if filename.lower().endswith('.ipy'):
1571 1571 self.api.runlines(open(filename).read())
1572 1572 return
1573 1573
1574 1574 # Control the response to exit() calls made by the script being run
1575 1575 exit_ignore = opts.has_key('e')
1576 1576
1577 1577 # Make sure that the running script gets a proper sys.argv as if it
1578 1578 # were run from a system shell.
1579 1579 save_argv = sys.argv # save it for later restoring
1580 1580 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1581 1581
1582 1582 if opts.has_key('i'):
1583 1583 # Run in user's interactive namespace
1584 1584 prog_ns = self.shell.user_ns
1585 1585 __name__save = self.shell.user_ns['__name__']
1586 1586 prog_ns['__name__'] = '__main__'
1587 main_mod = FakeModule(prog_ns)
1587
1588 ##main_mod = FakeModule(prog_ns)
1589 main_mod = self.shell.new_main_mod(prog_ns)
1590
1588 1591 else:
1589 1592 # Run in a fresh, empty namespace
1590 1593 if opts.has_key('n'):
1591 1594 name = os.path.splitext(os.path.basename(filename))[0]
1592 1595 else:
1593 1596 name = '__main__'
1594 main_mod = FakeModule()
1597
1598 main_mod = self.shell.new_main_mod()
1599
1595 1600 prog_ns = main_mod.__dict__
1596 1601 prog_ns['__name__'] = name
1597 1602
1598 # The shell MUST hold a reference to main_mod so after %run exits,
1599 # the python deletion mechanism doesn't zero it out (leaving
1600 # dangling references). However, we should drop old versions of
1601 # main_mod. There is now a proper API to manage this caching in
1602 # the main shell object, we use that.
1603 self.shell.cache_main_mod(main_mod)
1604 1603
1605 1604 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1606 1605 # set the __file__ global in the script's namespace
1607 1606 prog_ns['__file__'] = filename
1608 1607
1609 1608 # pickle fix. See iplib for an explanation. But we need to make sure
1610 1609 # that, if we overwrite __main__, we replace it at the end
1611 1610 main_mod_name = prog_ns['__name__']
1612 1611
1613 1612 if main_mod_name == '__main__':
1614 1613 restore_main = sys.modules['__main__']
1615 1614 else:
1616 1615 restore_main = False
1617 1616
1618 1617 # This needs to be undone at the end to prevent holding references to
1619 1618 # every single object ever created.
1620 1619 sys.modules[main_mod_name] = main_mod
1621 1620
1622 1621 stats = None
1623 1622 try:
1624 1623 self.shell.savehist()
1625 1624
1626 1625 if opts.has_key('p'):
1627 1626 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1628 1627 else:
1629 1628 if opts.has_key('d'):
1630 1629 deb = Debugger.Pdb(self.shell.rc.colors)
1631 1630 # reset Breakpoint state, which is moronically kept
1632 1631 # in a class
1633 1632 bdb.Breakpoint.next = 1
1634 1633 bdb.Breakpoint.bplist = {}
1635 1634 bdb.Breakpoint.bpbynumber = [None]
1636 1635 # Set an initial breakpoint to stop execution
1637 1636 maxtries = 10
1638 1637 bp = int(opts.get('b',[1])[0])
1639 1638 checkline = deb.checkline(filename,bp)
1640 1639 if not checkline:
1641 1640 for bp in range(bp+1,bp+maxtries+1):
1642 1641 if deb.checkline(filename,bp):
1643 1642 break
1644 1643 else:
1645 1644 msg = ("\nI failed to find a valid line to set "
1646 1645 "a breakpoint\n"
1647 1646 "after trying up to line: %s.\n"
1648 1647 "Please set a valid breakpoint manually "
1649 1648 "with the -b option." % bp)
1650 1649 error(msg)
1651 1650 return
1652 1651 # if we find a good linenumber, set the breakpoint
1653 1652 deb.do_break('%s:%s' % (filename,bp))
1654 1653 # Start file run
1655 1654 print "NOTE: Enter 'c' at the",
1656 1655 print "%s prompt to start your script." % deb.prompt
1657 1656 try:
1658 1657 deb.run('execfile("%s")' % filename,prog_ns)
1659 1658
1660 1659 except:
1661 1660 etype, value, tb = sys.exc_info()
1662 1661 # Skip three frames in the traceback: the %run one,
1663 1662 # one inside bdb.py, and the command-line typed by the
1664 1663 # user (run by exec in pdb itself).
1665 1664 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1666 1665 else:
1667 1666 if runner is None:
1668 1667 runner = self.shell.safe_execfile
1669 1668 if opts.has_key('t'):
1670 1669 # timed execution
1671 1670 try:
1672 1671 nruns = int(opts['N'][0])
1673 1672 if nruns < 1:
1674 1673 error('Number of runs must be >=1')
1675 1674 return
1676 1675 except (KeyError):
1677 1676 nruns = 1
1678 1677 if nruns == 1:
1679 1678 t0 = clock2()
1680 1679 runner(filename,prog_ns,prog_ns,
1681 1680 exit_ignore=exit_ignore)
1682 1681 t1 = clock2()
1683 1682 t_usr = t1[0]-t0[0]
1684 1683 t_sys = t1[1]-t1[1]
1685 1684 print "\nIPython CPU timings (estimated):"
1686 1685 print " User : %10s s." % t_usr
1687 1686 print " System: %10s s." % t_sys
1688 1687 else:
1689 1688 runs = range(nruns)
1690 1689 t0 = clock2()
1691 1690 for nr in runs:
1692 1691 runner(filename,prog_ns,prog_ns,
1693 1692 exit_ignore=exit_ignore)
1694 1693 t1 = clock2()
1695 1694 t_usr = t1[0]-t0[0]
1696 1695 t_sys = t1[1]-t1[1]
1697 1696 print "\nIPython CPU timings (estimated):"
1698 1697 print "Total runs performed:",nruns
1699 1698 print " Times : %10s %10s" % ('Total','Per run')
1700 1699 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1701 1700 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1702 1701
1703 1702 else:
1704 1703 # regular execution
1705 1704 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1705
1706 1706 if opts.has_key('i'):
1707 1707 self.shell.user_ns['__name__'] = __name__save
1708 1708 else:
1709 # The shell MUST hold a reference to prog_ns so after %run
1710 # exits, the python deletion mechanism doesn't zero it out
1711 # (leaving dangling references).
1712 self.shell.cache_main_mod(prog_ns,filename)
1709 1713 # update IPython interactive namespace
1710 1714 del prog_ns['__name__']
1711 1715 self.shell.user_ns.update(prog_ns)
1712 1716 finally:
1713 1717 # Ensure key global structures are restored
1714 1718 sys.argv = save_argv
1715 1719 if restore_main:
1716 1720 sys.modules['__main__'] = restore_main
1717 1721 else:
1718 1722 # Remove from sys.modules the reference to main_mod we'd
1719 1723 # added. Otherwise it will trap references to objects
1720 1724 # contained therein.
1721 1725 del sys.modules[main_mod_name]
1726
1722 1727 self.shell.reloadhist()
1723 1728
1724 1729 return stats
1725 1730
1726 1731 def magic_runlog(self, parameter_s =''):
1727 1732 """Run files as logs.
1728 1733
1729 1734 Usage:\\
1730 1735 %runlog file1 file2 ...
1731 1736
1732 1737 Run the named files (treating them as log files) in sequence inside
1733 1738 the interpreter, and return to the prompt. This is much slower than
1734 1739 %run because each line is executed in a try/except block, but it
1735 1740 allows running files with syntax errors in them.
1736 1741
1737 1742 Normally IPython will guess when a file is one of its own logfiles, so
1738 1743 you can typically use %run even for logs. This shorthand allows you to
1739 1744 force any file to be treated as a log file."""
1740 1745
1741 1746 for f in parameter_s.split():
1742 1747 self.shell.safe_execfile(f,self.shell.user_ns,
1743 1748 self.shell.user_ns,islog=1)
1744 1749
1745 1750 @testdec.skip_doctest
1746 1751 def magic_timeit(self, parameter_s =''):
1747 1752 """Time execution of a Python statement or expression
1748 1753
1749 1754 Usage:\\
1750 1755 %timeit [-n<N> -r<R> [-t|-c]] statement
1751 1756
1752 1757 Time execution of a Python statement or expression using the timeit
1753 1758 module.
1754 1759
1755 1760 Options:
1756 1761 -n<N>: execute the given statement <N> times in a loop. If this value
1757 1762 is not given, a fitting value is chosen.
1758 1763
1759 1764 -r<R>: repeat the loop iteration <R> times and take the best result.
1760 1765 Default: 3
1761 1766
1762 1767 -t: use time.time to measure the time, which is the default on Unix.
1763 1768 This function measures wall time.
1764 1769
1765 1770 -c: use time.clock to measure the time, which is the default on
1766 1771 Windows and measures wall time. On Unix, resource.getrusage is used
1767 1772 instead and returns the CPU user time.
1768 1773
1769 1774 -p<P>: use a precision of <P> digits to display the timing result.
1770 1775 Default: 3
1771 1776
1772 1777
1773 1778 Examples:
1774 1779
1775 1780 In [1]: %timeit pass
1776 1781 10000000 loops, best of 3: 53.3 ns per loop
1777 1782
1778 1783 In [2]: u = None
1779 1784
1780 1785 In [3]: %timeit u is None
1781 1786 10000000 loops, best of 3: 184 ns per loop
1782 1787
1783 1788 In [4]: %timeit -r 4 u == None
1784 1789 1000000 loops, best of 4: 242 ns per loop
1785 1790
1786 1791 In [5]: import time
1787 1792
1788 1793 In [6]: %timeit -n1 time.sleep(2)
1789 1794 1 loops, best of 3: 2 s per loop
1790 1795
1791 1796
1792 1797 The times reported by %timeit will be slightly higher than those
1793 1798 reported by the timeit.py script when variables are accessed. This is
1794 1799 due to the fact that %timeit executes the statement in the namespace
1795 1800 of the shell, compared with timeit.py, which uses a single setup
1796 1801 statement to import function or create variables. Generally, the bias
1797 1802 does not matter as long as results from timeit.py are not mixed with
1798 1803 those from %timeit."""
1799 1804
1800 1805 import timeit
1801 1806 import math
1802 1807
1803 1808 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1804 1809 # certain terminals. Until we figure out a robust way of
1805 1810 # auto-detecting if the terminal can deal with it, use plain 'us' for
1806 1811 # microseconds. Note: using
1807 1812 #
1808 1813 # s = u'\xb5'
1809 1814 # s.encode(sys.getdefaultencoding())
1810 1815 #
1811 1816 # is not sufficient, as I've seen terminals where that fails but
1812 1817 # print s
1813 1818 #
1814 1819 # succeeds
1815 1820 #
1816 1821 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1817 1822
1818 1823 #units = [u"s", u"ms",u'\xb5',"ns"]
1819 1824 units = [u"s", u"ms",u'us',"ns"]
1820 1825
1821 1826 scaling = [1, 1e3, 1e6, 1e9]
1822 1827
1823 1828 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1824 1829 posix=False)
1825 1830 if stmt == "":
1826 1831 return
1827 1832 timefunc = timeit.default_timer
1828 1833 number = int(getattr(opts, "n", 0))
1829 1834 repeat = int(getattr(opts, "r", timeit.default_repeat))
1830 1835 precision = int(getattr(opts, "p", 3))
1831 1836 if hasattr(opts, "t"):
1832 1837 timefunc = time.time
1833 1838 if hasattr(opts, "c"):
1834 1839 timefunc = clock
1835 1840
1836 1841 timer = timeit.Timer(timer=timefunc)
1837 1842 # this code has tight coupling to the inner workings of timeit.Timer,
1838 1843 # but is there a better way to achieve that the code stmt has access
1839 1844 # to the shell namespace?
1840 1845
1841 1846 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1842 1847 'setup': "pass"}
1843 1848 # Track compilation time so it can be reported if too long
1844 1849 # Minimum time above which compilation time will be reported
1845 1850 tc_min = 0.1
1846 1851
1847 1852 t0 = clock()
1848 1853 code = compile(src, "<magic-timeit>", "exec")
1849 1854 tc = clock()-t0
1850 1855
1851 1856 ns = {}
1852 1857 exec code in self.shell.user_ns, ns
1853 1858 timer.inner = ns["inner"]
1854 1859
1855 1860 if number == 0:
1856 1861 # determine number so that 0.2 <= total time < 2.0
1857 1862 number = 1
1858 1863 for i in range(1, 10):
1859 1864 number *= 10
1860 1865 if timer.timeit(number) >= 0.2:
1861 1866 break
1862 1867
1863 1868 best = min(timer.repeat(repeat, number)) / number
1864 1869
1865 1870 if best > 0.0:
1866 1871 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1867 1872 else:
1868 1873 order = 3
1869 1874 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1870 1875 precision,
1871 1876 best * scaling[order],
1872 1877 units[order])
1873 1878 if tc > tc_min:
1874 1879 print "Compiler time: %.2f s" % tc
1875 1880
1876 1881 @testdec.skip_doctest
1877 1882 def magic_time(self,parameter_s = ''):
1878 1883 """Time execution of a Python statement or expression.
1879 1884
1880 1885 The CPU and wall clock times are printed, and the value of the
1881 1886 expression (if any) is returned. Note that under Win32, system time
1882 1887 is always reported as 0, since it can not be measured.
1883 1888
1884 1889 This function provides very basic timing functionality. In Python
1885 1890 2.3, the timeit module offers more control and sophistication, so this
1886 1891 could be rewritten to use it (patches welcome).
1887 1892
1888 1893 Some examples:
1889 1894
1890 1895 In [1]: time 2**128
1891 1896 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1892 1897 Wall time: 0.00
1893 1898 Out[1]: 340282366920938463463374607431768211456L
1894 1899
1895 1900 In [2]: n = 1000000
1896 1901
1897 1902 In [3]: time sum(range(n))
1898 1903 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1899 1904 Wall time: 1.37
1900 1905 Out[3]: 499999500000L
1901 1906
1902 1907 In [4]: time print 'hello world'
1903 1908 hello world
1904 1909 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1905 1910 Wall time: 0.00
1906 1911
1907 1912 Note that the time needed by Python to compile the given expression
1908 1913 will be reported if it is more than 0.1s. In this example, the
1909 1914 actual exponentiation is done by Python at compilation time, so while
1910 1915 the expression can take a noticeable amount of time to compute, that
1911 1916 time is purely due to the compilation:
1912 1917
1913 1918 In [5]: time 3**9999;
1914 1919 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1915 1920 Wall time: 0.00 s
1916 1921
1917 1922 In [6]: time 3**999999;
1918 1923 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1919 1924 Wall time: 0.00 s
1920 1925 Compiler : 0.78 s
1921 1926 """
1922 1927
1923 1928 # fail immediately if the given expression can't be compiled
1924 1929
1925 1930 expr = self.shell.prefilter(parameter_s,False)
1926 1931
1927 1932 # Minimum time above which compilation time will be reported
1928 1933 tc_min = 0.1
1929 1934
1930 1935 try:
1931 1936 mode = 'eval'
1932 1937 t0 = clock()
1933 1938 code = compile(expr,'<timed eval>',mode)
1934 1939 tc = clock()-t0
1935 1940 except SyntaxError:
1936 1941 mode = 'exec'
1937 1942 t0 = clock()
1938 1943 code = compile(expr,'<timed exec>',mode)
1939 1944 tc = clock()-t0
1940 1945 # skew measurement as little as possible
1941 1946 glob = self.shell.user_ns
1942 1947 clk = clock2
1943 1948 wtime = time.time
1944 1949 # time execution
1945 1950 wall_st = wtime()
1946 1951 if mode=='eval':
1947 1952 st = clk()
1948 1953 out = eval(code,glob)
1949 1954 end = clk()
1950 1955 else:
1951 1956 st = clk()
1952 1957 exec code in glob
1953 1958 end = clk()
1954 1959 out = None
1955 1960 wall_end = wtime()
1956 1961 # Compute actual times and report
1957 1962 wall_time = wall_end-wall_st
1958 1963 cpu_user = end[0]-st[0]
1959 1964 cpu_sys = end[1]-st[1]
1960 1965 cpu_tot = cpu_user+cpu_sys
1961 1966 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1962 1967 (cpu_user,cpu_sys,cpu_tot)
1963 1968 print "Wall time: %.2f s" % wall_time
1964 1969 if tc > tc_min:
1965 1970 print "Compiler : %.2f s" % tc
1966 1971 return out
1967 1972
1968 1973 @testdec.skip_doctest
1969 1974 def magic_macro(self,parameter_s = ''):
1970 1975 """Define a set of input lines as a macro for future re-execution.
1971 1976
1972 1977 Usage:\\
1973 1978 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1974 1979
1975 1980 Options:
1976 1981
1977 1982 -r: use 'raw' input. By default, the 'processed' history is used,
1978 1983 so that magics are loaded in their transformed version to valid
1979 1984 Python. If this option is given, the raw input as typed as the
1980 1985 command line is used instead.
1981 1986
1982 1987 This will define a global variable called `name` which is a string
1983 1988 made of joining the slices and lines you specify (n1,n2,... numbers
1984 1989 above) from your input history into a single string. This variable
1985 1990 acts like an automatic function which re-executes those lines as if
1986 1991 you had typed them. You just type 'name' at the prompt and the code
1987 1992 executes.
1988 1993
1989 1994 The notation for indicating number ranges is: n1-n2 means 'use line
1990 1995 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1991 1996 using the lines numbered 5,6 and 7.
1992 1997
1993 1998 Note: as a 'hidden' feature, you can also use traditional python slice
1994 1999 notation, where N:M means numbers N through M-1.
1995 2000
1996 2001 For example, if your history contains (%hist prints it):
1997 2002
1998 2003 44: x=1
1999 2004 45: y=3
2000 2005 46: z=x+y
2001 2006 47: print x
2002 2007 48: a=5
2003 2008 49: print 'x',x,'y',y
2004 2009
2005 2010 you can create a macro with lines 44 through 47 (included) and line 49
2006 2011 called my_macro with:
2007 2012
2008 2013 In [55]: %macro my_macro 44-47 49
2009 2014
2010 2015 Now, typing `my_macro` (without quotes) will re-execute all this code
2011 2016 in one pass.
2012 2017
2013 2018 You don't need to give the line-numbers in order, and any given line
2014 2019 number can appear multiple times. You can assemble macros with any
2015 2020 lines from your input history in any order.
2016 2021
2017 2022 The macro is a simple object which holds its value in an attribute,
2018 2023 but IPython's display system checks for macros and executes them as
2019 2024 code instead of printing them when you type their name.
2020 2025
2021 2026 You can view a macro's contents by explicitly printing it with:
2022 2027
2023 2028 'print macro_name'.
2024 2029
2025 2030 For one-off cases which DON'T contain magic function calls in them you
2026 2031 can obtain similar results by explicitly executing slices from your
2027 2032 input history with:
2028 2033
2029 2034 In [60]: exec In[44:48]+In[49]"""
2030 2035
2031 2036 opts,args = self.parse_options(parameter_s,'r',mode='list')
2032 2037 if not args:
2033 2038 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2034 2039 macs.sort()
2035 2040 return macs
2036 2041 if len(args) == 1:
2037 2042 raise UsageError(
2038 2043 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2039 2044 name,ranges = args[0], args[1:]
2040 2045
2041 2046 #print 'rng',ranges # dbg
2042 2047 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2043 2048 macro = Macro(lines)
2044 2049 self.shell.user_ns.update({name:macro})
2045 2050 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2046 2051 print 'Macro contents:'
2047 2052 print macro,
2048 2053
2049 2054 def magic_save(self,parameter_s = ''):
2050 2055 """Save a set of lines to a given filename.
2051 2056
2052 2057 Usage:\\
2053 2058 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2054 2059
2055 2060 Options:
2056 2061
2057 2062 -r: use 'raw' input. By default, the 'processed' history is used,
2058 2063 so that magics are loaded in their transformed version to valid
2059 2064 Python. If this option is given, the raw input as typed as the
2060 2065 command line is used instead.
2061 2066
2062 2067 This function uses the same syntax as %macro for line extraction, but
2063 2068 instead of creating a macro it saves the resulting string to the
2064 2069 filename you specify.
2065 2070
2066 2071 It adds a '.py' extension to the file if you don't do so yourself, and
2067 2072 it asks for confirmation before overwriting existing files."""
2068 2073
2069 2074 opts,args = self.parse_options(parameter_s,'r',mode='list')
2070 2075 fname,ranges = args[0], args[1:]
2071 2076 if not fname.endswith('.py'):
2072 2077 fname += '.py'
2073 2078 if os.path.isfile(fname):
2074 2079 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2075 2080 if ans.lower() not in ['y','yes']:
2076 2081 print 'Operation cancelled.'
2077 2082 return
2078 2083 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2079 2084 f = file(fname,'w')
2080 2085 f.write(cmds)
2081 2086 f.close()
2082 2087 print 'The following commands were written to file `%s`:' % fname
2083 2088 print cmds
2084 2089
2085 2090 def _edit_macro(self,mname,macro):
2086 2091 """open an editor with the macro data in a file"""
2087 2092 filename = self.shell.mktempfile(macro.value)
2088 2093 self.shell.hooks.editor(filename)
2089 2094
2090 2095 # and make a new macro object, to replace the old one
2091 2096 mfile = open(filename)
2092 2097 mvalue = mfile.read()
2093 2098 mfile.close()
2094 2099 self.shell.user_ns[mname] = Macro(mvalue)
2095 2100
2096 2101 def magic_ed(self,parameter_s=''):
2097 2102 """Alias to %edit."""
2098 2103 return self.magic_edit(parameter_s)
2099 2104
2100 2105 @testdec.skip_doctest
2101 2106 def magic_edit(self,parameter_s='',last_call=['','']):
2102 2107 """Bring up an editor and execute the resulting code.
2103 2108
2104 2109 Usage:
2105 2110 %edit [options] [args]
2106 2111
2107 2112 %edit runs IPython's editor hook. The default version of this hook is
2108 2113 set to call the __IPYTHON__.rc.editor command. This is read from your
2109 2114 environment variable $EDITOR. If this isn't found, it will default to
2110 2115 vi under Linux/Unix and to notepad under Windows. See the end of this
2111 2116 docstring for how to change the editor hook.
2112 2117
2113 2118 You can also set the value of this editor via the command line option
2114 2119 '-editor' or in your ipythonrc file. This is useful if you wish to use
2115 2120 specifically for IPython an editor different from your typical default
2116 2121 (and for Windows users who typically don't set environment variables).
2117 2122
2118 2123 This command allows you to conveniently edit multi-line code right in
2119 2124 your IPython session.
2120 2125
2121 2126 If called without arguments, %edit opens up an empty editor with a
2122 2127 temporary file and will execute the contents of this file when you
2123 2128 close it (don't forget to save it!).
2124 2129
2125 2130
2126 2131 Options:
2127 2132
2128 2133 -n <number>: open the editor at a specified line number. By default,
2129 2134 the IPython editor hook uses the unix syntax 'editor +N filename', but
2130 2135 you can configure this by providing your own modified hook if your
2131 2136 favorite editor supports line-number specifications with a different
2132 2137 syntax.
2133 2138
2134 2139 -p: this will call the editor with the same data as the previous time
2135 2140 it was used, regardless of how long ago (in your current session) it
2136 2141 was.
2137 2142
2138 2143 -r: use 'raw' input. This option only applies to input taken from the
2139 2144 user's history. By default, the 'processed' history is used, so that
2140 2145 magics are loaded in their transformed version to valid Python. If
2141 2146 this option is given, the raw input as typed as the command line is
2142 2147 used instead. When you exit the editor, it will be executed by
2143 2148 IPython's own processor.
2144 2149
2145 2150 -x: do not execute the edited code immediately upon exit. This is
2146 2151 mainly useful if you are editing programs which need to be called with
2147 2152 command line arguments, which you can then do using %run.
2148 2153
2149 2154
2150 2155 Arguments:
2151 2156
2152 2157 If arguments are given, the following possibilites exist:
2153 2158
2154 2159 - The arguments are numbers or pairs of colon-separated numbers (like
2155 2160 1 4:8 9). These are interpreted as lines of previous input to be
2156 2161 loaded into the editor. The syntax is the same of the %macro command.
2157 2162
2158 2163 - If the argument doesn't start with a number, it is evaluated as a
2159 2164 variable and its contents loaded into the editor. You can thus edit
2160 2165 any string which contains python code (including the result of
2161 2166 previous edits).
2162 2167
2163 2168 - If the argument is the name of an object (other than a string),
2164 2169 IPython will try to locate the file where it was defined and open the
2165 2170 editor at the point where it is defined. You can use `%edit function`
2166 2171 to load an editor exactly at the point where 'function' is defined,
2167 2172 edit it and have the file be executed automatically.
2168 2173
2169 2174 If the object is a macro (see %macro for details), this opens up your
2170 2175 specified editor with a temporary file containing the macro's data.
2171 2176 Upon exit, the macro is reloaded with the contents of the file.
2172 2177
2173 2178 Note: opening at an exact line is only supported under Unix, and some
2174 2179 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2175 2180 '+NUMBER' parameter necessary for this feature. Good editors like
2176 2181 (X)Emacs, vi, jed, pico and joe all do.
2177 2182
2178 2183 - If the argument is not found as a variable, IPython will look for a
2179 2184 file with that name (adding .py if necessary) and load it into the
2180 2185 editor. It will execute its contents with execfile() when you exit,
2181 2186 loading any code in the file into your interactive namespace.
2182 2187
2183 2188 After executing your code, %edit will return as output the code you
2184 2189 typed in the editor (except when it was an existing file). This way
2185 2190 you can reload the code in further invocations of %edit as a variable,
2186 2191 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2187 2192 the output.
2188 2193
2189 2194 Note that %edit is also available through the alias %ed.
2190 2195
2191 2196 This is an example of creating a simple function inside the editor and
2192 2197 then modifying it. First, start up the editor:
2193 2198
2194 2199 In [1]: ed
2195 2200 Editing... done. Executing edited code...
2196 2201 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2197 2202
2198 2203 We can then call the function foo():
2199 2204
2200 2205 In [2]: foo()
2201 2206 foo() was defined in an editing session
2202 2207
2203 2208 Now we edit foo. IPython automatically loads the editor with the
2204 2209 (temporary) file where foo() was previously defined:
2205 2210
2206 2211 In [3]: ed foo
2207 2212 Editing... done. Executing edited code...
2208 2213
2209 2214 And if we call foo() again we get the modified version:
2210 2215
2211 2216 In [4]: foo()
2212 2217 foo() has now been changed!
2213 2218
2214 2219 Here is an example of how to edit a code snippet successive
2215 2220 times. First we call the editor:
2216 2221
2217 2222 In [5]: ed
2218 2223 Editing... done. Executing edited code...
2219 2224 hello
2220 2225 Out[5]: "print 'hello'n"
2221 2226
2222 2227 Now we call it again with the previous output (stored in _):
2223 2228
2224 2229 In [6]: ed _
2225 2230 Editing... done. Executing edited code...
2226 2231 hello world
2227 2232 Out[6]: "print 'hello world'n"
2228 2233
2229 2234 Now we call it with the output #8 (stored in _8, also as Out[8]):
2230 2235
2231 2236 In [7]: ed _8
2232 2237 Editing... done. Executing edited code...
2233 2238 hello again
2234 2239 Out[7]: "print 'hello again'n"
2235 2240
2236 2241
2237 2242 Changing the default editor hook:
2238 2243
2239 2244 If you wish to write your own editor hook, you can put it in a
2240 2245 configuration file which you load at startup time. The default hook
2241 2246 is defined in the IPython.hooks module, and you can use that as a
2242 2247 starting example for further modifications. That file also has
2243 2248 general instructions on how to set a new hook for use once you've
2244 2249 defined it."""
2245 2250
2246 2251 # FIXME: This function has become a convoluted mess. It needs a
2247 2252 # ground-up rewrite with clean, simple logic.
2248 2253
2249 2254 def make_filename(arg):
2250 2255 "Make a filename from the given args"
2251 2256 try:
2252 2257 filename = get_py_filename(arg)
2253 2258 except IOError:
2254 2259 if args.endswith('.py'):
2255 2260 filename = arg
2256 2261 else:
2257 2262 filename = None
2258 2263 return filename
2259 2264
2260 2265 # custom exceptions
2261 2266 class DataIsObject(Exception): pass
2262 2267
2263 2268 opts,args = self.parse_options(parameter_s,'prxn:')
2264 2269 # Set a few locals from the options for convenience:
2265 2270 opts_p = opts.has_key('p')
2266 2271 opts_r = opts.has_key('r')
2267 2272
2268 2273 # Default line number value
2269 2274 lineno = opts.get('n',None)
2270 2275
2271 2276 if opts_p:
2272 2277 args = '_%s' % last_call[0]
2273 2278 if not self.shell.user_ns.has_key(args):
2274 2279 args = last_call[1]
2275 2280
2276 2281 # use last_call to remember the state of the previous call, but don't
2277 2282 # let it be clobbered by successive '-p' calls.
2278 2283 try:
2279 2284 last_call[0] = self.shell.outputcache.prompt_count
2280 2285 if not opts_p:
2281 2286 last_call[1] = parameter_s
2282 2287 except:
2283 2288 pass
2284 2289
2285 2290 # by default this is done with temp files, except when the given
2286 2291 # arg is a filename
2287 2292 use_temp = 1
2288 2293
2289 2294 if re.match(r'\d',args):
2290 2295 # Mode where user specifies ranges of lines, like in %macro.
2291 2296 # This means that you can't edit files whose names begin with
2292 2297 # numbers this way. Tough.
2293 2298 ranges = args.split()
2294 2299 data = ''.join(self.extract_input_slices(ranges,opts_r))
2295 2300 elif args.endswith('.py'):
2296 2301 filename = make_filename(args)
2297 2302 data = ''
2298 2303 use_temp = 0
2299 2304 elif args:
2300 2305 try:
2301 2306 # Load the parameter given as a variable. If not a string,
2302 2307 # process it as an object instead (below)
2303 2308
2304 2309 #print '*** args',args,'type',type(args) # dbg
2305 2310 data = eval(args,self.shell.user_ns)
2306 2311 if not type(data) in StringTypes:
2307 2312 raise DataIsObject
2308 2313
2309 2314 except (NameError,SyntaxError):
2310 2315 # given argument is not a variable, try as a filename
2311 2316 filename = make_filename(args)
2312 2317 if filename is None:
2313 2318 warn("Argument given (%s) can't be found as a variable "
2314 2319 "or as a filename." % args)
2315 2320 return
2316 2321
2317 2322 data = ''
2318 2323 use_temp = 0
2319 2324 except DataIsObject:
2320 2325
2321 2326 # macros have a special edit function
2322 2327 if isinstance(data,Macro):
2323 2328 self._edit_macro(args,data)
2324 2329 return
2325 2330
2326 2331 # For objects, try to edit the file where they are defined
2327 2332 try:
2328 2333 filename = inspect.getabsfile(data)
2329 2334 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2330 2335 # class created by %edit? Try to find source
2331 2336 # by looking for method definitions instead, the
2332 2337 # __module__ in those classes is FakeModule.
2333 2338 attrs = [getattr(data, aname) for aname in dir(data)]
2334 2339 for attr in attrs:
2335 2340 if not inspect.ismethod(attr):
2336 2341 continue
2337 2342 filename = inspect.getabsfile(attr)
2338 2343 if filename and 'fakemodule' not in filename.lower():
2339 2344 # change the attribute to be the edit target instead
2340 2345 data = attr
2341 2346 break
2342 2347
2343 2348 datafile = 1
2344 2349 except TypeError:
2345 2350 filename = make_filename(args)
2346 2351 datafile = 1
2347 2352 warn('Could not find file where `%s` is defined.\n'
2348 2353 'Opening a file named `%s`' % (args,filename))
2349 2354 # Now, make sure we can actually read the source (if it was in
2350 2355 # a temp file it's gone by now).
2351 2356 if datafile:
2352 2357 try:
2353 2358 if lineno is None:
2354 2359 lineno = inspect.getsourcelines(data)[1]
2355 2360 except IOError:
2356 2361 filename = make_filename(args)
2357 2362 if filename is None:
2358 2363 warn('The file `%s` where `%s` was defined cannot '
2359 2364 'be read.' % (filename,data))
2360 2365 return
2361 2366 use_temp = 0
2362 2367 else:
2363 2368 data = ''
2364 2369
2365 2370 if use_temp:
2366 2371 filename = self.shell.mktempfile(data)
2367 2372 print 'IPython will make a temporary file named:',filename
2368 2373
2369 2374 # do actual editing here
2370 2375 print 'Editing...',
2371 2376 sys.stdout.flush()
2372 2377 try:
2373 2378 self.shell.hooks.editor(filename,lineno)
2374 2379 except IPython.ipapi.TryNext:
2375 2380 warn('Could not open editor')
2376 2381 return
2377 2382
2378 2383 # XXX TODO: should this be generalized for all string vars?
2379 2384 # For now, this is special-cased to blocks created by cpaste
2380 2385 if args.strip() == 'pasted_block':
2381 2386 self.shell.user_ns['pasted_block'] = file_read(filename)
2382 2387
2383 2388 if opts.has_key('x'): # -x prevents actual execution
2384 2389 print
2385 2390 else:
2386 2391 print 'done. Executing edited code...'
2387 2392 if opts_r:
2388 2393 self.shell.runlines(file_read(filename))
2389 2394 else:
2390 2395 self.shell.safe_execfile(filename,self.shell.user_ns,
2391 2396 self.shell.user_ns)
2392 2397
2393 2398
2394 2399 if use_temp:
2395 2400 try:
2396 2401 return open(filename).read()
2397 2402 except IOError,msg:
2398 2403 if msg.filename == filename:
2399 2404 warn('File not found. Did you forget to save?')
2400 2405 return
2401 2406 else:
2402 2407 self.shell.showtraceback()
2403 2408
2404 2409 def magic_xmode(self,parameter_s = ''):
2405 2410 """Switch modes for the exception handlers.
2406 2411
2407 2412 Valid modes: Plain, Context and Verbose.
2408 2413
2409 2414 If called without arguments, acts as a toggle."""
2410 2415
2411 2416 def xmode_switch_err(name):
2412 2417 warn('Error changing %s exception modes.\n%s' %
2413 2418 (name,sys.exc_info()[1]))
2414 2419
2415 2420 shell = self.shell
2416 2421 new_mode = parameter_s.strip().capitalize()
2417 2422 try:
2418 2423 shell.InteractiveTB.set_mode(mode=new_mode)
2419 2424 print 'Exception reporting mode:',shell.InteractiveTB.mode
2420 2425 except:
2421 2426 xmode_switch_err('user')
2422 2427
2423 2428 # threaded shells use a special handler in sys.excepthook
2424 2429 if shell.isthreaded:
2425 2430 try:
2426 2431 shell.sys_excepthook.set_mode(mode=new_mode)
2427 2432 except:
2428 2433 xmode_switch_err('threaded')
2429 2434
2430 2435 def magic_colors(self,parameter_s = ''):
2431 2436 """Switch color scheme for prompts, info system and exception handlers.
2432 2437
2433 2438 Currently implemented schemes: NoColor, Linux, LightBG.
2434 2439
2435 2440 Color scheme names are not case-sensitive."""
2436 2441
2437 2442 def color_switch_err(name):
2438 2443 warn('Error changing %s color schemes.\n%s' %
2439 2444 (name,sys.exc_info()[1]))
2440 2445
2441 2446
2442 2447 new_scheme = parameter_s.strip()
2443 2448 if not new_scheme:
2444 2449 raise UsageError(
2445 2450 "%colors: you must specify a color scheme. See '%colors?'")
2446 2451 return
2447 2452 # local shortcut
2448 2453 shell = self.shell
2449 2454
2450 2455 import IPython.rlineimpl as readline
2451 2456
2452 2457 if not readline.have_readline and sys.platform == "win32":
2453 2458 msg = """\
2454 2459 Proper color support under MS Windows requires the pyreadline library.
2455 2460 You can find it at:
2456 2461 http://ipython.scipy.org/moin/PyReadline/Intro
2457 2462 Gary's readline needs the ctypes module, from:
2458 2463 http://starship.python.net/crew/theller/ctypes
2459 2464 (Note that ctypes is already part of Python versions 2.5 and newer).
2460 2465
2461 2466 Defaulting color scheme to 'NoColor'"""
2462 2467 new_scheme = 'NoColor'
2463 2468 warn(msg)
2464 2469
2465 2470 # readline option is 0
2466 2471 if not shell.has_readline:
2467 2472 new_scheme = 'NoColor'
2468 2473
2469 2474 # Set prompt colors
2470 2475 try:
2471 2476 shell.outputcache.set_colors(new_scheme)
2472 2477 except:
2473 2478 color_switch_err('prompt')
2474 2479 else:
2475 2480 shell.rc.colors = \
2476 2481 shell.outputcache.color_table.active_scheme_name
2477 2482 # Set exception colors
2478 2483 try:
2479 2484 shell.InteractiveTB.set_colors(scheme = new_scheme)
2480 2485 shell.SyntaxTB.set_colors(scheme = new_scheme)
2481 2486 except:
2482 2487 color_switch_err('exception')
2483 2488
2484 2489 # threaded shells use a verbose traceback in sys.excepthook
2485 2490 if shell.isthreaded:
2486 2491 try:
2487 2492 shell.sys_excepthook.set_colors(scheme=new_scheme)
2488 2493 except:
2489 2494 color_switch_err('system exception handler')
2490 2495
2491 2496 # Set info (for 'object?') colors
2492 2497 if shell.rc.color_info:
2493 2498 try:
2494 2499 shell.inspector.set_active_scheme(new_scheme)
2495 2500 except:
2496 2501 color_switch_err('object inspector')
2497 2502 else:
2498 2503 shell.inspector.set_active_scheme('NoColor')
2499 2504
2500 2505 def magic_color_info(self,parameter_s = ''):
2501 2506 """Toggle color_info.
2502 2507
2503 2508 The color_info configuration parameter controls whether colors are
2504 2509 used for displaying object details (by things like %psource, %pfile or
2505 2510 the '?' system). This function toggles this value with each call.
2506 2511
2507 2512 Note that unless you have a fairly recent pager (less works better
2508 2513 than more) in your system, using colored object information displays
2509 2514 will not work properly. Test it and see."""
2510 2515
2511 2516 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2512 2517 self.magic_colors(self.shell.rc.colors)
2513 2518 print 'Object introspection functions have now coloring:',
2514 2519 print ['OFF','ON'][self.shell.rc.color_info]
2515 2520
2516 2521 def magic_Pprint(self, parameter_s=''):
2517 2522 """Toggle pretty printing on/off."""
2518 2523
2519 2524 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2520 2525 print 'Pretty printing has been turned', \
2521 2526 ['OFF','ON'][self.shell.rc.pprint]
2522 2527
2523 2528 def magic_exit(self, parameter_s=''):
2524 2529 """Exit IPython, confirming if configured to do so.
2525 2530
2526 2531 You can configure whether IPython asks for confirmation upon exit by
2527 2532 setting the confirm_exit flag in the ipythonrc file."""
2528 2533
2529 2534 self.shell.exit()
2530 2535
2531 2536 def magic_quit(self, parameter_s=''):
2532 2537 """Exit IPython, confirming if configured to do so (like %exit)"""
2533 2538
2534 2539 self.shell.exit()
2535 2540
2536 2541 def magic_Exit(self, parameter_s=''):
2537 2542 """Exit IPython without confirmation."""
2538 2543
2539 2544 self.shell.ask_exit()
2540 2545
2541 2546 #......................................................................
2542 2547 # Functions to implement unix shell-type things
2543 2548
2544 2549 @testdec.skip_doctest
2545 2550 def magic_alias(self, parameter_s = ''):
2546 2551 """Define an alias for a system command.
2547 2552
2548 2553 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2549 2554
2550 2555 Then, typing 'alias_name params' will execute the system command 'cmd
2551 2556 params' (from your underlying operating system).
2552 2557
2553 2558 Aliases have lower precedence than magic functions and Python normal
2554 2559 variables, so if 'foo' is both a Python variable and an alias, the
2555 2560 alias can not be executed until 'del foo' removes the Python variable.
2556 2561
2557 2562 You can use the %l specifier in an alias definition to represent the
2558 2563 whole line when the alias is called. For example:
2559 2564
2560 2565 In [2]: alias all echo "Input in brackets: <%l>"
2561 2566 In [3]: all hello world
2562 2567 Input in brackets: <hello world>
2563 2568
2564 2569 You can also define aliases with parameters using %s specifiers (one
2565 2570 per parameter):
2566 2571
2567 2572 In [1]: alias parts echo first %s second %s
2568 2573 In [2]: %parts A B
2569 2574 first A second B
2570 2575 In [3]: %parts A
2571 2576 Incorrect number of arguments: 2 expected.
2572 2577 parts is an alias to: 'echo first %s second %s'
2573 2578
2574 2579 Note that %l and %s are mutually exclusive. You can only use one or
2575 2580 the other in your aliases.
2576 2581
2577 2582 Aliases expand Python variables just like system calls using ! or !!
2578 2583 do: all expressions prefixed with '$' get expanded. For details of
2579 2584 the semantic rules, see PEP-215:
2580 2585 http://www.python.org/peps/pep-0215.html. This is the library used by
2581 2586 IPython for variable expansion. If you want to access a true shell
2582 2587 variable, an extra $ is necessary to prevent its expansion by IPython:
2583 2588
2584 2589 In [6]: alias show echo
2585 2590 In [7]: PATH='A Python string'
2586 2591 In [8]: show $PATH
2587 2592 A Python string
2588 2593 In [9]: show $$PATH
2589 2594 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2590 2595
2591 2596 You can use the alias facility to acess all of $PATH. See the %rehash
2592 2597 and %rehashx functions, which automatically create aliases for the
2593 2598 contents of your $PATH.
2594 2599
2595 2600 If called with no parameters, %alias prints the current alias table."""
2596 2601
2597 2602 par = parameter_s.strip()
2598 2603 if not par:
2599 2604 stored = self.db.get('stored_aliases', {} )
2600 2605 atab = self.shell.alias_table
2601 2606 aliases = atab.keys()
2602 2607 aliases.sort()
2603 2608 res = []
2604 2609 showlast = []
2605 2610 for alias in aliases:
2606 2611 special = False
2607 2612 try:
2608 2613 tgt = atab[alias][1]
2609 2614 except (TypeError, AttributeError):
2610 2615 # unsubscriptable? probably a callable
2611 2616 tgt = atab[alias]
2612 2617 special = True
2613 2618 # 'interesting' aliases
2614 2619 if (alias in stored or
2615 2620 special or
2616 2621 alias.lower() != os.path.splitext(tgt)[0].lower() or
2617 2622 ' ' in tgt):
2618 2623 showlast.append((alias, tgt))
2619 2624 else:
2620 2625 res.append((alias, tgt ))
2621 2626
2622 2627 # show most interesting aliases last
2623 2628 res.extend(showlast)
2624 2629 print "Total number of aliases:",len(aliases)
2625 2630 return res
2626 2631 try:
2627 2632 alias,cmd = par.split(None,1)
2628 2633 except:
2629 2634 print OInspect.getdoc(self.magic_alias)
2630 2635 else:
2631 2636 nargs = cmd.count('%s')
2632 2637 if nargs>0 and cmd.find('%l')>=0:
2633 2638 error('The %s and %l specifiers are mutually exclusive '
2634 2639 'in alias definitions.')
2635 2640 else: # all looks OK
2636 2641 self.shell.alias_table[alias] = (nargs,cmd)
2637 2642 self.shell.alias_table_validate(verbose=0)
2638 2643 # end magic_alias
2639 2644
2640 2645 def magic_unalias(self, parameter_s = ''):
2641 2646 """Remove an alias"""
2642 2647
2643 2648 aname = parameter_s.strip()
2644 2649 if aname in self.shell.alias_table:
2645 2650 del self.shell.alias_table[aname]
2646 2651 stored = self.db.get('stored_aliases', {} )
2647 2652 if aname in stored:
2648 2653 print "Removing %stored alias",aname
2649 2654 del stored[aname]
2650 2655 self.db['stored_aliases'] = stored
2651 2656
2652 2657
2653 2658 def magic_rehashx(self, parameter_s = ''):
2654 2659 """Update the alias table with all executable files in $PATH.
2655 2660
2656 2661 This version explicitly checks that every entry in $PATH is a file
2657 2662 with execute access (os.X_OK), so it is much slower than %rehash.
2658 2663
2659 2664 Under Windows, it checks executability as a match agains a
2660 2665 '|'-separated string of extensions, stored in the IPython config
2661 2666 variable win_exec_ext. This defaults to 'exe|com|bat'.
2662 2667
2663 2668 This function also resets the root module cache of module completer,
2664 2669 used on slow filesystems.
2665 2670 """
2666 2671
2667 2672
2668 2673 ip = self.api
2669 2674
2670 2675 # for the benefit of module completer in ipy_completers.py
2671 2676 del ip.db['rootmodules']
2672 2677
2673 2678 path = [os.path.abspath(os.path.expanduser(p)) for p in
2674 2679 os.environ.get('PATH','').split(os.pathsep)]
2675 2680 path = filter(os.path.isdir,path)
2676 2681
2677 2682 alias_table = self.shell.alias_table
2678 2683 syscmdlist = []
2679 2684 if os.name == 'posix':
2680 2685 isexec = lambda fname:os.path.isfile(fname) and \
2681 2686 os.access(fname,os.X_OK)
2682 2687 else:
2683 2688
2684 2689 try:
2685 2690 winext = os.environ['pathext'].replace(';','|').replace('.','')
2686 2691 except KeyError:
2687 2692 winext = 'exe|com|bat|py'
2688 2693 if 'py' not in winext:
2689 2694 winext += '|py'
2690 2695 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2691 2696 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2692 2697 savedir = os.getcwd()
2693 2698 try:
2694 2699 # write the whole loop for posix/Windows so we don't have an if in
2695 2700 # the innermost part
2696 2701 if os.name == 'posix':
2697 2702 for pdir in path:
2698 2703 os.chdir(pdir)
2699 2704 for ff in os.listdir(pdir):
2700 2705 if isexec(ff) and ff not in self.shell.no_alias:
2701 2706 # each entry in the alias table must be (N,name),
2702 2707 # where N is the number of positional arguments of the
2703 2708 # alias.
2704 2709 # Dots will be removed from alias names, since ipython
2705 2710 # assumes names with dots to be python code
2706 2711 alias_table[ff.replace('.','')] = (0,ff)
2707 2712 syscmdlist.append(ff)
2708 2713 else:
2709 2714 for pdir in path:
2710 2715 os.chdir(pdir)
2711 2716 for ff in os.listdir(pdir):
2712 2717 base, ext = os.path.splitext(ff)
2713 2718 if isexec(ff) and base.lower() not in self.shell.no_alias:
2714 2719 if ext.lower() == '.exe':
2715 2720 ff = base
2716 2721 alias_table[base.lower().replace('.','')] = (0,ff)
2717 2722 syscmdlist.append(ff)
2718 2723 # Make sure the alias table doesn't contain keywords or builtins
2719 2724 self.shell.alias_table_validate()
2720 2725 # Call again init_auto_alias() so we get 'rm -i' and other
2721 2726 # modified aliases since %rehashx will probably clobber them
2722 2727
2723 2728 # no, we don't want them. if %rehashx clobbers them, good,
2724 2729 # we'll probably get better versions
2725 2730 # self.shell.init_auto_alias()
2726 2731 db = ip.db
2727 2732 db['syscmdlist'] = syscmdlist
2728 2733 finally:
2729 2734 os.chdir(savedir)
2730 2735
2731 2736 def magic_pwd(self, parameter_s = ''):
2732 2737 """Return the current working directory path."""
2733 2738 return os.getcwd()
2734 2739
2735 2740 def magic_cd(self, parameter_s=''):
2736 2741 """Change the current working directory.
2737 2742
2738 2743 This command automatically maintains an internal list of directories
2739 2744 you visit during your IPython session, in the variable _dh. The
2740 2745 command %dhist shows this history nicely formatted. You can also
2741 2746 do 'cd -<tab>' to see directory history conveniently.
2742 2747
2743 2748 Usage:
2744 2749
2745 2750 cd 'dir': changes to directory 'dir'.
2746 2751
2747 2752 cd -: changes to the last visited directory.
2748 2753
2749 2754 cd -<n>: changes to the n-th directory in the directory history.
2750 2755
2751 2756 cd --foo: change to directory that matches 'foo' in history
2752 2757
2753 2758 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2754 2759 (note: cd <bookmark_name> is enough if there is no
2755 2760 directory <bookmark_name>, but a bookmark with the name exists.)
2756 2761 'cd -b <tab>' allows you to tab-complete bookmark names.
2757 2762
2758 2763 Options:
2759 2764
2760 2765 -q: quiet. Do not print the working directory after the cd command is
2761 2766 executed. By default IPython's cd command does print this directory,
2762 2767 since the default prompts do not display path information.
2763 2768
2764 2769 Note that !cd doesn't work for this purpose because the shell where
2765 2770 !command runs is immediately discarded after executing 'command'."""
2766 2771
2767 2772 parameter_s = parameter_s.strip()
2768 2773 #bkms = self.shell.persist.get("bookmarks",{})
2769 2774
2770 2775 oldcwd = os.getcwd()
2771 2776 numcd = re.match(r'(-)(\d+)$',parameter_s)
2772 2777 # jump in directory history by number
2773 2778 if numcd:
2774 2779 nn = int(numcd.group(2))
2775 2780 try:
2776 2781 ps = self.shell.user_ns['_dh'][nn]
2777 2782 except IndexError:
2778 2783 print 'The requested directory does not exist in history.'
2779 2784 return
2780 2785 else:
2781 2786 opts = {}
2782 2787 elif parameter_s.startswith('--'):
2783 2788 ps = None
2784 2789 fallback = None
2785 2790 pat = parameter_s[2:]
2786 2791 dh = self.shell.user_ns['_dh']
2787 2792 # first search only by basename (last component)
2788 2793 for ent in reversed(dh):
2789 2794 if pat in os.path.basename(ent) and os.path.isdir(ent):
2790 2795 ps = ent
2791 2796 break
2792 2797
2793 2798 if fallback is None and pat in ent and os.path.isdir(ent):
2794 2799 fallback = ent
2795 2800
2796 2801 # if we have no last part match, pick the first full path match
2797 2802 if ps is None:
2798 2803 ps = fallback
2799 2804
2800 2805 if ps is None:
2801 2806 print "No matching entry in directory history"
2802 2807 return
2803 2808 else:
2804 2809 opts = {}
2805 2810
2806 2811
2807 2812 else:
2808 2813 #turn all non-space-escaping backslashes to slashes,
2809 2814 # for c:\windows\directory\names\
2810 2815 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2811 2816 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2812 2817 # jump to previous
2813 2818 if ps == '-':
2814 2819 try:
2815 2820 ps = self.shell.user_ns['_dh'][-2]
2816 2821 except IndexError:
2817 2822 raise UsageError('%cd -: No previous directory to change to.')
2818 2823 # jump to bookmark if needed
2819 2824 else:
2820 2825 if not os.path.isdir(ps) or opts.has_key('b'):
2821 2826 bkms = self.db.get('bookmarks', {})
2822 2827
2823 2828 if bkms.has_key(ps):
2824 2829 target = bkms[ps]
2825 2830 print '(bookmark:%s) -> %s' % (ps,target)
2826 2831 ps = target
2827 2832 else:
2828 2833 if opts.has_key('b'):
2829 2834 raise UsageError("Bookmark '%s' not found. "
2830 2835 "Use '%%bookmark -l' to see your bookmarks." % ps)
2831 2836
2832 2837 # at this point ps should point to the target dir
2833 2838 if ps:
2834 2839 try:
2835 2840 os.chdir(os.path.expanduser(ps))
2836 2841 if self.shell.rc.term_title:
2837 2842 #print 'set term title:',self.shell.rc.term_title # dbg
2838 2843 platutils.set_term_title('IPy ' + abbrev_cwd())
2839 2844 except OSError:
2840 2845 print sys.exc_info()[1]
2841 2846 else:
2842 2847 cwd = os.getcwd()
2843 2848 dhist = self.shell.user_ns['_dh']
2844 2849 if oldcwd != cwd:
2845 2850 dhist.append(cwd)
2846 2851 self.db['dhist'] = compress_dhist(dhist)[-100:]
2847 2852
2848 2853 else:
2849 2854 os.chdir(self.shell.home_dir)
2850 2855 if self.shell.rc.term_title:
2851 2856 platutils.set_term_title("IPy ~")
2852 2857 cwd = os.getcwd()
2853 2858 dhist = self.shell.user_ns['_dh']
2854 2859
2855 2860 if oldcwd != cwd:
2856 2861 dhist.append(cwd)
2857 2862 self.db['dhist'] = compress_dhist(dhist)[-100:]
2858 2863 if not 'q' in opts and self.shell.user_ns['_dh']:
2859 2864 print self.shell.user_ns['_dh'][-1]
2860 2865
2861 2866
2862 2867 def magic_env(self, parameter_s=''):
2863 2868 """List environment variables."""
2864 2869
2865 2870 return os.environ.data
2866 2871
2867 2872 def magic_pushd(self, parameter_s=''):
2868 2873 """Place the current dir on stack and change directory.
2869 2874
2870 2875 Usage:\\
2871 2876 %pushd ['dirname']
2872 2877 """
2873 2878
2874 2879 dir_s = self.shell.dir_stack
2875 2880 tgt = os.path.expanduser(parameter_s)
2876 2881 cwd = os.getcwd().replace(self.home_dir,'~')
2877 2882 if tgt:
2878 2883 self.magic_cd(parameter_s)
2879 2884 dir_s.insert(0,cwd)
2880 2885 return self.magic_dirs()
2881 2886
2882 2887 def magic_popd(self, parameter_s=''):
2883 2888 """Change to directory popped off the top of the stack.
2884 2889 """
2885 2890 if not self.shell.dir_stack:
2886 2891 raise UsageError("%popd on empty stack")
2887 2892 top = self.shell.dir_stack.pop(0)
2888 2893 self.magic_cd(top)
2889 2894 print "popd ->",top
2890 2895
2891 2896 def magic_dirs(self, parameter_s=''):
2892 2897 """Return the current directory stack."""
2893 2898
2894 2899 return self.shell.dir_stack
2895 2900
2896 2901 def magic_dhist(self, parameter_s=''):
2897 2902 """Print your history of visited directories.
2898 2903
2899 2904 %dhist -> print full history\\
2900 2905 %dhist n -> print last n entries only\\
2901 2906 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2902 2907
2903 2908 This history is automatically maintained by the %cd command, and
2904 2909 always available as the global list variable _dh. You can use %cd -<n>
2905 2910 to go to directory number <n>.
2906 2911
2907 2912 Note that most of time, you should view directory history by entering
2908 2913 cd -<TAB>.
2909 2914
2910 2915 """
2911 2916
2912 2917 dh = self.shell.user_ns['_dh']
2913 2918 if parameter_s:
2914 2919 try:
2915 2920 args = map(int,parameter_s.split())
2916 2921 except:
2917 2922 self.arg_err(Magic.magic_dhist)
2918 2923 return
2919 2924 if len(args) == 1:
2920 2925 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2921 2926 elif len(args) == 2:
2922 2927 ini,fin = args
2923 2928 else:
2924 2929 self.arg_err(Magic.magic_dhist)
2925 2930 return
2926 2931 else:
2927 2932 ini,fin = 0,len(dh)
2928 2933 nlprint(dh,
2929 2934 header = 'Directory history (kept in _dh)',
2930 2935 start=ini,stop=fin)
2931 2936
2932 2937 @testdec.skip_doctest
2933 2938 def magic_sc(self, parameter_s=''):
2934 2939 """Shell capture - execute a shell command and capture its output.
2935 2940
2936 2941 DEPRECATED. Suboptimal, retained for backwards compatibility.
2937 2942
2938 2943 You should use the form 'var = !command' instead. Example:
2939 2944
2940 2945 "%sc -l myfiles = ls ~" should now be written as
2941 2946
2942 2947 "myfiles = !ls ~"
2943 2948
2944 2949 myfiles.s, myfiles.l and myfiles.n still apply as documented
2945 2950 below.
2946 2951
2947 2952 --
2948 2953 %sc [options] varname=command
2949 2954
2950 2955 IPython will run the given command using commands.getoutput(), and
2951 2956 will then update the user's interactive namespace with a variable
2952 2957 called varname, containing the value of the call. Your command can
2953 2958 contain shell wildcards, pipes, etc.
2954 2959
2955 2960 The '=' sign in the syntax is mandatory, and the variable name you
2956 2961 supply must follow Python's standard conventions for valid names.
2957 2962
2958 2963 (A special format without variable name exists for internal use)
2959 2964
2960 2965 Options:
2961 2966
2962 2967 -l: list output. Split the output on newlines into a list before
2963 2968 assigning it to the given variable. By default the output is stored
2964 2969 as a single string.
2965 2970
2966 2971 -v: verbose. Print the contents of the variable.
2967 2972
2968 2973 In most cases you should not need to split as a list, because the
2969 2974 returned value is a special type of string which can automatically
2970 2975 provide its contents either as a list (split on newlines) or as a
2971 2976 space-separated string. These are convenient, respectively, either
2972 2977 for sequential processing or to be passed to a shell command.
2973 2978
2974 2979 For example:
2975 2980
2976 2981 # all-random
2977 2982
2978 2983 # Capture into variable a
2979 2984 In [1]: sc a=ls *py
2980 2985
2981 2986 # a is a string with embedded newlines
2982 2987 In [2]: a
2983 2988 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2984 2989
2985 2990 # which can be seen as a list:
2986 2991 In [3]: a.l
2987 2992 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2988 2993
2989 2994 # or as a whitespace-separated string:
2990 2995 In [4]: a.s
2991 2996 Out[4]: 'setup.py win32_manual_post_install.py'
2992 2997
2993 2998 # a.s is useful to pass as a single command line:
2994 2999 In [5]: !wc -l $a.s
2995 3000 146 setup.py
2996 3001 130 win32_manual_post_install.py
2997 3002 276 total
2998 3003
2999 3004 # while the list form is useful to loop over:
3000 3005 In [6]: for f in a.l:
3001 3006 ...: !wc -l $f
3002 3007 ...:
3003 3008 146 setup.py
3004 3009 130 win32_manual_post_install.py
3005 3010
3006 3011 Similiarly, the lists returned by the -l option are also special, in
3007 3012 the sense that you can equally invoke the .s attribute on them to
3008 3013 automatically get a whitespace-separated string from their contents:
3009 3014
3010 3015 In [7]: sc -l b=ls *py
3011 3016
3012 3017 In [8]: b
3013 3018 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3014 3019
3015 3020 In [9]: b.s
3016 3021 Out[9]: 'setup.py win32_manual_post_install.py'
3017 3022
3018 3023 In summary, both the lists and strings used for ouptut capture have
3019 3024 the following special attributes:
3020 3025
3021 3026 .l (or .list) : value as list.
3022 3027 .n (or .nlstr): value as newline-separated string.
3023 3028 .s (or .spstr): value as space-separated string.
3024 3029 """
3025 3030
3026 3031 opts,args = self.parse_options(parameter_s,'lv')
3027 3032 # Try to get a variable name and command to run
3028 3033 try:
3029 3034 # the variable name must be obtained from the parse_options
3030 3035 # output, which uses shlex.split to strip options out.
3031 3036 var,_ = args.split('=',1)
3032 3037 var = var.strip()
3033 3038 # But the the command has to be extracted from the original input
3034 3039 # parameter_s, not on what parse_options returns, to avoid the
3035 3040 # quote stripping which shlex.split performs on it.
3036 3041 _,cmd = parameter_s.split('=',1)
3037 3042 except ValueError:
3038 3043 var,cmd = '',''
3039 3044 # If all looks ok, proceed
3040 3045 out,err = self.shell.getoutputerror(cmd)
3041 3046 if err:
3042 3047 print >> Term.cerr,err
3043 3048 if opts.has_key('l'):
3044 3049 out = SList(out.split('\n'))
3045 3050 else:
3046 3051 out = LSString(out)
3047 3052 if opts.has_key('v'):
3048 3053 print '%s ==\n%s' % (var,pformat(out))
3049 3054 if var:
3050 3055 self.shell.user_ns.update({var:out})
3051 3056 else:
3052 3057 return out
3053 3058
3054 3059 def magic_sx(self, parameter_s=''):
3055 3060 """Shell execute - run a shell command and capture its output.
3056 3061
3057 3062 %sx command
3058 3063
3059 3064 IPython will run the given command using commands.getoutput(), and
3060 3065 return the result formatted as a list (split on '\\n'). Since the
3061 3066 output is _returned_, it will be stored in ipython's regular output
3062 3067 cache Out[N] and in the '_N' automatic variables.
3063 3068
3064 3069 Notes:
3065 3070
3066 3071 1) If an input line begins with '!!', then %sx is automatically
3067 3072 invoked. That is, while:
3068 3073 !ls
3069 3074 causes ipython to simply issue system('ls'), typing
3070 3075 !!ls
3071 3076 is a shorthand equivalent to:
3072 3077 %sx ls
3073 3078
3074 3079 2) %sx differs from %sc in that %sx automatically splits into a list,
3075 3080 like '%sc -l'. The reason for this is to make it as easy as possible
3076 3081 to process line-oriented shell output via further python commands.
3077 3082 %sc is meant to provide much finer control, but requires more
3078 3083 typing.
3079 3084
3080 3085 3) Just like %sc -l, this is a list with special attributes:
3081 3086
3082 3087 .l (or .list) : value as list.
3083 3088 .n (or .nlstr): value as newline-separated string.
3084 3089 .s (or .spstr): value as whitespace-separated string.
3085 3090
3086 3091 This is very useful when trying to use such lists as arguments to
3087 3092 system commands."""
3088 3093
3089 3094 if parameter_s:
3090 3095 out,err = self.shell.getoutputerror(parameter_s)
3091 3096 if err:
3092 3097 print >> Term.cerr,err
3093 3098 return SList(out.split('\n'))
3094 3099
3095 3100 def magic_bg(self, parameter_s=''):
3096 3101 """Run a job in the background, in a separate thread.
3097 3102
3098 3103 For example,
3099 3104
3100 3105 %bg myfunc(x,y,z=1)
3101 3106
3102 3107 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3103 3108 execution starts, a message will be printed indicating the job
3104 3109 number. If your job number is 5, you can use
3105 3110
3106 3111 myvar = jobs.result(5) or myvar = jobs[5].result
3107 3112
3108 3113 to assign this result to variable 'myvar'.
3109 3114
3110 3115 IPython has a job manager, accessible via the 'jobs' object. You can
3111 3116 type jobs? to get more information about it, and use jobs.<TAB> to see
3112 3117 its attributes. All attributes not starting with an underscore are
3113 3118 meant for public use.
3114 3119
3115 3120 In particular, look at the jobs.new() method, which is used to create
3116 3121 new jobs. This magic %bg function is just a convenience wrapper
3117 3122 around jobs.new(), for expression-based jobs. If you want to create a
3118 3123 new job with an explicit function object and arguments, you must call
3119 3124 jobs.new() directly.
3120 3125
3121 3126 The jobs.new docstring also describes in detail several important
3122 3127 caveats associated with a thread-based model for background job
3123 3128 execution. Type jobs.new? for details.
3124 3129
3125 3130 You can check the status of all jobs with jobs.status().
3126 3131
3127 3132 The jobs variable is set by IPython into the Python builtin namespace.
3128 3133 If you ever declare a variable named 'jobs', you will shadow this
3129 3134 name. You can either delete your global jobs variable to regain
3130 3135 access to the job manager, or make a new name and assign it manually
3131 3136 to the manager (stored in IPython's namespace). For example, to
3132 3137 assign the job manager to the Jobs name, use:
3133 3138
3134 3139 Jobs = __builtins__.jobs"""
3135 3140
3136 3141 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3137 3142
3138 3143 def magic_r(self, parameter_s=''):
3139 3144 """Repeat previous input.
3140 3145
3141 3146 Note: Consider using the more powerfull %rep instead!
3142 3147
3143 3148 If given an argument, repeats the previous command which starts with
3144 3149 the same string, otherwise it just repeats the previous input.
3145 3150
3146 3151 Shell escaped commands (with ! as first character) are not recognized
3147 3152 by this system, only pure python code and magic commands.
3148 3153 """
3149 3154
3150 3155 start = parameter_s.strip()
3151 3156 esc_magic = self.shell.ESC_MAGIC
3152 3157 # Identify magic commands even if automagic is on (which means
3153 3158 # the in-memory version is different from that typed by the user).
3154 3159 if self.shell.rc.automagic:
3155 3160 start_magic = esc_magic+start
3156 3161 else:
3157 3162 start_magic = start
3158 3163 # Look through the input history in reverse
3159 3164 for n in range(len(self.shell.input_hist)-2,0,-1):
3160 3165 input = self.shell.input_hist[n]
3161 3166 # skip plain 'r' lines so we don't recurse to infinity
3162 3167 if input != '_ip.magic("r")\n' and \
3163 3168 (input.startswith(start) or input.startswith(start_magic)):
3164 3169 #print 'match',`input` # dbg
3165 3170 print 'Executing:',input,
3166 3171 self.shell.runlines(input)
3167 3172 return
3168 3173 print 'No previous input matching `%s` found.' % start
3169 3174
3170 3175
3171 3176 def magic_bookmark(self, parameter_s=''):
3172 3177 """Manage IPython's bookmark system.
3173 3178
3174 3179 %bookmark <name> - set bookmark to current dir
3175 3180 %bookmark <name> <dir> - set bookmark to <dir>
3176 3181 %bookmark -l - list all bookmarks
3177 3182 %bookmark -d <name> - remove bookmark
3178 3183 %bookmark -r - remove all bookmarks
3179 3184
3180 3185 You can later on access a bookmarked folder with:
3181 3186 %cd -b <name>
3182 3187 or simply '%cd <name>' if there is no directory called <name> AND
3183 3188 there is such a bookmark defined.
3184 3189
3185 3190 Your bookmarks persist through IPython sessions, but they are
3186 3191 associated with each profile."""
3187 3192
3188 3193 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3189 3194 if len(args) > 2:
3190 3195 raise UsageError("%bookmark: too many arguments")
3191 3196
3192 3197 bkms = self.db.get('bookmarks',{})
3193 3198
3194 3199 if opts.has_key('d'):
3195 3200 try:
3196 3201 todel = args[0]
3197 3202 except IndexError:
3198 3203 raise UsageError(
3199 3204 "%bookmark -d: must provide a bookmark to delete")
3200 3205 else:
3201 3206 try:
3202 3207 del bkms[todel]
3203 3208 except KeyError:
3204 3209 raise UsageError(
3205 3210 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3206 3211
3207 3212 elif opts.has_key('r'):
3208 3213 bkms = {}
3209 3214 elif opts.has_key('l'):
3210 3215 bks = bkms.keys()
3211 3216 bks.sort()
3212 3217 if bks:
3213 3218 size = max(map(len,bks))
3214 3219 else:
3215 3220 size = 0
3216 3221 fmt = '%-'+str(size)+'s -> %s'
3217 3222 print 'Current bookmarks:'
3218 3223 for bk in bks:
3219 3224 print fmt % (bk,bkms[bk])
3220 3225 else:
3221 3226 if not args:
3222 3227 raise UsageError("%bookmark: You must specify the bookmark name")
3223 3228 elif len(args)==1:
3224 3229 bkms[args[0]] = os.getcwd()
3225 3230 elif len(args)==2:
3226 3231 bkms[args[0]] = args[1]
3227 3232 self.db['bookmarks'] = bkms
3228 3233
3229 3234 def magic_pycat(self, parameter_s=''):
3230 3235 """Show a syntax-highlighted file through a pager.
3231 3236
3232 3237 This magic is similar to the cat utility, but it will assume the file
3233 3238 to be Python source and will show it with syntax highlighting. """
3234 3239
3235 3240 try:
3236 3241 filename = get_py_filename(parameter_s)
3237 3242 cont = file_read(filename)
3238 3243 except IOError:
3239 3244 try:
3240 3245 cont = eval(parameter_s,self.user_ns)
3241 3246 except NameError:
3242 3247 cont = None
3243 3248 if cont is None:
3244 3249 print "Error: no such file or variable"
3245 3250 return
3246 3251
3247 3252 page(self.shell.pycolorize(cont),
3248 3253 screen_lines=self.shell.rc.screen_length)
3249 3254
3250 3255 def magic_cpaste(self, parameter_s=''):
3251 3256 """Allows you to paste & execute a pre-formatted code block from clipboard.
3252 3257
3253 3258 You must terminate the block with '--' (two minus-signs) alone on the
3254 3259 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3255 3260 is the new sentinel for this operation)
3256 3261
3257 3262 The block is dedented prior to execution to enable execution of method
3258 3263 definitions. '>' and '+' characters at the beginning of a line are
3259 3264 ignored, to allow pasting directly from e-mails, diff files and
3260 3265 doctests (the '...' continuation prompt is also stripped). The
3261 3266 executed block is also assigned to variable named 'pasted_block' for
3262 3267 later editing with '%edit pasted_block'.
3263 3268
3264 3269 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3265 3270 This assigns the pasted block to variable 'foo' as string, without
3266 3271 dedenting or executing it (preceding >>> and + is still stripped)
3267 3272
3268 3273 '%cpaste -r' re-executes the block previously entered by cpaste.
3269 3274
3270 3275 Do not be alarmed by garbled output on Windows (it's a readline bug).
3271 3276 Just press enter and type -- (and press enter again) and the block
3272 3277 will be what was just pasted.
3273 3278
3274 3279 IPython statements (magics, shell escapes) are not supported (yet).
3275 3280 """
3276 3281 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3277 3282 par = args.strip()
3278 3283 if opts.has_key('r'):
3279 3284 b = self.user_ns.get('pasted_block', None)
3280 3285 if b is None:
3281 3286 raise UsageError('No previous pasted block available')
3282 3287 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3283 3288 exec b in self.user_ns
3284 3289 return
3285 3290
3286 3291 sentinel = opts.get('s','--')
3287 3292
3288 3293 # Regular expressions that declare text we strip from the input:
3289 3294 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3290 3295 r'^\s*(\s?>)+', # Python input prompt
3291 3296 r'^\s*\.{3,}', # Continuation prompts
3292 3297 r'^\++',
3293 3298 ]
3294 3299
3295 3300 strip_from_start = map(re.compile,strip_re)
3296 3301
3297 3302 from IPython import iplib
3298 3303 lines = []
3299 3304 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3300 3305 while 1:
3301 3306 l = iplib.raw_input_original(':')
3302 3307 if l ==sentinel:
3303 3308 break
3304 3309
3305 3310 for pat in strip_from_start:
3306 3311 l = pat.sub('',l)
3307 3312 lines.append(l)
3308 3313
3309 3314 block = "\n".join(lines) + '\n'
3310 3315 #print "block:\n",block
3311 3316 if not par:
3312 3317 b = textwrap.dedent(block)
3313 3318 self.user_ns['pasted_block'] = b
3314 3319 exec b in self.user_ns
3315 3320 else:
3316 3321 self.user_ns[par] = SList(block.splitlines())
3317 3322 print "Block assigned to '%s'" % par
3318 3323
3319 3324 def magic_quickref(self,arg):
3320 3325 """ Show a quick reference sheet """
3321 3326 import IPython.usage
3322 3327 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3323 3328
3324 3329 page(qr)
3325 3330
3326 3331 def magic_upgrade(self,arg):
3327 3332 """ Upgrade your IPython installation
3328 3333
3329 3334 This will copy the config files that don't yet exist in your
3330 3335 ipython dir from the system config dir. Use this after upgrading
3331 3336 IPython if you don't wish to delete your .ipython dir.
3332 3337
3333 3338 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3334 3339 new users)
3335 3340
3336 3341 """
3337 3342 ip = self.getapi()
3338 3343 ipinstallation = path(IPython.__file__).dirname()
3339 3344 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3340 3345 src_config = ipinstallation / 'UserConfig'
3341 3346 userdir = path(ip.options.ipythondir)
3342 3347 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3343 3348 print ">",cmd
3344 3349 shell(cmd)
3345 3350 if arg == '-nolegacy':
3346 3351 legacy = userdir.files('ipythonrc*')
3347 3352 print "Nuking legacy files:",legacy
3348 3353
3349 3354 [p.remove() for p in legacy]
3350 3355 suffix = (sys.platform == 'win32' and '.ini' or '')
3351 3356 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3352 3357
3353 3358
3354 3359 def magic_doctest_mode(self,parameter_s=''):
3355 3360 """Toggle doctest mode on and off.
3356 3361
3357 3362 This mode allows you to toggle the prompt behavior between normal
3358 3363 IPython prompts and ones that are as similar to the default IPython
3359 3364 interpreter as possible.
3360 3365
3361 3366 It also supports the pasting of code snippets that have leading '>>>'
3362 3367 and '...' prompts in them. This means that you can paste doctests from
3363 3368 files or docstrings (even if they have leading whitespace), and the
3364 3369 code will execute correctly. You can then use '%history -tn' to see
3365 3370 the translated history without line numbers; this will give you the
3366 3371 input after removal of all the leading prompts and whitespace, which
3367 3372 can be pasted back into an editor.
3368 3373
3369 3374 With these features, you can switch into this mode easily whenever you
3370 3375 need to do testing and changes to doctests, without having to leave
3371 3376 your existing IPython session.
3372 3377 """
3373 3378
3374 3379 # XXX - Fix this to have cleaner activate/deactivate calls.
3375 3380 from IPython.Extensions import InterpreterPasteInput as ipaste
3376 3381 from IPython.ipstruct import Struct
3377 3382
3378 3383 # Shorthands
3379 3384 shell = self.shell
3380 3385 oc = shell.outputcache
3381 3386 rc = shell.rc
3382 3387 meta = shell.meta
3383 3388 # dstore is a data store kept in the instance metadata bag to track any
3384 3389 # changes we make, so we can undo them later.
3385 3390 dstore = meta.setdefault('doctest_mode',Struct())
3386 3391 save_dstore = dstore.setdefault
3387 3392
3388 3393 # save a few values we'll need to recover later
3389 3394 mode = save_dstore('mode',False)
3390 3395 save_dstore('rc_pprint',rc.pprint)
3391 3396 save_dstore('xmode',shell.InteractiveTB.mode)
3392 3397 save_dstore('rc_separate_out',rc.separate_out)
3393 3398 save_dstore('rc_separate_out2',rc.separate_out2)
3394 3399 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3395 3400 save_dstore('rc_separate_in',rc.separate_in)
3396 3401
3397 3402 if mode == False:
3398 3403 # turn on
3399 3404 ipaste.activate_prefilter()
3400 3405
3401 3406 oc.prompt1.p_template = '>>> '
3402 3407 oc.prompt2.p_template = '... '
3403 3408 oc.prompt_out.p_template = ''
3404 3409
3405 3410 # Prompt separators like plain python
3406 3411 oc.input_sep = oc.prompt1.sep = ''
3407 3412 oc.output_sep = ''
3408 3413 oc.output_sep2 = ''
3409 3414
3410 3415 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3411 3416 oc.prompt_out.pad_left = False
3412 3417
3413 3418 rc.pprint = False
3414 3419
3415 3420 shell.magic_xmode('Plain')
3416 3421
3417 3422 else:
3418 3423 # turn off
3419 3424 ipaste.deactivate_prefilter()
3420 3425
3421 3426 oc.prompt1.p_template = rc.prompt_in1
3422 3427 oc.prompt2.p_template = rc.prompt_in2
3423 3428 oc.prompt_out.p_template = rc.prompt_out
3424 3429
3425 3430 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3426 3431
3427 3432 oc.output_sep = dstore.rc_separate_out
3428 3433 oc.output_sep2 = dstore.rc_separate_out2
3429 3434
3430 3435 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3431 3436 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3432 3437
3433 3438 rc.pprint = dstore.rc_pprint
3434 3439
3435 3440 shell.magic_xmode(dstore.xmode)
3436 3441
3437 3442 # Store new mode and inform
3438 3443 dstore.mode = bool(1-int(mode))
3439 3444 print 'Doctest mode is:',
3440 3445 print ['OFF','ON'][dstore.mode]
3441 3446
3442 3447 # end Magic
@@ -1,2839 +1,2865 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.4 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8 """
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #
17 17 # Note: this code originally subclassed code.InteractiveConsole from the
18 18 # Python standard library. Over time, all of that class has been copied
19 19 # verbatim here for modifications which could not be accomplished by
20 20 # subclassing. At this point, there are no dependencies at all on the code
21 21 # module anymore (it is not even imported). The Python License (sec. 2)
22 22 # allows for this, but it's always nice to acknowledge credit where credit is
23 23 # due.
24 24 #*****************************************************************************
25 25
26 26 #****************************************************************************
27 27 # Modules and globals
28 28
29 29 # Python standard modules
30 30 import __main__
31 31 import __builtin__
32 32 import StringIO
33 33 import bdb
34 34 import cPickle as pickle
35 35 import codeop
36 36 import exceptions
37 37 import glob
38 38 import inspect
39 39 import keyword
40 40 import new
41 41 import os
42 42 import pydoc
43 43 import re
44 44 import shutil
45 45 import string
46 46 import sys
47 47 import tempfile
48 48 import traceback
49 49 import types
50 50 from pprint import pprint, pformat
51 51
52 52 # IPython's own modules
53 53 #import IPython
54 54 from IPython import Debugger,OInspect,PyColorize,ultraTB
55 55 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
56 56 from IPython.Extensions import pickleshare
57 from IPython.FakeModule import FakeModule
57 from IPython.FakeModule import FakeModule, init_fakemod_dict
58 58 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
59 59 from IPython.Logger import Logger
60 60 from IPython.Magic import Magic
61 61 from IPython.Prompts import CachedOutput
62 62 from IPython.ipstruct import Struct
63 63 from IPython.background_jobs import BackgroundJobManager
64 64 from IPython.usage import cmd_line_usage,interactive_usage
65 65 from IPython.genutils import *
66 66 from IPython.strdispatch import StrDispatch
67 67 import IPython.ipapi
68 68 import IPython.history
69 69 import IPython.prefilter as prefilter
70 70 import IPython.shadowns
71 71 # Globals
72 72
73 73 # store the builtin raw_input globally, and use this always, in case user code
74 74 # overwrites it (like wx.py.PyShell does)
75 75 raw_input_original = raw_input
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 #****************************************************************************
82 82 # Some utility function definitions
83 83
84 84 ini_spaces_re = re.compile(r'^(\s+)')
85 85
86 86 def num_ini_spaces(strng):
87 87 """Return the number of initial spaces in a string"""
88 88
89 89 ini_spaces = ini_spaces_re.match(strng)
90 90 if ini_spaces:
91 91 return ini_spaces.end()
92 92 else:
93 93 return 0
94 94
95 95 def softspace(file, newvalue):
96 96 """Copied from code.py, to remove the dependency"""
97 97
98 98 oldvalue = 0
99 99 try:
100 100 oldvalue = file.softspace
101 101 except AttributeError:
102 102 pass
103 103 try:
104 104 file.softspace = newvalue
105 105 except (AttributeError, TypeError):
106 106 # "attribute-less object" or "read-only attributes"
107 107 pass
108 108 return oldvalue
109 109
110 110
111 111 def user_setup(ipythondir,rc_suffix,mode='install',interactive=True):
112 112 """Install or upgrade the user configuration directory.
113 113
114 114 Can be called when running for the first time or to upgrade the user's
115 115 .ipython/ directory.
116 116
117 117 Parameters
118 118 ----------
119 119 ipythondir : path
120 120 The directory to be used for installation/upgrade. In 'install' mode,
121 121 if this path already exists, the function exits immediately.
122 122
123 123 rc_suffix : str
124 124 Extension for the config files. On *nix platforms it is typically the
125 125 empty string, while Windows normally uses '.ini'.
126 126
127 127 mode : str, optional
128 128 Valid modes are 'install' and 'upgrade'.
129 129
130 130 interactive : bool, optional
131 131 If False, do not wait for user input on any errors. Normally after
132 132 printing its status information, this function waits for the user to
133 133 hit Return before proceeding. This is because the default use case is
134 134 when first installing the IPython configuration, so we want the user to
135 135 acknowledge the initial message, which contains some useful
136 136 information.
137 137 """
138 138
139 139 # For automatic use, deactivate all i/o
140 140 if interactive:
141 141 def wait():
142 142 try:
143 143 raw_input("Please press <RETURN> to start IPython.")
144 144 except EOFError:
145 145 print >> Term.cout
146 146 print '*'*70
147 147
148 148 def printf(s):
149 149 print s
150 150 else:
151 151 wait = lambda : None
152 152 printf = lambda s : None
153 153
154 154 # Install mode should be re-entrant: if the install dir already exists,
155 155 # bail out cleanly
156 156 if mode == 'install' and os.path.isdir(ipythondir):
157 157 return
158 158
159 159 cwd = os.getcwd() # remember where we started
160 160 glb = glob.glob
161 161
162 162 printf('*'*70)
163 163 if mode == 'install':
164 164 printf(
165 165 """Welcome to IPython. I will try to create a personal configuration directory
166 166 where you can customize many aspects of IPython's functionality in:\n""")
167 167 else:
168 168 printf('I am going to upgrade your configuration in:')
169 169
170 170 printf(ipythondir)
171 171
172 172 rcdirend = os.path.join('IPython','UserConfig')
173 173 cfg = lambda d: os.path.join(d,rcdirend)
174 174 try:
175 175 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
176 176 printf("Initializing from configuration: %s" % rcdir)
177 177 except IndexError:
178 178 warning = """
179 179 Installation error. IPython's directory was not found.
180 180
181 181 Check the following:
182 182
183 183 The ipython/IPython directory should be in a directory belonging to your
184 184 PYTHONPATH environment variable (that is, it should be in a directory
185 185 belonging to sys.path). You can copy it explicitly there or just link to it.
186 186
187 187 IPython will create a minimal default configuration for you.
188 188
189 189 """
190 190 warn(warning)
191 191 wait()
192 192
193 193 if sys.platform =='win32':
194 194 inif = 'ipythonrc.ini'
195 195 else:
196 196 inif = 'ipythonrc'
197 197 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
198 198 inif : '# intentionally left blank' }
199 199 os.makedirs(ipythondir, mode = 0777)
200 200 for f, cont in minimal_setup.items():
201 201 # In 2.5, this can be more cleanly done using 'with'
202 202 fobj = file(ipythondir + '/' + f,'w')
203 203 fobj.write(cont)
204 204 fobj.close()
205 205
206 206 return
207 207
208 208 if mode == 'install':
209 209 try:
210 210 shutil.copytree(rcdir,ipythondir)
211 211 os.chdir(ipythondir)
212 212 rc_files = glb("ipythonrc*")
213 213 for rc_file in rc_files:
214 214 os.rename(rc_file,rc_file+rc_suffix)
215 215 except:
216 216 warning = """
217 217
218 218 There was a problem with the installation:
219 219 %s
220 220 Try to correct it or contact the developers if you think it's a bug.
221 221 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
222 222 warn(warning)
223 223 wait()
224 224 return
225 225
226 226 elif mode == 'upgrade':
227 227 try:
228 228 os.chdir(ipythondir)
229 229 except:
230 230 printf("""
231 231 Can not upgrade: changing to directory %s failed. Details:
232 232 %s
233 233 """ % (ipythondir,sys.exc_info()[1]) )
234 234 wait()
235 235 return
236 236 else:
237 237 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
238 238 for new_full_path in sources:
239 239 new_filename = os.path.basename(new_full_path)
240 240 if new_filename.startswith('ipythonrc'):
241 241 new_filename = new_filename + rc_suffix
242 242 # The config directory should only contain files, skip any
243 243 # directories which may be there (like CVS)
244 244 if os.path.isdir(new_full_path):
245 245 continue
246 246 if os.path.exists(new_filename):
247 247 old_file = new_filename+'.old'
248 248 if os.path.exists(old_file):
249 249 os.remove(old_file)
250 250 os.rename(new_filename,old_file)
251 251 shutil.copy(new_full_path,new_filename)
252 252 else:
253 253 raise ValueError('unrecognized mode for install: %r' % mode)
254 254
255 255 # Fix line-endings to those native to each platform in the config
256 256 # directory.
257 257 try:
258 258 os.chdir(ipythondir)
259 259 except:
260 260 printf("""
261 261 Problem: changing to directory %s failed.
262 262 Details:
263 263 %s
264 264
265 265 Some configuration files may have incorrect line endings. This should not
266 266 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) )
267 267 wait()
268 268 else:
269 269 for fname in glb('ipythonrc*'):
270 270 try:
271 271 native_line_ends(fname,backup=0)
272 272 except IOError:
273 273 pass
274 274
275 275 if mode == 'install':
276 276 printf("""
277 277 Successful installation!
278 278
279 279 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
280 280 IPython manual (there are both HTML and PDF versions supplied with the
281 281 distribution) to make sure that your system environment is properly configured
282 282 to take advantage of IPython's features.
283 283
284 284 Important note: the configuration system has changed! The old system is
285 285 still in place, but its setting may be partly overridden by the settings in
286 286 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
287 287 if some of the new settings bother you.
288 288
289 289 """)
290 290 else:
291 291 printf("""
292 292 Successful upgrade!
293 293
294 294 All files in your directory:
295 295 %(ipythondir)s
296 296 which would have been overwritten by the upgrade were backed up with a .old
297 297 extension. If you had made particular customizations in those files you may
298 298 want to merge them back into the new files.""" % locals() )
299 299 wait()
300 300 os.chdir(cwd)
301 301
302 302 #****************************************************************************
303 303 # Local use exceptions
304 304 class SpaceInInput(exceptions.Exception): pass
305 305
306 306
307 307 #****************************************************************************
308 308 # Local use classes
309 309 class Bunch: pass
310 310
311 311 class Undefined: pass
312 312
313 313 class Quitter(object):
314 314 """Simple class to handle exit, similar to Python 2.5's.
315 315
316 316 It handles exiting in an ipython-safe manner, which the one in Python 2.5
317 317 doesn't do (obviously, since it doesn't know about ipython)."""
318 318
319 319 def __init__(self,shell,name):
320 320 self.shell = shell
321 321 self.name = name
322 322
323 323 def __repr__(self):
324 324 return 'Type %s() to exit.' % self.name
325 325 __str__ = __repr__
326 326
327 327 def __call__(self):
328 328 self.shell.exit()
329 329
330 330 class InputList(list):
331 331 """Class to store user input.
332 332
333 333 It's basically a list, but slices return a string instead of a list, thus
334 334 allowing things like (assuming 'In' is an instance):
335 335
336 336 exec In[4:7]
337 337
338 338 or
339 339
340 340 exec In[5:9] + In[14] + In[21:25]"""
341 341
342 342 def __getslice__(self,i,j):
343 343 return ''.join(list.__getslice__(self,i,j))
344 344
345 345 class SyntaxTB(ultraTB.ListTB):
346 346 """Extension which holds some state: the last exception value"""
347 347
348 348 def __init__(self,color_scheme = 'NoColor'):
349 349 ultraTB.ListTB.__init__(self,color_scheme)
350 350 self.last_syntax_error = None
351 351
352 352 def __call__(self, etype, value, elist):
353 353 self.last_syntax_error = value
354 354 ultraTB.ListTB.__call__(self,etype,value,elist)
355 355
356 356 def clear_err_state(self):
357 357 """Return the current error state and clear it"""
358 358 e = self.last_syntax_error
359 359 self.last_syntax_error = None
360 360 return e
361 361
362 362 #****************************************************************************
363 363 # Main IPython class
364 364
365 365 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
366 366 # until a full rewrite is made. I've cleaned all cross-class uses of
367 367 # attributes and methods, but too much user code out there relies on the
368 368 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
369 369 #
370 370 # But at least now, all the pieces have been separated and we could, in
371 371 # principle, stop using the mixin. This will ease the transition to the
372 372 # chainsaw branch.
373 373
374 374 # For reference, the following is the list of 'self.foo' uses in the Magic
375 375 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
376 376 # class, to prevent clashes.
377 377
378 378 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
379 379 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
380 380 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
381 381 # 'self.value']
382 382
383 383 class InteractiveShell(object,Magic):
384 384 """An enhanced console for Python."""
385 385
386 386 # class attribute to indicate whether the class supports threads or not.
387 387 # Subclasses with thread support should override this as needed.
388 388 isthreaded = False
389 389
390 390 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
391 391 user_ns=None,user_global_ns=None,banner2='',
392 392 custom_exceptions=((),None),embedded=False):
393 393
394 394 # log system
395 395 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
396 396
397 397 # Job manager (for jobs run as background threads)
398 398 self.jobs = BackgroundJobManager()
399 399
400 400 # Store the actual shell's name
401 401 self.name = name
402 402 self.more = False
403 403
404 404 # We need to know whether the instance is meant for embedding, since
405 405 # global/local namespaces need to be handled differently in that case
406 406 self.embedded = embedded
407 407 if embedded:
408 408 # Control variable so users can, from within the embedded instance,
409 409 # permanently deactivate it.
410 410 self.embedded_active = True
411 411
412 412 # command compiler
413 413 self.compile = codeop.CommandCompiler()
414 414
415 415 # User input buffer
416 416 self.buffer = []
417 417
418 418 # Default name given in compilation of code
419 419 self.filename = '<ipython console>'
420 420
421 421 # Install our own quitter instead of the builtins. For python2.3-2.4,
422 422 # this brings in behavior like 2.5, and for 2.5 it's identical.
423 423 __builtin__.exit = Quitter(self,'exit')
424 424 __builtin__.quit = Quitter(self,'quit')
425 425
426 426 # Make an empty namespace, which extension writers can rely on both
427 427 # existing and NEVER being used by ipython itself. This gives them a
428 428 # convenient location for storing additional information and state
429 429 # their extensions may require, without fear of collisions with other
430 430 # ipython names that may develop later.
431 431 self.meta = Struct()
432 432
433 433 # Create the namespace where the user will operate. user_ns is
434 434 # normally the only one used, and it is passed to the exec calls as
435 435 # the locals argument. But we do carry a user_global_ns namespace
436 436 # given as the exec 'globals' argument, This is useful in embedding
437 437 # situations where the ipython shell opens in a context where the
438 438 # distinction between locals and globals is meaningful. For
439 439 # non-embedded contexts, it is just the same object as the user_ns dict.
440 440
441 441 # FIXME. For some strange reason, __builtins__ is showing up at user
442 442 # level as a dict instead of a module. This is a manual fix, but I
443 443 # should really track down where the problem is coming from. Alex
444 444 # Schmolck reported this problem first.
445 445
446 446 # A useful post by Alex Martelli on this topic:
447 447 # Re: inconsistent value from __builtins__
448 448 # Von: Alex Martelli <aleaxit@yahoo.com>
449 449 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
450 450 # Gruppen: comp.lang.python
451 451
452 452 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
453 453 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
454 454 # > <type 'dict'>
455 455 # > >>> print type(__builtins__)
456 456 # > <type 'module'>
457 457 # > Is this difference in return value intentional?
458 458
459 459 # Well, it's documented that '__builtins__' can be either a dictionary
460 460 # or a module, and it's been that way for a long time. Whether it's
461 461 # intentional (or sensible), I don't know. In any case, the idea is
462 462 # that if you need to access the built-in namespace directly, you
463 463 # should start with "import __builtin__" (note, no 's') which will
464 464 # definitely give you a module. Yeah, it's somewhat confusing:-(.
465 465
466 466 # These routines return properly built dicts as needed by the rest of
467 467 # the code, and can also be used by extension writers to generate
468 468 # properly initialized namespaces.
469 469 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
470 470 user_global_ns)
471 471
472 472 # Assign namespaces
473 473 # This is the namespace where all normal user variables live
474 474 self.user_ns = user_ns
475 475 self.user_global_ns = user_global_ns
476 476
477 477 # An auxiliary namespace that checks what parts of the user_ns were
478 478 # loaded at startup, so we can list later only variables defined in
479 479 # actual interactive use. Since it is always a subset of user_ns, it
480 480 # doesn't need to be seaparately tracked in the ns_table
481 481 self.user_config_ns = {}
482 482
483 483 # A namespace to keep track of internal data structures to prevent
484 484 # them from cluttering user-visible stuff. Will be updated later
485 485 self.internal_ns = {}
486 486
487 487 # Namespace of system aliases. Each entry in the alias
488 488 # table must be a 2-tuple of the form (N,name), where N is the number
489 489 # of positional arguments of the alias.
490 490 self.alias_table = {}
491 491
492 492 # Now that FakeModule produces a real module, we've run into a nasty
493 493 # problem: after script execution (via %run), the module where the user
494 494 # code ran is deleted. Now that this object is a true module (needed
495 495 # so docetst and other tools work correctly), the Python module
496 496 # teardown mechanism runs over it, and sets to None every variable
497 497 # present in that module. Top-level references to objects from the
498 498 # script survive, because the user_ns is updated with them. However,
499 499 # calling functions defined in the script that use other things from
500 500 # the script will fail, because the function's closure had references
501 501 # to the original objects, which are now all None. So we must protect
502 # these modules from deletion by keeping a cache. To avoid keeping
503 # stale modules around (we only need the one from the last run), we use
504 # a dict keyed with the full path to the script, so only the last
505 # version of the module is held in the cache. The %reset command will
506 # flush this cache. See the cache_main_mod() and clear_main_mod_cache()
507 # methods for details on use.
508 self._user_main_modules = {}
502 # these modules from deletion by keeping a cache.
503 #
504 # To avoid keeping stale modules around (we only need the one from the
505 # last run), we use a dict keyed with the full path to the script, so
506 # only the last version of the module is held in the cache. Note,
507 # however, that we must cache the module *namespace contents* (their
508 # __dict__). Because if we try to cache the actual modules, old ones
509 # (uncached) could be destroyed while still holding references (such as
510 # those held by GUI objects that tend to be long-lived)>
511 #
512 # The %reset command will flush this cache. See the cache_main_mod()
513 # and clear_main_mod_cache() methods for details on use.
514
515 # This is the cache used for 'main' namespaces
516 self._main_ns_cache = {}
517 # And this is the single instance of FakeModule whose __dict__ we keep
518 # copying and clearing for reuse on each %run
519 self._user_main_module = FakeModule()
509 520
510 521 # A table holding all the namespaces IPython deals with, so that
511 522 # introspection facilities can search easily.
512 523 self.ns_table = {'user':user_ns,
513 524 'user_global':user_global_ns,
514 525 'alias':self.alias_table,
515 526 'internal':self.internal_ns,
516 527 'builtin':__builtin__.__dict__
517 528 }
518 529
519 530 # Similarly, track all namespaces where references can be held and that
520 531 # we can safely clear (so it can NOT include builtin). This one can be
521 532 # a simple list.
522 533 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
523 534 self.alias_table, self.internal_ns,
524 self._user_main_modules ]
535 self._main_ns_cache ]
525 536
526 537 # We need to insert into sys.modules something that looks like a
527 538 # module but which accesses the IPython namespace, for shelve and
528 539 # pickle to work interactively. Normally they rely on getting
529 540 # everything out of __main__, but for embedding purposes each IPython
530 541 # instance has its own private namespace, so we can't go shoving
531 542 # everything into __main__.
532 543
533 544 # note, however, that we should only do this for non-embedded
534 545 # ipythons, which really mimic the __main__.__dict__ with their own
535 546 # namespace. Embedded instances, on the other hand, should not do
536 547 # this because they need to manage the user local/global namespaces
537 548 # only, but they live within a 'normal' __main__ (meaning, they
538 549 # shouldn't overtake the execution environment of the script they're
539 550 # embedded in).
540 551
541 552 if not embedded:
542 553 try:
543 554 main_name = self.user_ns['__name__']
544 555 except KeyError:
545 556 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
546 557 else:
547 558 #print "pickle hack in place" # dbg
548 559 #print 'main_name:',main_name # dbg
549 560 sys.modules[main_name] = FakeModule(self.user_ns)
550 561
551 562 # List of input with multi-line handling.
552 563 self.input_hist = InputList()
553 564 # This one will hold the 'raw' input history, without any
554 565 # pre-processing. This will allow users to retrieve the input just as
555 566 # it was exactly typed in by the user, with %hist -r.
556 567 self.input_hist_raw = InputList()
557 568
558 569 # list of visited directories
559 570 try:
560 571 self.dir_hist = [os.getcwd()]
561 572 except OSError:
562 573 self.dir_hist = []
563 574
564 575 # dict of output history
565 576 self.output_hist = {}
566 577
567 578 # Get system encoding at startup time. Certain terminals (like Emacs
568 579 # under Win32 have it set to None, and we need to have a known valid
569 580 # encoding to use in the raw_input() method
570 581 try:
571 582 self.stdin_encoding = sys.stdin.encoding or 'ascii'
572 583 except AttributeError:
573 584 self.stdin_encoding = 'ascii'
574 585
575 586 # dict of things NOT to alias (keywords, builtins and some magics)
576 587 no_alias = {}
577 588 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
578 589 for key in keyword.kwlist + no_alias_magics:
579 590 no_alias[key] = 1
580 591 no_alias.update(__builtin__.__dict__)
581 592 self.no_alias = no_alias
582 593
583 594 # Object variable to store code object waiting execution. This is
584 595 # used mainly by the multithreaded shells, but it can come in handy in
585 596 # other situations. No need to use a Queue here, since it's a single
586 597 # item which gets cleared once run.
587 598 self.code_to_run = None
588 599
589 600 # escapes for automatic behavior on the command line
590 601 self.ESC_SHELL = '!'
591 602 self.ESC_SH_CAP = '!!'
592 603 self.ESC_HELP = '?'
593 604 self.ESC_MAGIC = '%'
594 605 self.ESC_QUOTE = ','
595 606 self.ESC_QUOTE2 = ';'
596 607 self.ESC_PAREN = '/'
597 608
598 609 # And their associated handlers
599 610 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
600 611 self.ESC_QUOTE : self.handle_auto,
601 612 self.ESC_QUOTE2 : self.handle_auto,
602 613 self.ESC_MAGIC : self.handle_magic,
603 614 self.ESC_HELP : self.handle_help,
604 615 self.ESC_SHELL : self.handle_shell_escape,
605 616 self.ESC_SH_CAP : self.handle_shell_escape,
606 617 }
607 618
608 619 # class initializations
609 620 Magic.__init__(self,self)
610 621
611 622 # Python source parser/formatter for syntax highlighting
612 623 pyformat = PyColorize.Parser().format
613 624 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
614 625
615 626 # hooks holds pointers used for user-side customizations
616 627 self.hooks = Struct()
617 628
618 629 self.strdispatchers = {}
619 630
620 631 # Set all default hooks, defined in the IPython.hooks module.
621 632 hooks = IPython.hooks
622 633 for hook_name in hooks.__all__:
623 634 # default hooks have priority 100, i.e. low; user hooks should have
624 635 # 0-100 priority
625 636 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
626 637 #print "bound hook",hook_name
627 638
628 639 # Flag to mark unconditional exit
629 640 self.exit_now = False
630 641
631 642 self.usage_min = """\
632 643 An enhanced console for Python.
633 644 Some of its features are:
634 645 - Readline support if the readline library is present.
635 646 - Tab completion in the local namespace.
636 647 - Logging of input, see command-line options.
637 648 - System shell escape via ! , eg !ls.
638 649 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
639 650 - Keeps track of locally defined variables via %who, %whos.
640 651 - Show object information with a ? eg ?x or x? (use ?? for more info).
641 652 """
642 653 if usage: self.usage = usage
643 654 else: self.usage = self.usage_min
644 655
645 656 # Storage
646 657 self.rc = rc # This will hold all configuration information
647 658 self.pager = 'less'
648 659 # temporary files used for various purposes. Deleted at exit.
649 660 self.tempfiles = []
650 661
651 662 # Keep track of readline usage (later set by init_readline)
652 663 self.has_readline = False
653 664
654 665 # template for logfile headers. It gets resolved at runtime by the
655 666 # logstart method.
656 667 self.loghead_tpl = \
657 668 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
658 669 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
659 670 #log# opts = %s
660 671 #log# args = %s
661 672 #log# It is safe to make manual edits below here.
662 673 #log#-----------------------------------------------------------------------
663 674 """
664 675 # for pushd/popd management
665 676 try:
666 677 self.home_dir = get_home_dir()
667 678 except HomeDirError,msg:
668 679 fatal(msg)
669 680
670 681 self.dir_stack = []
671 682
672 683 # Functions to call the underlying shell.
673 684
674 685 # The first is similar to os.system, but it doesn't return a value,
675 686 # and it allows interpolation of variables in the user's namespace.
676 687 self.system = lambda cmd: \
677 688 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
678 689
679 690 # These are for getoutput and getoutputerror:
680 691 self.getoutput = lambda cmd: \
681 692 getoutput(self.var_expand(cmd,depth=2),
682 693 header=self.rc.system_header,
683 694 verbose=self.rc.system_verbose)
684 695
685 696 self.getoutputerror = lambda cmd: \
686 697 getoutputerror(self.var_expand(cmd,depth=2),
687 698 header=self.rc.system_header,
688 699 verbose=self.rc.system_verbose)
689 700
690 701
691 702 # keep track of where we started running (mainly for crash post-mortem)
692 703 self.starting_dir = os.getcwd()
693 704
694 705 # Various switches which can be set
695 706 self.CACHELENGTH = 5000 # this is cheap, it's just text
696 707 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
697 708 self.banner2 = banner2
698 709
699 710 # TraceBack handlers:
700 711
701 712 # Syntax error handler.
702 713 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
703 714
704 715 # The interactive one is initialized with an offset, meaning we always
705 716 # want to remove the topmost item in the traceback, which is our own
706 717 # internal code. Valid modes: ['Plain','Context','Verbose']
707 718 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
708 719 color_scheme='NoColor',
709 720 tb_offset = 1)
710 721
711 722 # IPython itself shouldn't crash. This will produce a detailed
712 723 # post-mortem if it does. But we only install the crash handler for
713 724 # non-threaded shells, the threaded ones use a normal verbose reporter
714 725 # and lose the crash handler. This is because exceptions in the main
715 726 # thread (such as in GUI code) propagate directly to sys.excepthook,
716 727 # and there's no point in printing crash dumps for every user exception.
717 728 if self.isthreaded:
718 729 ipCrashHandler = ultraTB.FormattedTB()
719 730 else:
720 731 from IPython import CrashHandler
721 732 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
722 733 self.set_crash_handler(ipCrashHandler)
723 734
724 735 # and add any custom exception handlers the user may have specified
725 736 self.set_custom_exc(*custom_exceptions)
726 737
727 738 # indentation management
728 739 self.autoindent = False
729 740 self.indent_current_nsp = 0
730 741
731 742 # Make some aliases automatically
732 743 # Prepare list of shell aliases to auto-define
733 744 if os.name == 'posix':
734 745 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
735 746 'mv mv -i','rm rm -i','cp cp -i',
736 747 'cat cat','less less','clear clear',
737 748 # a better ls
738 749 'ls ls -F',
739 750 # long ls
740 751 'll ls -lF')
741 752 # Extra ls aliases with color, which need special treatment on BSD
742 753 # variants
743 754 ls_extra = ( # color ls
744 755 'lc ls -F -o --color',
745 756 # ls normal files only
746 757 'lf ls -F -o --color %l | grep ^-',
747 758 # ls symbolic links
748 759 'lk ls -F -o --color %l | grep ^l',
749 760 # directories or links to directories,
750 761 'ldir ls -F -o --color %l | grep /$',
751 762 # things which are executable
752 763 'lx ls -F -o --color %l | grep ^-..x',
753 764 )
754 765 # The BSDs don't ship GNU ls, so they don't understand the
755 766 # --color switch out of the box
756 767 if 'bsd' in sys.platform:
757 768 ls_extra = ( # ls normal files only
758 769 'lf ls -lF | grep ^-',
759 770 # ls symbolic links
760 771 'lk ls -lF | grep ^l',
761 772 # directories or links to directories,
762 773 'ldir ls -lF | grep /$',
763 774 # things which are executable
764 775 'lx ls -lF | grep ^-..x',
765 776 )
766 777 auto_alias = auto_alias + ls_extra
767 778 elif os.name in ['nt','dos']:
768 779 auto_alias = ('ls dir /on',
769 780 'ddir dir /ad /on', 'ldir dir /ad /on',
770 781 'mkdir mkdir','rmdir rmdir','echo echo',
771 782 'ren ren','cls cls','copy copy')
772 783 else:
773 784 auto_alias = ()
774 785 self.auto_alias = [s.split(None,1) for s in auto_alias]
775 786
776 787 # Produce a public API instance
777 788 self.api = IPython.ipapi.IPApi(self)
778 789
779 790 # Initialize all user-visible namespaces
780 791 self.init_namespaces()
781 792
782 793 # Call the actual (public) initializer
783 794 self.init_auto_alias()
784 795
785 796 # track which builtins we add, so we can clean up later
786 797 self.builtins_added = {}
787 798 # This method will add the necessary builtins for operation, but
788 799 # tracking what it did via the builtins_added dict.
789 800
790 801 #TODO: remove this, redundant
791 802 self.add_builtins()
792 803 # end __init__
793 804
794 805 def var_expand(self,cmd,depth=0):
795 806 """Expand python variables in a string.
796 807
797 808 The depth argument indicates how many frames above the caller should
798 809 be walked to look for the local namespace where to expand variables.
799 810
800 811 The global namespace for expansion is always the user's interactive
801 812 namespace.
802 813 """
803 814
804 815 return str(ItplNS(cmd,
805 816 self.user_ns, # globals
806 817 # Skip our own frame in searching for locals:
807 818 sys._getframe(depth+1).f_locals # locals
808 819 ))
809 820
810 821 def pre_config_initialization(self):
811 822 """Pre-configuration init method
812 823
813 824 This is called before the configuration files are processed to
814 825 prepare the services the config files might need.
815 826
816 827 self.rc already has reasonable default values at this point.
817 828 """
818 829 rc = self.rc
819 830 try:
820 831 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
821 832 except exceptions.UnicodeDecodeError:
822 833 print "Your ipythondir can't be decoded to unicode!"
823 834 print "Please set HOME environment variable to something that"
824 835 print r"only has ASCII characters, e.g. c:\home"
825 836 print "Now it is",rc.ipythondir
826 837 sys.exit()
827 838 self.shadowhist = IPython.history.ShadowHist(self.db)
828 839
829 840 def post_config_initialization(self):
830 841 """Post configuration init method
831 842
832 843 This is called after the configuration files have been processed to
833 844 'finalize' the initialization."""
834 845
835 846 rc = self.rc
836 847
837 848 # Object inspector
838 849 self.inspector = OInspect.Inspector(OInspect.InspectColors,
839 850 PyColorize.ANSICodeColors,
840 851 'NoColor',
841 852 rc.object_info_string_level)
842 853
843 854 self.rl_next_input = None
844 855 self.rl_do_indent = False
845 856 # Load readline proper
846 857 if rc.readline:
847 858 self.init_readline()
848 859
849 860 # local shortcut, this is used a LOT
850 861 self.log = self.logger.log
851 862
852 863 # Initialize cache, set in/out prompts and printing system
853 864 self.outputcache = CachedOutput(self,
854 865 rc.cache_size,
855 866 rc.pprint,
856 867 input_sep = rc.separate_in,
857 868 output_sep = rc.separate_out,
858 869 output_sep2 = rc.separate_out2,
859 870 ps1 = rc.prompt_in1,
860 871 ps2 = rc.prompt_in2,
861 872 ps_out = rc.prompt_out,
862 873 pad_left = rc.prompts_pad_left)
863 874
864 875 # user may have over-ridden the default print hook:
865 876 try:
866 877 self.outputcache.__class__.display = self.hooks.display
867 878 except AttributeError:
868 879 pass
869 880
870 881 # I don't like assigning globally to sys, because it means when
871 882 # embedding instances, each embedded instance overrides the previous
872 883 # choice. But sys.displayhook seems to be called internally by exec,
873 884 # so I don't see a way around it. We first save the original and then
874 885 # overwrite it.
875 886 self.sys_displayhook = sys.displayhook
876 887 sys.displayhook = self.outputcache
877 888
878 889 # Do a proper resetting of doctest, including the necessary displayhook
879 890 # monkeypatching
880 891 try:
881 892 doctest_reload()
882 893 except ImportError:
883 894 warn("doctest module does not exist.")
884 895
885 896 # Set user colors (don't do it in the constructor above so that it
886 897 # doesn't crash if colors option is invalid)
887 898 self.magic_colors(rc.colors)
888 899
889 900 # Set calling of pdb on exceptions
890 901 self.call_pdb = rc.pdb
891 902
892 903 # Load user aliases
893 904 for alias in rc.alias:
894 905 self.magic_alias(alias)
895 906
896 907 self.hooks.late_startup_hook()
897 908
898 909 for cmd in self.rc.autoexec:
899 910 #print "autoexec>",cmd #dbg
900 911 self.api.runlines(cmd)
901 912
902 913 batchrun = False
903 914 for batchfile in [path(arg) for arg in self.rc.args
904 915 if arg.lower().endswith('.ipy')]:
905 916 if not batchfile.isfile():
906 917 print "No such batch file:", batchfile
907 918 continue
908 919 self.api.runlines(batchfile.text())
909 920 batchrun = True
910 921 # without -i option, exit after running the batch file
911 922 if batchrun and not self.rc.interact:
912 923 self.ask_exit()
913 924
914 925 def init_namespaces(self):
915 926 """Initialize all user-visible namespaces to their minimum defaults.
916 927
917 928 Certain history lists are also initialized here, as they effectively
918 929 act as user namespaces.
919 930
920 931 Note
921 932 ----
922 933 All data structures here are only filled in, they are NOT reset by this
923 934 method. If they were not empty before, data will simply be added to
924 935 therm.
925 936 """
926 937 # The user namespace MUST have a pointer to the shell itself.
927 938 self.user_ns[self.name] = self
928 939
929 940 # Store the public api instance
930 941 self.user_ns['_ip'] = self.api
931 942
932 943 # make global variables for user access to the histories
933 944 self.user_ns['_ih'] = self.input_hist
934 945 self.user_ns['_oh'] = self.output_hist
935 946 self.user_ns['_dh'] = self.dir_hist
936 947
937 948 # user aliases to input and output histories
938 949 self.user_ns['In'] = self.input_hist
939 950 self.user_ns['Out'] = self.output_hist
940 951
941 952 self.user_ns['_sh'] = IPython.shadowns
942 953
943 954 # Fill the history zero entry, user counter starts at 1
944 955 self.input_hist.append('\n')
945 956 self.input_hist_raw.append('\n')
946 957
947 958 def add_builtins(self):
948 959 """Store ipython references into the builtin namespace.
949 960
950 961 Some parts of ipython operate via builtins injected here, which hold a
951 962 reference to IPython itself."""
952 963
953 964 # TODO: deprecate all of these, they are unsafe
954 965 builtins_new = dict(__IPYTHON__ = self,
955 966 ip_set_hook = self.set_hook,
956 967 jobs = self.jobs,
957 968 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
958 969 ipalias = wrap_deprecated(self.ipalias),
959 970 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
960 971 #_ip = self.api
961 972 )
962 973 for biname,bival in builtins_new.items():
963 974 try:
964 975 # store the orignal value so we can restore it
965 976 self.builtins_added[biname] = __builtin__.__dict__[biname]
966 977 except KeyError:
967 978 # or mark that it wasn't defined, and we'll just delete it at
968 979 # cleanup
969 980 self.builtins_added[biname] = Undefined
970 981 __builtin__.__dict__[biname] = bival
971 982
972 983 # Keep in the builtins a flag for when IPython is active. We set it
973 984 # with setdefault so that multiple nested IPythons don't clobber one
974 985 # another. Each will increase its value by one upon being activated,
975 986 # which also gives us a way to determine the nesting level.
976 987 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
977 988
978 989 def clean_builtins(self):
979 990 """Remove any builtins which might have been added by add_builtins, or
980 991 restore overwritten ones to their previous values."""
981 992 for biname,bival in self.builtins_added.items():
982 993 if bival is Undefined:
983 994 del __builtin__.__dict__[biname]
984 995 else:
985 996 __builtin__.__dict__[biname] = bival
986 997 self.builtins_added.clear()
987 998
988 999 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
989 1000 """set_hook(name,hook) -> sets an internal IPython hook.
990 1001
991 1002 IPython exposes some of its internal API as user-modifiable hooks. By
992 1003 adding your function to one of these hooks, you can modify IPython's
993 1004 behavior to call at runtime your own routines."""
994 1005
995 1006 # At some point in the future, this should validate the hook before it
996 1007 # accepts it. Probably at least check that the hook takes the number
997 1008 # of args it's supposed to.
998 1009
999 1010 f = new.instancemethod(hook,self,self.__class__)
1000 1011
1001 1012 # check if the hook is for strdispatcher first
1002 1013 if str_key is not None:
1003 1014 sdp = self.strdispatchers.get(name, StrDispatch())
1004 1015 sdp.add_s(str_key, f, priority )
1005 1016 self.strdispatchers[name] = sdp
1006 1017 return
1007 1018 if re_key is not None:
1008 1019 sdp = self.strdispatchers.get(name, StrDispatch())
1009 1020 sdp.add_re(re.compile(re_key), f, priority )
1010 1021 self.strdispatchers[name] = sdp
1011 1022 return
1012 1023
1013 1024 dp = getattr(self.hooks, name, None)
1014 1025 if name not in IPython.hooks.__all__:
1015 1026 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
1016 1027 if not dp:
1017 1028 dp = IPython.hooks.CommandChainDispatcher()
1018 1029
1019 1030 try:
1020 1031 dp.add(f,priority)
1021 1032 except AttributeError:
1022 1033 # it was not commandchain, plain old func - replace
1023 1034 dp = f
1024 1035
1025 1036 setattr(self.hooks,name, dp)
1026 1037
1027 1038
1028 1039 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
1029 1040
1030 1041 def set_crash_handler(self,crashHandler):
1031 1042 """Set the IPython crash handler.
1032 1043
1033 1044 This must be a callable with a signature suitable for use as
1034 1045 sys.excepthook."""
1035 1046
1036 1047 # Install the given crash handler as the Python exception hook
1037 1048 sys.excepthook = crashHandler
1038 1049
1039 1050 # The instance will store a pointer to this, so that runtime code
1040 1051 # (such as magics) can access it. This is because during the
1041 1052 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1042 1053 # frameworks).
1043 1054 self.sys_excepthook = sys.excepthook
1044 1055
1045 1056
1046 1057 def set_custom_exc(self,exc_tuple,handler):
1047 1058 """set_custom_exc(exc_tuple,handler)
1048 1059
1049 1060 Set a custom exception handler, which will be called if any of the
1050 1061 exceptions in exc_tuple occur in the mainloop (specifically, in the
1051 1062 runcode() method.
1052 1063
1053 1064 Inputs:
1054 1065
1055 1066 - exc_tuple: a *tuple* of valid exceptions to call the defined
1056 1067 handler for. It is very important that you use a tuple, and NOT A
1057 1068 LIST here, because of the way Python's except statement works. If
1058 1069 you only want to trap a single exception, use a singleton tuple:
1059 1070
1060 1071 exc_tuple == (MyCustomException,)
1061 1072
1062 1073 - handler: this must be defined as a function with the following
1063 1074 basic interface: def my_handler(self,etype,value,tb).
1064 1075
1065 1076 This will be made into an instance method (via new.instancemethod)
1066 1077 of IPython itself, and it will be called if any of the exceptions
1067 1078 listed in the exc_tuple are caught. If the handler is None, an
1068 1079 internal basic one is used, which just prints basic info.
1069 1080
1070 1081 WARNING: by putting in your own exception handler into IPython's main
1071 1082 execution loop, you run a very good chance of nasty crashes. This
1072 1083 facility should only be used if you really know what you are doing."""
1073 1084
1074 1085 assert type(exc_tuple)==type(()) , \
1075 1086 "The custom exceptions must be given AS A TUPLE."
1076 1087
1077 1088 def dummy_handler(self,etype,value,tb):
1078 1089 print '*** Simple custom exception handler ***'
1079 1090 print 'Exception type :',etype
1080 1091 print 'Exception value:',value
1081 1092 print 'Traceback :',tb
1082 1093 print 'Source code :','\n'.join(self.buffer)
1083 1094
1084 1095 if handler is None: handler = dummy_handler
1085 1096
1086 1097 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1087 1098 self.custom_exceptions = exc_tuple
1088 1099
1089 1100 def set_custom_completer(self,completer,pos=0):
1090 1101 """set_custom_completer(completer,pos=0)
1091 1102
1092 1103 Adds a new custom completer function.
1093 1104
1094 1105 The position argument (defaults to 0) is the index in the completers
1095 1106 list where you want the completer to be inserted."""
1096 1107
1097 1108 newcomp = new.instancemethod(completer,self.Completer,
1098 1109 self.Completer.__class__)
1099 1110 self.Completer.matchers.insert(pos,newcomp)
1100 1111
1101 1112 def set_completer(self):
1102 1113 """reset readline's completer to be our own."""
1103 1114 self.readline.set_completer(self.Completer.complete)
1104 1115
1105 1116 def _get_call_pdb(self):
1106 1117 return self._call_pdb
1107 1118
1108 1119 def _set_call_pdb(self,val):
1109 1120
1110 1121 if val not in (0,1,False,True):
1111 1122 raise ValueError,'new call_pdb value must be boolean'
1112 1123
1113 1124 # store value in instance
1114 1125 self._call_pdb = val
1115 1126
1116 1127 # notify the actual exception handlers
1117 1128 self.InteractiveTB.call_pdb = val
1118 1129 if self.isthreaded:
1119 1130 try:
1120 1131 self.sys_excepthook.call_pdb = val
1121 1132 except:
1122 1133 warn('Failed to activate pdb for threaded exception handler')
1123 1134
1124 1135 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1125 1136 'Control auto-activation of pdb at exceptions')
1126 1137
1127 1138 # These special functions get installed in the builtin namespace, to
1128 1139 # provide programmatic (pure python) access to magics, aliases and system
1129 1140 # calls. This is important for logging, user scripting, and more.
1130 1141
1131 1142 # We are basically exposing, via normal python functions, the three
1132 1143 # mechanisms in which ipython offers special call modes (magics for
1133 1144 # internal control, aliases for direct system access via pre-selected
1134 1145 # names, and !cmd for calling arbitrary system commands).
1135 1146
1136 1147 def ipmagic(self,arg_s):
1137 1148 """Call a magic function by name.
1138 1149
1139 1150 Input: a string containing the name of the magic function to call and any
1140 1151 additional arguments to be passed to the magic.
1141 1152
1142 1153 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1143 1154 prompt:
1144 1155
1145 1156 In[1]: %name -opt foo bar
1146 1157
1147 1158 To call a magic without arguments, simply use ipmagic('name').
1148 1159
1149 1160 This provides a proper Python function to call IPython's magics in any
1150 1161 valid Python code you can type at the interpreter, including loops and
1151 1162 compound statements. It is added by IPython to the Python builtin
1152 1163 namespace upon initialization."""
1153 1164
1154 1165 args = arg_s.split(' ',1)
1155 1166 magic_name = args[0]
1156 1167 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1157 1168
1158 1169 try:
1159 1170 magic_args = args[1]
1160 1171 except IndexError:
1161 1172 magic_args = ''
1162 1173 fn = getattr(self,'magic_'+magic_name,None)
1163 1174 if fn is None:
1164 1175 error("Magic function `%s` not found." % magic_name)
1165 1176 else:
1166 1177 magic_args = self.var_expand(magic_args,1)
1167 1178 return fn(magic_args)
1168 1179
1169 1180 def ipalias(self,arg_s):
1170 1181 """Call an alias by name.
1171 1182
1172 1183 Input: a string containing the name of the alias to call and any
1173 1184 additional arguments to be passed to the magic.
1174 1185
1175 1186 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1176 1187 prompt:
1177 1188
1178 1189 In[1]: name -opt foo bar
1179 1190
1180 1191 To call an alias without arguments, simply use ipalias('name').
1181 1192
1182 1193 This provides a proper Python function to call IPython's aliases in any
1183 1194 valid Python code you can type at the interpreter, including loops and
1184 1195 compound statements. It is added by IPython to the Python builtin
1185 1196 namespace upon initialization."""
1186 1197
1187 1198 args = arg_s.split(' ',1)
1188 1199 alias_name = args[0]
1189 1200 try:
1190 1201 alias_args = args[1]
1191 1202 except IndexError:
1192 1203 alias_args = ''
1193 1204 if alias_name in self.alias_table:
1194 1205 self.call_alias(alias_name,alias_args)
1195 1206 else:
1196 1207 error("Alias `%s` not found." % alias_name)
1197 1208
1198 1209 def ipsystem(self,arg_s):
1199 1210 """Make a system call, using IPython."""
1200 1211
1201 1212 self.system(arg_s)
1202 1213
1203 1214 def complete(self,text):
1204 1215 """Return a sorted list of all possible completions on text.
1205 1216
1206 1217 Inputs:
1207 1218
1208 1219 - text: a string of text to be completed on.
1209 1220
1210 1221 This is a wrapper around the completion mechanism, similar to what
1211 1222 readline does at the command line when the TAB key is hit. By
1212 1223 exposing it as a method, it can be used by other non-readline
1213 1224 environments (such as GUIs) for text completion.
1214 1225
1215 1226 Simple usage example:
1216 1227
1217 1228 In [7]: x = 'hello'
1218 1229
1219 1230 In [8]: x
1220 1231 Out[8]: 'hello'
1221 1232
1222 1233 In [9]: print x
1223 1234 hello
1224 1235
1225 1236 In [10]: _ip.IP.complete('x.l')
1226 1237 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1227 1238 """
1228 1239
1229 1240 complete = self.Completer.complete
1230 1241 state = 0
1231 1242 # use a dict so we get unique keys, since ipyhton's multiple
1232 1243 # completers can return duplicates. When we make 2.4 a requirement,
1233 1244 # start using sets instead, which are faster.
1234 1245 comps = {}
1235 1246 while True:
1236 1247 newcomp = complete(text,state,line_buffer=text)
1237 1248 if newcomp is None:
1238 1249 break
1239 1250 comps[newcomp] = 1
1240 1251 state += 1
1241 1252 outcomps = comps.keys()
1242 1253 outcomps.sort()
1243 1254 #print "T:",text,"OC:",outcomps # dbg
1244 1255 #print "vars:",self.user_ns.keys()
1245 1256 return outcomps
1246 1257
1247 1258 def set_completer_frame(self, frame=None):
1248 1259 if frame:
1249 1260 self.Completer.namespace = frame.f_locals
1250 1261 self.Completer.global_namespace = frame.f_globals
1251 1262 else:
1252 1263 self.Completer.namespace = self.user_ns
1253 1264 self.Completer.global_namespace = self.user_global_ns
1254 1265
1255 1266 def init_auto_alias(self):
1256 1267 """Define some aliases automatically.
1257 1268
1258 1269 These are ALL parameter-less aliases"""
1259 1270
1260 1271 for alias,cmd in self.auto_alias:
1261 1272 self.getapi().defalias(alias,cmd)
1262 1273
1263 1274
1264 1275 def alias_table_validate(self,verbose=0):
1265 1276 """Update information about the alias table.
1266 1277
1267 1278 In particular, make sure no Python keywords/builtins are in it."""
1268 1279
1269 1280 no_alias = self.no_alias
1270 1281 for k in self.alias_table.keys():
1271 1282 if k in no_alias:
1272 1283 del self.alias_table[k]
1273 1284 if verbose:
1274 1285 print ("Deleting alias <%s>, it's a Python "
1275 1286 "keyword or builtin." % k)
1276 1287
1277 1288 def set_autoindent(self,value=None):
1278 1289 """Set the autoindent flag, checking for readline support.
1279 1290
1280 1291 If called with no arguments, it acts as a toggle."""
1281 1292
1282 1293 if not self.has_readline:
1283 1294 if os.name == 'posix':
1284 1295 warn("The auto-indent feature requires the readline library")
1285 1296 self.autoindent = 0
1286 1297 return
1287 1298 if value is None:
1288 1299 self.autoindent = not self.autoindent
1289 1300 else:
1290 1301 self.autoindent = value
1291 1302
1292 1303 def rc_set_toggle(self,rc_field,value=None):
1293 1304 """Set or toggle a field in IPython's rc config. structure.
1294 1305
1295 1306 If called with no arguments, it acts as a toggle.
1296 1307
1297 1308 If called with a non-existent field, the resulting AttributeError
1298 1309 exception will propagate out."""
1299 1310
1300 1311 rc_val = getattr(self.rc,rc_field)
1301 1312 if value is None:
1302 1313 value = not rc_val
1303 1314 setattr(self.rc,rc_field,value)
1304 1315
1305 1316 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1306 1317 """Install the user configuration directory.
1307 1318
1308 1319 Note
1309 1320 ----
1310 1321 DEPRECATED: use the top-level user_setup() function instead.
1311 1322 """
1312 1323 return user_setup(ipythondir,rc_suffix,mode)
1313 1324
1314 1325 def atexit_operations(self):
1315 1326 """This will be executed at the time of exit.
1316 1327
1317 1328 Saving of persistent data should be performed here. """
1318 1329
1319 1330 #print '*** IPython exit cleanup ***' # dbg
1320 1331 # input history
1321 1332 self.savehist()
1322 1333
1323 1334 # Cleanup all tempfiles left around
1324 1335 for tfile in self.tempfiles:
1325 1336 try:
1326 1337 os.unlink(tfile)
1327 1338 except OSError:
1328 1339 pass
1329 1340
1330 1341 # Clear all user namespaces to release all references cleanly.
1331 1342 self.reset()
1332 1343
1333 1344 # Run user hooks
1334 1345 self.hooks.shutdown_hook()
1335 1346
1336 1347 def reset(self):
1337 1348 """Clear all internal namespaces.
1338 1349
1339 1350 Note that this is much more aggressive than %reset, since it clears
1340 1351 fully all namespaces, as well as all input/output lists.
1341 1352 """
1342 1353 for ns in self.ns_refs_table:
1343 1354 ns.clear()
1344 1355
1345 1356 # Clear input and output histories
1346 1357 self.input_hist[:] = []
1347 1358 self.input_hist_raw[:] = []
1348 1359 self.output_hist.clear()
1349 1360 # Restore the user namespaces to minimal usability
1350 1361 self.init_namespaces()
1351 1362
1352 1363 def savehist(self):
1353 1364 """Save input history to a file (via readline library)."""
1354 1365
1355 1366 if not self.has_readline:
1356 1367 return
1357 1368
1358 1369 try:
1359 1370 self.readline.write_history_file(self.histfile)
1360 1371 except:
1361 1372 print 'Unable to save IPython command history to file: ' + \
1362 1373 `self.histfile`
1363 1374
1364 1375 def reloadhist(self):
1365 1376 """Reload the input history from disk file."""
1366 1377
1367 1378 if self.has_readline:
1368 1379 try:
1369 1380 self.readline.clear_history()
1370 1381 self.readline.read_history_file(self.shell.histfile)
1371 1382 except AttributeError:
1372 1383 pass
1373 1384
1374 1385
1375 1386 def history_saving_wrapper(self, func):
1376 1387 """ Wrap func for readline history saving
1377 1388
1378 1389 Convert func into callable that saves & restores
1379 1390 history around the call """
1380 1391
1381 1392 if not self.has_readline:
1382 1393 return func
1383 1394
1384 1395 def wrapper():
1385 1396 self.savehist()
1386 1397 try:
1387 1398 func()
1388 1399 finally:
1389 1400 readline.read_history_file(self.histfile)
1390 1401 return wrapper
1391 1402
1392 1403 def pre_readline(self):
1393 1404 """readline hook to be used at the start of each line.
1394 1405
1395 1406 Currently it handles auto-indent only."""
1396 1407
1397 1408 #debugx('self.indent_current_nsp','pre_readline:')
1398 1409
1399 1410 if self.rl_do_indent:
1400 1411 self.readline.insert_text(self.indent_current_str())
1401 1412 if self.rl_next_input is not None:
1402 1413 self.readline.insert_text(self.rl_next_input)
1403 1414 self.rl_next_input = None
1404 1415
1405 1416 def init_readline(self):
1406 1417 """Command history completion/saving/reloading."""
1407 1418
1408 1419
1409 1420 import IPython.rlineimpl as readline
1410 1421
1411 1422 if not readline.have_readline:
1412 1423 self.has_readline = 0
1413 1424 self.readline = None
1414 1425 # no point in bugging windows users with this every time:
1415 1426 warn('Readline services not available on this platform.')
1416 1427 else:
1417 1428 sys.modules['readline'] = readline
1418 1429 import atexit
1419 1430 from IPython.completer import IPCompleter
1420 1431 self.Completer = IPCompleter(self,
1421 1432 self.user_ns,
1422 1433 self.user_global_ns,
1423 1434 self.rc.readline_omit__names,
1424 1435 self.alias_table)
1425 1436 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1426 1437 self.strdispatchers['complete_command'] = sdisp
1427 1438 self.Completer.custom_completers = sdisp
1428 1439 # Platform-specific configuration
1429 1440 if os.name == 'nt':
1430 1441 self.readline_startup_hook = readline.set_pre_input_hook
1431 1442 else:
1432 1443 self.readline_startup_hook = readline.set_startup_hook
1433 1444
1434 1445 # Load user's initrc file (readline config)
1435 1446 # Or if libedit is used, load editrc.
1436 1447 inputrc_name = os.environ.get('INPUTRC')
1437 1448 if inputrc_name is None:
1438 1449 home_dir = get_home_dir()
1439 1450 if home_dir is not None:
1440 1451 inputrc_name = '.inputrc'
1441 1452 if readline.uses_libedit:
1442 1453 inputrc_name = '.editrc'
1443 1454 inputrc_name = os.path.join(home_dir, inputrc_name)
1444 1455 if os.path.isfile(inputrc_name):
1445 1456 try:
1446 1457 readline.read_init_file(inputrc_name)
1447 1458 except:
1448 1459 warn('Problems reading readline initialization file <%s>'
1449 1460 % inputrc_name)
1450 1461
1451 1462 self.has_readline = 1
1452 1463 self.readline = readline
1453 1464 # save this in sys so embedded copies can restore it properly
1454 1465 sys.ipcompleter = self.Completer.complete
1455 1466 self.set_completer()
1456 1467
1457 1468 # Configure readline according to user's prefs
1458 1469 # This is only done if GNU readline is being used. If libedit
1459 1470 # is being used (as on Leopard) the readline config is
1460 1471 # not run as the syntax for libedit is different.
1461 1472 if not readline.uses_libedit:
1462 1473 for rlcommand in self.rc.readline_parse_and_bind:
1463 1474 #print "loading rl:",rlcommand # dbg
1464 1475 readline.parse_and_bind(rlcommand)
1465 1476
1466 1477 # remove some chars from the delimiters list
1467 1478 delims = readline.get_completer_delims()
1468 1479 delims = delims.translate(string._idmap,
1469 1480 self.rc.readline_remove_delims)
1470 1481 readline.set_completer_delims(delims)
1471 1482 # otherwise we end up with a monster history after a while:
1472 1483 readline.set_history_length(1000)
1473 1484 try:
1474 1485 #print '*** Reading readline history' # dbg
1475 1486 readline.read_history_file(self.histfile)
1476 1487 except IOError:
1477 1488 pass # It doesn't exist yet.
1478 1489
1479 1490 atexit.register(self.atexit_operations)
1480 1491 del atexit
1481 1492
1482 1493 # Configure auto-indent for all platforms
1483 1494 self.set_autoindent(self.rc.autoindent)
1484 1495
1485 1496 def ask_yes_no(self,prompt,default=True):
1486 1497 if self.rc.quiet:
1487 1498 return True
1488 1499 return ask_yes_no(prompt,default)
1489 1500
1490 def cache_main_mod(self,mod,fname=None):
1491 """Cache a main module.
1501 def new_main_mod(self,ns=None):
1502 """Return a new 'main' module object for user code execution.
1503 """
1504 main_mod = self._user_main_module
1505 init_fakemod_dict(main_mod,ns)
1506 return main_mod
1507
1508 def cache_main_mod(self,ns,fname):
1509 """Cache a main module's namespace.
1492 1510
1493 When scripts are executed via %run, we must keep a reference to their
1494 __main__ module (a FakeModule instance) around so that Python doesn't
1495 clear it, rendering objects defined therein useless.
1511 When scripts are executed via %run, we must keep a reference to the
1512 namespace of their __main__ module (a FakeModule instance) around so
1513 that Python doesn't clear it, rendering objects defined therein
1514 useless.
1496 1515
1497 1516 This method keeps said reference in a private dict, keyed by the
1498 1517 absolute path of the module object (which corresponds to the script
1499 1518 path). This way, for multiple executions of the same script we only
1500 keep one copy of __main__ (the last one), thus preventing memory leaks
1501 from old references while allowing the objects from the last execution
1502 to be accessible.
1519 keep one copy of the namespace (the last one), thus preventing memory
1520 leaks from old references while allowing the objects from the last
1521 execution to be accessible.
1522
1523 Note: we can not allow the actual FakeModule instances to be deleted,
1524 because of how Python tears down modules (it hard-sets all their
1525 references to None without regard for reference counts). This method
1526 must therefore make a *copy* of the given namespace, to allow the
1527 original module's __dict__ to be cleared and reused.
1503 1528
1529
1504 1530 Parameters
1505 1531 ----------
1506 mod : a module object
1532 ns : a namespace (a dict, typically)
1533
1534 fname : str
1535 Filename associated with the namespace.
1507 1536
1508 1537 Examples
1509 1538 --------
1510 1539
1511 1540 In [10]: import IPython
1512 1541
1513 In [11]: _ip.IP.cache_main_mod(IPython)
1542 In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1514 1543
1515 In [12]: IPython.__file__ in _ip.IP._user_main_modules
1544 In [12]: IPython.__file__ in _ip.IP._main_ns_cache
1516 1545 Out[12]: True
1517 1546 """
1518 if fname is None:
1519 fname = mod.__file__
1520 #print >> sys.stderr, 'CFNAME :', os.path.abspath(fname) # dbg
1521 self._user_main_modules[os.path.abspath(fname)] = mod
1547 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1522 1548
1523 1549 def clear_main_mod_cache(self):
1524 1550 """Clear the cache of main modules.
1525 1551
1526 1552 Mainly for use by utilities like %reset.
1527 1553
1528 1554 Examples
1529 1555 --------
1530 1556
1531 1557 In [15]: import IPython
1532 1558
1533 In [16]: _ip.IP.cache_main_mod(IPython)
1559 In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1534 1560
1535 In [17]: len(_ip.IP._user_main_modules) > 0
1561 In [17]: len(_ip.IP._main_ns_cache) > 0
1536 1562 Out[17]: True
1537 1563
1538 1564 In [18]: _ip.IP.clear_main_mod_cache()
1539 1565
1540 In [19]: len(_ip.IP._user_main_modules) == 0
1566 In [19]: len(_ip.IP._main_ns_cache) == 0
1541 1567 Out[19]: True
1542 1568 """
1543 self._user_main_modules.clear()
1569 self._main_ns_cache.clear()
1544 1570
1545 1571 def _should_recompile(self,e):
1546 1572 """Utility routine for edit_syntax_error"""
1547 1573
1548 1574 if e.filename in ('<ipython console>','<input>','<string>',
1549 1575 '<console>','<BackgroundJob compilation>',
1550 1576 None):
1551 1577
1552 1578 return False
1553 1579 try:
1554 1580 if (self.rc.autoedit_syntax and
1555 1581 not self.ask_yes_no('Return to editor to correct syntax error? '
1556 1582 '[Y/n] ','y')):
1557 1583 return False
1558 1584 except EOFError:
1559 1585 return False
1560 1586
1561 1587 def int0(x):
1562 1588 try:
1563 1589 return int(x)
1564 1590 except TypeError:
1565 1591 return 0
1566 1592 # always pass integer line and offset values to editor hook
1567 1593 try:
1568 1594 self.hooks.fix_error_editor(e.filename,
1569 1595 int0(e.lineno),int0(e.offset),e.msg)
1570 1596 except IPython.ipapi.TryNext:
1571 1597 warn('Could not open editor')
1572 1598 return False
1573 1599 return True
1574 1600
1575 1601 def edit_syntax_error(self):
1576 1602 """The bottom half of the syntax error handler called in the main loop.
1577 1603
1578 1604 Loop until syntax error is fixed or user cancels.
1579 1605 """
1580 1606
1581 1607 while self.SyntaxTB.last_syntax_error:
1582 1608 # copy and clear last_syntax_error
1583 1609 err = self.SyntaxTB.clear_err_state()
1584 1610 if not self._should_recompile(err):
1585 1611 return
1586 1612 try:
1587 1613 # may set last_syntax_error again if a SyntaxError is raised
1588 1614 self.safe_execfile(err.filename,self.user_ns)
1589 1615 except:
1590 1616 self.showtraceback()
1591 1617 else:
1592 1618 try:
1593 1619 f = file(err.filename)
1594 1620 try:
1595 1621 sys.displayhook(f.read())
1596 1622 finally:
1597 1623 f.close()
1598 1624 except:
1599 1625 self.showtraceback()
1600 1626
1601 1627 def showsyntaxerror(self, filename=None):
1602 1628 """Display the syntax error that just occurred.
1603 1629
1604 1630 This doesn't display a stack trace because there isn't one.
1605 1631
1606 1632 If a filename is given, it is stuffed in the exception instead
1607 1633 of what was there before (because Python's parser always uses
1608 1634 "<string>" when reading from a string).
1609 1635 """
1610 1636 etype, value, last_traceback = sys.exc_info()
1611 1637
1612 1638 # See note about these variables in showtraceback() below
1613 1639 sys.last_type = etype
1614 1640 sys.last_value = value
1615 1641 sys.last_traceback = last_traceback
1616 1642
1617 1643 if filename and etype is SyntaxError:
1618 1644 # Work hard to stuff the correct filename in the exception
1619 1645 try:
1620 1646 msg, (dummy_filename, lineno, offset, line) = value
1621 1647 except:
1622 1648 # Not the format we expect; leave it alone
1623 1649 pass
1624 1650 else:
1625 1651 # Stuff in the right filename
1626 1652 try:
1627 1653 # Assume SyntaxError is a class exception
1628 1654 value = SyntaxError(msg, (filename, lineno, offset, line))
1629 1655 except:
1630 1656 # If that failed, assume SyntaxError is a string
1631 1657 value = msg, (filename, lineno, offset, line)
1632 1658 self.SyntaxTB(etype,value,[])
1633 1659
1634 1660 def debugger(self,force=False):
1635 1661 """Call the pydb/pdb debugger.
1636 1662
1637 1663 Keywords:
1638 1664
1639 1665 - force(False): by default, this routine checks the instance call_pdb
1640 1666 flag and does not actually invoke the debugger if the flag is false.
1641 1667 The 'force' option forces the debugger to activate even if the flag
1642 1668 is false.
1643 1669 """
1644 1670
1645 1671 if not (force or self.call_pdb):
1646 1672 return
1647 1673
1648 1674 if not hasattr(sys,'last_traceback'):
1649 1675 error('No traceback has been produced, nothing to debug.')
1650 1676 return
1651 1677
1652 1678 # use pydb if available
1653 1679 if Debugger.has_pydb:
1654 1680 from pydb import pm
1655 1681 else:
1656 1682 # fallback to our internal debugger
1657 1683 pm = lambda : self.InteractiveTB.debugger(force=True)
1658 1684 self.history_saving_wrapper(pm)()
1659 1685
1660 1686 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1661 1687 """Display the exception that just occurred.
1662 1688
1663 1689 If nothing is known about the exception, this is the method which
1664 1690 should be used throughout the code for presenting user tracebacks,
1665 1691 rather than directly invoking the InteractiveTB object.
1666 1692
1667 1693 A specific showsyntaxerror() also exists, but this method can take
1668 1694 care of calling it if needed, so unless you are explicitly catching a
1669 1695 SyntaxError exception, don't try to analyze the stack manually and
1670 1696 simply call this method."""
1671 1697
1672 1698
1673 1699 # Though this won't be called by syntax errors in the input line,
1674 1700 # there may be SyntaxError cases whith imported code.
1675 1701
1676 1702 try:
1677 1703 if exc_tuple is None:
1678 1704 etype, value, tb = sys.exc_info()
1679 1705 else:
1680 1706 etype, value, tb = exc_tuple
1681 1707
1682 1708 if etype is SyntaxError:
1683 1709 self.showsyntaxerror(filename)
1684 1710 elif etype is IPython.ipapi.UsageError:
1685 1711 print "UsageError:", value
1686 1712 else:
1687 1713 # WARNING: these variables are somewhat deprecated and not
1688 1714 # necessarily safe to use in a threaded environment, but tools
1689 1715 # like pdb depend on their existence, so let's set them. If we
1690 1716 # find problems in the field, we'll need to revisit their use.
1691 1717 sys.last_type = etype
1692 1718 sys.last_value = value
1693 1719 sys.last_traceback = tb
1694 1720
1695 1721 if etype in self.custom_exceptions:
1696 1722 self.CustomTB(etype,value,tb)
1697 1723 else:
1698 1724 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1699 1725 if self.InteractiveTB.call_pdb and self.has_readline:
1700 1726 # pdb mucks up readline, fix it back
1701 1727 self.set_completer()
1702 1728 except KeyboardInterrupt:
1703 1729 self.write("\nKeyboardInterrupt\n")
1704 1730
1705 1731 def mainloop(self,banner=None):
1706 1732 """Creates the local namespace and starts the mainloop.
1707 1733
1708 1734 If an optional banner argument is given, it will override the
1709 1735 internally created default banner."""
1710 1736
1711 1737 if self.rc.c: # Emulate Python's -c option
1712 1738 self.exec_init_cmd()
1713 1739 if banner is None:
1714 1740 if not self.rc.banner:
1715 1741 banner = ''
1716 1742 # banner is string? Use it directly!
1717 1743 elif isinstance(self.rc.banner,basestring):
1718 1744 banner = self.rc.banner
1719 1745 else:
1720 1746 banner = self.BANNER+self.banner2
1721 1747
1722 1748 # if you run stuff with -c <cmd>, raw hist is not updated
1723 1749 # ensure that it's in sync
1724 1750 if len(self.input_hist) != len (self.input_hist_raw):
1725 1751 self.input_hist_raw = InputList(self.input_hist)
1726 1752
1727 1753 while 1:
1728 1754 try:
1729 1755 self.interact(banner)
1730 1756 #self.interact_with_readline()
1731 1757
1732 1758 # XXX for testing of a readline-decoupled repl loop, call
1733 1759 # interact_with_readline above
1734 1760
1735 1761 break
1736 1762 except KeyboardInterrupt:
1737 1763 # this should not be necessary, but KeyboardInterrupt
1738 1764 # handling seems rather unpredictable...
1739 1765 self.write("\nKeyboardInterrupt in interact()\n")
1740 1766
1741 1767 def exec_init_cmd(self):
1742 1768 """Execute a command given at the command line.
1743 1769
1744 1770 This emulates Python's -c option."""
1745 1771
1746 1772 #sys.argv = ['-c']
1747 1773 self.push(self.prefilter(self.rc.c, False))
1748 1774 if not self.rc.interact:
1749 1775 self.ask_exit()
1750 1776
1751 1777 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1752 1778 """Embeds IPython into a running python program.
1753 1779
1754 1780 Input:
1755 1781
1756 1782 - header: An optional header message can be specified.
1757 1783
1758 1784 - local_ns, global_ns: working namespaces. If given as None, the
1759 1785 IPython-initialized one is updated with __main__.__dict__, so that
1760 1786 program variables become visible but user-specific configuration
1761 1787 remains possible.
1762 1788
1763 1789 - stack_depth: specifies how many levels in the stack to go to
1764 1790 looking for namespaces (when local_ns and global_ns are None). This
1765 1791 allows an intermediate caller to make sure that this function gets
1766 1792 the namespace from the intended level in the stack. By default (0)
1767 1793 it will get its locals and globals from the immediate caller.
1768 1794
1769 1795 Warning: it's possible to use this in a program which is being run by
1770 1796 IPython itself (via %run), but some funny things will happen (a few
1771 1797 globals get overwritten). In the future this will be cleaned up, as
1772 1798 there is no fundamental reason why it can't work perfectly."""
1773 1799
1774 1800 # Get locals and globals from caller
1775 1801 if local_ns is None or global_ns is None:
1776 1802 call_frame = sys._getframe(stack_depth).f_back
1777 1803
1778 1804 if local_ns is None:
1779 1805 local_ns = call_frame.f_locals
1780 1806 if global_ns is None:
1781 1807 global_ns = call_frame.f_globals
1782 1808
1783 1809 # Update namespaces and fire up interpreter
1784 1810
1785 1811 # The global one is easy, we can just throw it in
1786 1812 self.user_global_ns = global_ns
1787 1813
1788 1814 # but the user/local one is tricky: ipython needs it to store internal
1789 1815 # data, but we also need the locals. We'll copy locals in the user
1790 1816 # one, but will track what got copied so we can delete them at exit.
1791 1817 # This is so that a later embedded call doesn't see locals from a
1792 1818 # previous call (which most likely existed in a separate scope).
1793 1819 local_varnames = local_ns.keys()
1794 1820 self.user_ns.update(local_ns)
1795 1821 #self.user_ns['local_ns'] = local_ns # dbg
1796 1822
1797 1823 # Patch for global embedding to make sure that things don't overwrite
1798 1824 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1799 1825 # FIXME. Test this a bit more carefully (the if.. is new)
1800 1826 if local_ns is None and global_ns is None:
1801 1827 self.user_global_ns.update(__main__.__dict__)
1802 1828
1803 1829 # make sure the tab-completer has the correct frame information, so it
1804 1830 # actually completes using the frame's locals/globals
1805 1831 self.set_completer_frame()
1806 1832
1807 1833 # before activating the interactive mode, we need to make sure that
1808 1834 # all names in the builtin namespace needed by ipython point to
1809 1835 # ourselves, and not to other instances.
1810 1836 self.add_builtins()
1811 1837
1812 1838 self.interact(header)
1813 1839
1814 1840 # now, purge out the user namespace from anything we might have added
1815 1841 # from the caller's local namespace
1816 1842 delvar = self.user_ns.pop
1817 1843 for var in local_varnames:
1818 1844 delvar(var,None)
1819 1845 # and clean builtins we may have overridden
1820 1846 self.clean_builtins()
1821 1847
1822 1848 def interact_prompt(self):
1823 1849 """ Print the prompt (in read-eval-print loop)
1824 1850
1825 1851 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1826 1852 used in standard IPython flow.
1827 1853 """
1828 1854 if self.more:
1829 1855 try:
1830 1856 prompt = self.hooks.generate_prompt(True)
1831 1857 except:
1832 1858 self.showtraceback()
1833 1859 if self.autoindent:
1834 1860 self.rl_do_indent = True
1835 1861
1836 1862 else:
1837 1863 try:
1838 1864 prompt = self.hooks.generate_prompt(False)
1839 1865 except:
1840 1866 self.showtraceback()
1841 1867 self.write(prompt)
1842 1868
1843 1869 def interact_handle_input(self,line):
1844 1870 """ Handle the input line (in read-eval-print loop)
1845 1871
1846 1872 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1847 1873 used in standard IPython flow.
1848 1874 """
1849 1875 if line.lstrip() == line:
1850 1876 self.shadowhist.add(line.strip())
1851 1877 lineout = self.prefilter(line,self.more)
1852 1878
1853 1879 if line.strip():
1854 1880 if self.more:
1855 1881 self.input_hist_raw[-1] += '%s\n' % line
1856 1882 else:
1857 1883 self.input_hist_raw.append('%s\n' % line)
1858 1884
1859 1885
1860 1886 self.more = self.push(lineout)
1861 1887 if (self.SyntaxTB.last_syntax_error and
1862 1888 self.rc.autoedit_syntax):
1863 1889 self.edit_syntax_error()
1864 1890
1865 1891 def interact_with_readline(self):
1866 1892 """ Demo of using interact_handle_input, interact_prompt
1867 1893
1868 1894 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1869 1895 it should work like this.
1870 1896 """
1871 1897 self.readline_startup_hook(self.pre_readline)
1872 1898 while not self.exit_now:
1873 1899 self.interact_prompt()
1874 1900 if self.more:
1875 1901 self.rl_do_indent = True
1876 1902 else:
1877 1903 self.rl_do_indent = False
1878 1904 line = raw_input_original().decode(self.stdin_encoding)
1879 1905 self.interact_handle_input(line)
1880 1906
1881 1907
1882 1908 def interact(self, banner=None):
1883 1909 """Closely emulate the interactive Python console.
1884 1910
1885 1911 The optional banner argument specify the banner to print
1886 1912 before the first interaction; by default it prints a banner
1887 1913 similar to the one printed by the real Python interpreter,
1888 1914 followed by the current class name in parentheses (so as not
1889 1915 to confuse this with the real interpreter -- since it's so
1890 1916 close!).
1891 1917
1892 1918 """
1893 1919
1894 1920 if self.exit_now:
1895 1921 # batch run -> do not interact
1896 1922 return
1897 1923 cprt = 'Type "copyright", "credits" or "license" for more information.'
1898 1924 if banner is None:
1899 1925 self.write("Python %s on %s\n%s\n(%s)\n" %
1900 1926 (sys.version, sys.platform, cprt,
1901 1927 self.__class__.__name__))
1902 1928 else:
1903 1929 self.write(banner)
1904 1930
1905 1931 more = 0
1906 1932
1907 1933 # Mark activity in the builtins
1908 1934 __builtin__.__dict__['__IPYTHON__active'] += 1
1909 1935
1910 1936 if self.has_readline:
1911 1937 self.readline_startup_hook(self.pre_readline)
1912 1938 # exit_now is set by a call to %Exit or %Quit, through the
1913 1939 # ask_exit callback.
1914 1940
1915 1941 while not self.exit_now:
1916 1942 self.hooks.pre_prompt_hook()
1917 1943 if more:
1918 1944 try:
1919 1945 prompt = self.hooks.generate_prompt(True)
1920 1946 except:
1921 1947 self.showtraceback()
1922 1948 if self.autoindent:
1923 1949 self.rl_do_indent = True
1924 1950
1925 1951 else:
1926 1952 try:
1927 1953 prompt = self.hooks.generate_prompt(False)
1928 1954 except:
1929 1955 self.showtraceback()
1930 1956 try:
1931 1957 line = self.raw_input(prompt,more)
1932 1958 if self.exit_now:
1933 1959 # quick exit on sys.std[in|out] close
1934 1960 break
1935 1961 if self.autoindent:
1936 1962 self.rl_do_indent = False
1937 1963
1938 1964 except KeyboardInterrupt:
1939 1965 #double-guard against keyboardinterrupts during kbdint handling
1940 1966 try:
1941 1967 self.write('\nKeyboardInterrupt\n')
1942 1968 self.resetbuffer()
1943 1969 # keep cache in sync with the prompt counter:
1944 1970 self.outputcache.prompt_count -= 1
1945 1971
1946 1972 if self.autoindent:
1947 1973 self.indent_current_nsp = 0
1948 1974 more = 0
1949 1975 except KeyboardInterrupt:
1950 1976 pass
1951 1977 except EOFError:
1952 1978 if self.autoindent:
1953 1979 self.rl_do_indent = False
1954 1980 self.readline_startup_hook(None)
1955 1981 self.write('\n')
1956 1982 self.exit()
1957 1983 except bdb.BdbQuit:
1958 1984 warn('The Python debugger has exited with a BdbQuit exception.\n'
1959 1985 'Because of how pdb handles the stack, it is impossible\n'
1960 1986 'for IPython to properly format this particular exception.\n'
1961 1987 'IPython will resume normal operation.')
1962 1988 except:
1963 1989 # exceptions here are VERY RARE, but they can be triggered
1964 1990 # asynchronously by signal handlers, for example.
1965 1991 self.showtraceback()
1966 1992 else:
1967 1993 more = self.push(line)
1968 1994 if (self.SyntaxTB.last_syntax_error and
1969 1995 self.rc.autoedit_syntax):
1970 1996 self.edit_syntax_error()
1971 1997
1972 1998 # We are off again...
1973 1999 __builtin__.__dict__['__IPYTHON__active'] -= 1
1974 2000
1975 2001 def excepthook(self, etype, value, tb):
1976 2002 """One more defense for GUI apps that call sys.excepthook.
1977 2003
1978 2004 GUI frameworks like wxPython trap exceptions and call
1979 2005 sys.excepthook themselves. I guess this is a feature that
1980 2006 enables them to keep running after exceptions that would
1981 2007 otherwise kill their mainloop. This is a bother for IPython
1982 2008 which excepts to catch all of the program exceptions with a try:
1983 2009 except: statement.
1984 2010
1985 2011 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1986 2012 any app directly invokes sys.excepthook, it will look to the user like
1987 2013 IPython crashed. In order to work around this, we can disable the
1988 2014 CrashHandler and replace it with this excepthook instead, which prints a
1989 2015 regular traceback using our InteractiveTB. In this fashion, apps which
1990 2016 call sys.excepthook will generate a regular-looking exception from
1991 2017 IPython, and the CrashHandler will only be triggered by real IPython
1992 2018 crashes.
1993 2019
1994 2020 This hook should be used sparingly, only in places which are not likely
1995 2021 to be true IPython errors.
1996 2022 """
1997 2023 self.showtraceback((etype,value,tb),tb_offset=0)
1998 2024
1999 2025 def expand_aliases(self,fn,rest):
2000 2026 """ Expand multiple levels of aliases:
2001 2027
2002 2028 if:
2003 2029
2004 2030 alias foo bar /tmp
2005 2031 alias baz foo
2006 2032
2007 2033 then:
2008 2034
2009 2035 baz huhhahhei -> bar /tmp huhhahhei
2010 2036
2011 2037 """
2012 2038 line = fn + " " + rest
2013 2039
2014 2040 done = set()
2015 2041 while 1:
2016 2042 pre,fn,rest = prefilter.splitUserInput(line,
2017 2043 prefilter.shell_line_split)
2018 2044 if fn in self.alias_table:
2019 2045 if fn in done:
2020 2046 warn("Cyclic alias definition, repeated '%s'" % fn)
2021 2047 return ""
2022 2048 done.add(fn)
2023 2049
2024 2050 l2 = self.transform_alias(fn,rest)
2025 2051 # dir -> dir
2026 2052 # print "alias",line, "->",l2 #dbg
2027 2053 if l2 == line:
2028 2054 break
2029 2055 # ls -> ls -F should not recurse forever
2030 2056 if l2.split(None,1)[0] == line.split(None,1)[0]:
2031 2057 line = l2
2032 2058 break
2033 2059
2034 2060 line=l2
2035 2061
2036 2062
2037 2063 # print "al expand to",line #dbg
2038 2064 else:
2039 2065 break
2040 2066
2041 2067 return line
2042 2068
2043 2069 def transform_alias(self, alias,rest=''):
2044 2070 """ Transform alias to system command string.
2045 2071 """
2046 2072 trg = self.alias_table[alias]
2047 2073
2048 2074 nargs,cmd = trg
2049 2075 # print trg #dbg
2050 2076 if ' ' in cmd and os.path.isfile(cmd):
2051 2077 cmd = '"%s"' % cmd
2052 2078
2053 2079 # Expand the %l special to be the user's input line
2054 2080 if cmd.find('%l') >= 0:
2055 2081 cmd = cmd.replace('%l',rest)
2056 2082 rest = ''
2057 2083 if nargs==0:
2058 2084 # Simple, argument-less aliases
2059 2085 cmd = '%s %s' % (cmd,rest)
2060 2086 else:
2061 2087 # Handle aliases with positional arguments
2062 2088 args = rest.split(None,nargs)
2063 2089 if len(args)< nargs:
2064 2090 error('Alias <%s> requires %s arguments, %s given.' %
2065 2091 (alias,nargs,len(args)))
2066 2092 return None
2067 2093 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2068 2094 # Now call the macro, evaluating in the user's namespace
2069 2095 #print 'new command: <%r>' % cmd # dbg
2070 2096 return cmd
2071 2097
2072 2098 def call_alias(self,alias,rest=''):
2073 2099 """Call an alias given its name and the rest of the line.
2074 2100
2075 2101 This is only used to provide backwards compatibility for users of
2076 2102 ipalias(), use of which is not recommended for anymore."""
2077 2103
2078 2104 # Now call the macro, evaluating in the user's namespace
2079 2105 cmd = self.transform_alias(alias, rest)
2080 2106 try:
2081 2107 self.system(cmd)
2082 2108 except:
2083 2109 self.showtraceback()
2084 2110
2085 2111 def indent_current_str(self):
2086 2112 """return the current level of indentation as a string"""
2087 2113 return self.indent_current_nsp * ' '
2088 2114
2089 2115 def autoindent_update(self,line):
2090 2116 """Keep track of the indent level."""
2091 2117
2092 2118 #debugx('line')
2093 2119 #debugx('self.indent_current_nsp')
2094 2120 if self.autoindent:
2095 2121 if line:
2096 2122 inisp = num_ini_spaces(line)
2097 2123 if inisp < self.indent_current_nsp:
2098 2124 self.indent_current_nsp = inisp
2099 2125
2100 2126 if line[-1] == ':':
2101 2127 self.indent_current_nsp += 4
2102 2128 elif dedent_re.match(line):
2103 2129 self.indent_current_nsp -= 4
2104 2130 else:
2105 2131 self.indent_current_nsp = 0
2106 2132
2107 2133 def runlines(self,lines):
2108 2134 """Run a string of one or more lines of source.
2109 2135
2110 2136 This method is capable of running a string containing multiple source
2111 2137 lines, as if they had been entered at the IPython prompt. Since it
2112 2138 exposes IPython's processing machinery, the given strings can contain
2113 2139 magic calls (%magic), special shell access (!cmd), etc."""
2114 2140
2115 2141 # We must start with a clean buffer, in case this is run from an
2116 2142 # interactive IPython session (via a magic, for example).
2117 2143 self.resetbuffer()
2118 2144 lines = lines.split('\n')
2119 2145 more = 0
2120 2146
2121 2147 for line in lines:
2122 2148 # skip blank lines so we don't mess up the prompt counter, but do
2123 2149 # NOT skip even a blank line if we are in a code block (more is
2124 2150 # true)
2125 2151
2126 2152 if line or more:
2127 2153 # push to raw history, so hist line numbers stay in sync
2128 2154 self.input_hist_raw.append("# " + line + "\n")
2129 2155 more = self.push(self.prefilter(line,more))
2130 2156 # IPython's runsource returns None if there was an error
2131 2157 # compiling the code. This allows us to stop processing right
2132 2158 # away, so the user gets the error message at the right place.
2133 2159 if more is None:
2134 2160 break
2135 2161 else:
2136 2162 self.input_hist_raw.append("\n")
2137 2163 # final newline in case the input didn't have it, so that the code
2138 2164 # actually does get executed
2139 2165 if more:
2140 2166 self.push('\n')
2141 2167
2142 2168 def runsource(self, source, filename='<input>', symbol='single'):
2143 2169 """Compile and run some source in the interpreter.
2144 2170
2145 2171 Arguments are as for compile_command().
2146 2172
2147 2173 One several things can happen:
2148 2174
2149 2175 1) The input is incorrect; compile_command() raised an
2150 2176 exception (SyntaxError or OverflowError). A syntax traceback
2151 2177 will be printed by calling the showsyntaxerror() method.
2152 2178
2153 2179 2) The input is incomplete, and more input is required;
2154 2180 compile_command() returned None. Nothing happens.
2155 2181
2156 2182 3) The input is complete; compile_command() returned a code
2157 2183 object. The code is executed by calling self.runcode() (which
2158 2184 also handles run-time exceptions, except for SystemExit).
2159 2185
2160 2186 The return value is:
2161 2187
2162 2188 - True in case 2
2163 2189
2164 2190 - False in the other cases, unless an exception is raised, where
2165 2191 None is returned instead. This can be used by external callers to
2166 2192 know whether to continue feeding input or not.
2167 2193
2168 2194 The return value can be used to decide whether to use sys.ps1 or
2169 2195 sys.ps2 to prompt the next line."""
2170 2196
2171 2197 # if the source code has leading blanks, add 'if 1:\n' to it
2172 2198 # this allows execution of indented pasted code. It is tempting
2173 2199 # to add '\n' at the end of source to run commands like ' a=1'
2174 2200 # directly, but this fails for more complicated scenarios
2175 2201 source=source.encode(self.stdin_encoding)
2176 2202 if source[:1] in [' ', '\t']:
2177 2203 source = 'if 1:\n%s' % source
2178 2204
2179 2205 try:
2180 2206 code = self.compile(source,filename,symbol)
2181 2207 except (OverflowError, SyntaxError, ValueError, TypeError):
2182 2208 # Case 1
2183 2209 self.showsyntaxerror(filename)
2184 2210 return None
2185 2211
2186 2212 if code is None:
2187 2213 # Case 2
2188 2214 return True
2189 2215
2190 2216 # Case 3
2191 2217 # We store the code object so that threaded shells and
2192 2218 # custom exception handlers can access all this info if needed.
2193 2219 # The source corresponding to this can be obtained from the
2194 2220 # buffer attribute as '\n'.join(self.buffer).
2195 2221 self.code_to_run = code
2196 2222 # now actually execute the code object
2197 2223 if self.runcode(code) == 0:
2198 2224 return False
2199 2225 else:
2200 2226 return None
2201 2227
2202 2228 def runcode(self,code_obj):
2203 2229 """Execute a code object.
2204 2230
2205 2231 When an exception occurs, self.showtraceback() is called to display a
2206 2232 traceback.
2207 2233
2208 2234 Return value: a flag indicating whether the code to be run completed
2209 2235 successfully:
2210 2236
2211 2237 - 0: successful execution.
2212 2238 - 1: an error occurred.
2213 2239 """
2214 2240
2215 2241 # Set our own excepthook in case the user code tries to call it
2216 2242 # directly, so that the IPython crash handler doesn't get triggered
2217 2243 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2218 2244
2219 2245 # we save the original sys.excepthook in the instance, in case config
2220 2246 # code (such as magics) needs access to it.
2221 2247 self.sys_excepthook = old_excepthook
2222 2248 outflag = 1 # happens in more places, so it's easier as default
2223 2249 try:
2224 2250 try:
2225 2251 self.hooks.pre_runcode_hook()
2226 2252 exec code_obj in self.user_global_ns, self.user_ns
2227 2253 finally:
2228 2254 # Reset our crash handler in place
2229 2255 sys.excepthook = old_excepthook
2230 2256 except SystemExit:
2231 2257 self.resetbuffer()
2232 2258 self.showtraceback()
2233 2259 warn("Type %exit or %quit to exit IPython "
2234 2260 "(%Exit or %Quit do so unconditionally).",level=1)
2235 2261 except self.custom_exceptions:
2236 2262 etype,value,tb = sys.exc_info()
2237 2263 self.CustomTB(etype,value,tb)
2238 2264 except:
2239 2265 self.showtraceback()
2240 2266 else:
2241 2267 outflag = 0
2242 2268 if softspace(sys.stdout, 0):
2243 2269 print
2244 2270 # Flush out code object which has been run (and source)
2245 2271 self.code_to_run = None
2246 2272 return outflag
2247 2273
2248 2274 def push(self, line):
2249 2275 """Push a line to the interpreter.
2250 2276
2251 2277 The line should not have a trailing newline; it may have
2252 2278 internal newlines. The line is appended to a buffer and the
2253 2279 interpreter's runsource() method is called with the
2254 2280 concatenated contents of the buffer as source. If this
2255 2281 indicates that the command was executed or invalid, the buffer
2256 2282 is reset; otherwise, the command is incomplete, and the buffer
2257 2283 is left as it was after the line was appended. The return
2258 2284 value is 1 if more input is required, 0 if the line was dealt
2259 2285 with in some way (this is the same as runsource()).
2260 2286 """
2261 2287
2262 2288 # autoindent management should be done here, and not in the
2263 2289 # interactive loop, since that one is only seen by keyboard input. We
2264 2290 # need this done correctly even for code run via runlines (which uses
2265 2291 # push).
2266 2292
2267 2293 #print 'push line: <%s>' % line # dbg
2268 2294 for subline in line.splitlines():
2269 2295 self.autoindent_update(subline)
2270 2296 self.buffer.append(line)
2271 2297 more = self.runsource('\n'.join(self.buffer), self.filename)
2272 2298 if not more:
2273 2299 self.resetbuffer()
2274 2300 return more
2275 2301
2276 2302 def split_user_input(self, line):
2277 2303 # This is really a hold-over to support ipapi and some extensions
2278 2304 return prefilter.splitUserInput(line)
2279 2305
2280 2306 def resetbuffer(self):
2281 2307 """Reset the input buffer."""
2282 2308 self.buffer[:] = []
2283 2309
2284 2310 def raw_input(self,prompt='',continue_prompt=False):
2285 2311 """Write a prompt and read a line.
2286 2312
2287 2313 The returned line does not include the trailing newline.
2288 2314 When the user enters the EOF key sequence, EOFError is raised.
2289 2315
2290 2316 Optional inputs:
2291 2317
2292 2318 - prompt(''): a string to be printed to prompt the user.
2293 2319
2294 2320 - continue_prompt(False): whether this line is the first one or a
2295 2321 continuation in a sequence of inputs.
2296 2322 """
2297 2323
2298 2324 # Code run by the user may have modified the readline completer state.
2299 2325 # We must ensure that our completer is back in place.
2300 2326 if self.has_readline:
2301 2327 self.set_completer()
2302 2328
2303 2329 try:
2304 2330 line = raw_input_original(prompt).decode(self.stdin_encoding)
2305 2331 except ValueError:
2306 2332 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2307 2333 " or sys.stdout.close()!\nExiting IPython!")
2308 2334 self.ask_exit()
2309 2335 return ""
2310 2336
2311 2337 # Try to be reasonably smart about not re-indenting pasted input more
2312 2338 # than necessary. We do this by trimming out the auto-indent initial
2313 2339 # spaces, if the user's actual input started itself with whitespace.
2314 2340 #debugx('self.buffer[-1]')
2315 2341
2316 2342 if self.autoindent:
2317 2343 if num_ini_spaces(line) > self.indent_current_nsp:
2318 2344 line = line[self.indent_current_nsp:]
2319 2345 self.indent_current_nsp = 0
2320 2346
2321 2347 # store the unfiltered input before the user has any chance to modify
2322 2348 # it.
2323 2349 if line.strip():
2324 2350 if continue_prompt:
2325 2351 self.input_hist_raw[-1] += '%s\n' % line
2326 2352 if self.has_readline: # and some config option is set?
2327 2353 try:
2328 2354 histlen = self.readline.get_current_history_length()
2329 2355 if histlen > 1:
2330 2356 newhist = self.input_hist_raw[-1].rstrip()
2331 2357 self.readline.remove_history_item(histlen-1)
2332 2358 self.readline.replace_history_item(histlen-2,
2333 2359 newhist.encode(self.stdin_encoding))
2334 2360 except AttributeError:
2335 2361 pass # re{move,place}_history_item are new in 2.4.
2336 2362 else:
2337 2363 self.input_hist_raw.append('%s\n' % line)
2338 2364 # only entries starting at first column go to shadow history
2339 2365 if line.lstrip() == line:
2340 2366 self.shadowhist.add(line.strip())
2341 2367 elif not continue_prompt:
2342 2368 self.input_hist_raw.append('\n')
2343 2369 try:
2344 2370 lineout = self.prefilter(line,continue_prompt)
2345 2371 except:
2346 2372 # blanket except, in case a user-defined prefilter crashes, so it
2347 2373 # can't take all of ipython with it.
2348 2374 self.showtraceback()
2349 2375 return ''
2350 2376 else:
2351 2377 return lineout
2352 2378
2353 2379 def _prefilter(self, line, continue_prompt):
2354 2380 """Calls different preprocessors, depending on the form of line."""
2355 2381
2356 2382 # All handlers *must* return a value, even if it's blank ('').
2357 2383
2358 2384 # Lines are NOT logged here. Handlers should process the line as
2359 2385 # needed, update the cache AND log it (so that the input cache array
2360 2386 # stays synced).
2361 2387
2362 2388 #.....................................................................
2363 2389 # Code begins
2364 2390
2365 2391 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2366 2392
2367 2393 # save the line away in case we crash, so the post-mortem handler can
2368 2394 # record it
2369 2395 self._last_input_line = line
2370 2396
2371 2397 #print '***line: <%s>' % line # dbg
2372 2398
2373 2399 if not line:
2374 2400 # Return immediately on purely empty lines, so that if the user
2375 2401 # previously typed some whitespace that started a continuation
2376 2402 # prompt, he can break out of that loop with just an empty line.
2377 2403 # This is how the default python prompt works.
2378 2404
2379 2405 # Only return if the accumulated input buffer was just whitespace!
2380 2406 if ''.join(self.buffer).isspace():
2381 2407 self.buffer[:] = []
2382 2408 return ''
2383 2409
2384 2410 line_info = prefilter.LineInfo(line, continue_prompt)
2385 2411
2386 2412 # the input history needs to track even empty lines
2387 2413 stripped = line.strip()
2388 2414
2389 2415 if not stripped:
2390 2416 if not continue_prompt:
2391 2417 self.outputcache.prompt_count -= 1
2392 2418 return self.handle_normal(line_info)
2393 2419
2394 2420 # print '***cont',continue_prompt # dbg
2395 2421 # special handlers are only allowed for single line statements
2396 2422 if continue_prompt and not self.rc.multi_line_specials:
2397 2423 return self.handle_normal(line_info)
2398 2424
2399 2425
2400 2426 # See whether any pre-existing handler can take care of it
2401 2427 rewritten = self.hooks.input_prefilter(stripped)
2402 2428 if rewritten != stripped: # ok, some prefilter did something
2403 2429 rewritten = line_info.pre + rewritten # add indentation
2404 2430 return self.handle_normal(prefilter.LineInfo(rewritten,
2405 2431 continue_prompt))
2406 2432
2407 2433 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2408 2434
2409 2435 return prefilter.prefilter(line_info, self)
2410 2436
2411 2437
2412 2438 def _prefilter_dumb(self, line, continue_prompt):
2413 2439 """simple prefilter function, for debugging"""
2414 2440 return self.handle_normal(line,continue_prompt)
2415 2441
2416 2442
2417 2443 def multiline_prefilter(self, line, continue_prompt):
2418 2444 """ Run _prefilter for each line of input
2419 2445
2420 2446 Covers cases where there are multiple lines in the user entry,
2421 2447 which is the case when the user goes back to a multiline history
2422 2448 entry and presses enter.
2423 2449
2424 2450 """
2425 2451 out = []
2426 2452 for l in line.rstrip('\n').split('\n'):
2427 2453 out.append(self._prefilter(l, continue_prompt))
2428 2454 return '\n'.join(out)
2429 2455
2430 2456 # Set the default prefilter() function (this can be user-overridden)
2431 2457 prefilter = multiline_prefilter
2432 2458
2433 2459 def handle_normal(self,line_info):
2434 2460 """Handle normal input lines. Use as a template for handlers."""
2435 2461
2436 2462 # With autoindent on, we need some way to exit the input loop, and I
2437 2463 # don't want to force the user to have to backspace all the way to
2438 2464 # clear the line. The rule will be in this case, that either two
2439 2465 # lines of pure whitespace in a row, or a line of pure whitespace but
2440 2466 # of a size different to the indent level, will exit the input loop.
2441 2467 line = line_info.line
2442 2468 continue_prompt = line_info.continue_prompt
2443 2469
2444 2470 if (continue_prompt and self.autoindent and line.isspace() and
2445 2471 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2446 2472 (self.buffer[-1]).isspace() )):
2447 2473 line = ''
2448 2474
2449 2475 self.log(line,line,continue_prompt)
2450 2476 return line
2451 2477
2452 2478 def handle_alias(self,line_info):
2453 2479 """Handle alias input lines. """
2454 2480 tgt = self.alias_table[line_info.iFun]
2455 2481 # print "=>",tgt #dbg
2456 2482 if callable(tgt):
2457 2483 if '$' in line_info.line:
2458 2484 call_meth = '(_ip, _ip.itpl(%s))'
2459 2485 else:
2460 2486 call_meth = '(_ip,%s)'
2461 2487 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2462 2488 line_info.iFun,
2463 2489 make_quoted_expr(line_info.line))
2464 2490 else:
2465 2491 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2466 2492
2467 2493 # pre is needed, because it carries the leading whitespace. Otherwise
2468 2494 # aliases won't work in indented sections.
2469 2495 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2470 2496 make_quoted_expr( transformed ))
2471 2497
2472 2498 self.log(line_info.line,line_out,line_info.continue_prompt)
2473 2499 #print 'line out:',line_out # dbg
2474 2500 return line_out
2475 2501
2476 2502 def handle_shell_escape(self, line_info):
2477 2503 """Execute the line in a shell, empty return value"""
2478 2504 #print 'line in :', `line` # dbg
2479 2505 line = line_info.line
2480 2506 if line.lstrip().startswith('!!'):
2481 2507 # rewrite LineInfo's line, iFun and theRest to properly hold the
2482 2508 # call to %sx and the actual command to be executed, so
2483 2509 # handle_magic can work correctly. Note that this works even if
2484 2510 # the line is indented, so it handles multi_line_specials
2485 2511 # properly.
2486 2512 new_rest = line.lstrip()[2:]
2487 2513 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2488 2514 line_info.iFun = 'sx'
2489 2515 line_info.theRest = new_rest
2490 2516 return self.handle_magic(line_info)
2491 2517 else:
2492 2518 cmd = line.lstrip().lstrip('!')
2493 2519 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2494 2520 make_quoted_expr(cmd))
2495 2521 # update cache/log and return
2496 2522 self.log(line,line_out,line_info.continue_prompt)
2497 2523 return line_out
2498 2524
2499 2525 def handle_magic(self, line_info):
2500 2526 """Execute magic functions."""
2501 2527 iFun = line_info.iFun
2502 2528 theRest = line_info.theRest
2503 2529 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2504 2530 make_quoted_expr(iFun + " " + theRest))
2505 2531 self.log(line_info.line,cmd,line_info.continue_prompt)
2506 2532 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2507 2533 return cmd
2508 2534
2509 2535 def handle_auto(self, line_info):
2510 2536 """Hande lines which can be auto-executed, quoting if requested."""
2511 2537
2512 2538 line = line_info.line
2513 2539 iFun = line_info.iFun
2514 2540 theRest = line_info.theRest
2515 2541 pre = line_info.pre
2516 2542 continue_prompt = line_info.continue_prompt
2517 2543 obj = line_info.ofind(self)['obj']
2518 2544
2519 2545 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2520 2546
2521 2547 # This should only be active for single-line input!
2522 2548 if continue_prompt:
2523 2549 self.log(line,line,continue_prompt)
2524 2550 return line
2525 2551
2526 2552 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2527 2553 auto_rewrite = True
2528 2554
2529 2555 if pre == self.ESC_QUOTE:
2530 2556 # Auto-quote splitting on whitespace
2531 2557 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2532 2558 elif pre == self.ESC_QUOTE2:
2533 2559 # Auto-quote whole string
2534 2560 newcmd = '%s("%s")' % (iFun,theRest)
2535 2561 elif pre == self.ESC_PAREN:
2536 2562 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2537 2563 else:
2538 2564 # Auto-paren.
2539 2565 # We only apply it to argument-less calls if the autocall
2540 2566 # parameter is set to 2. We only need to check that autocall is <
2541 2567 # 2, since this function isn't called unless it's at least 1.
2542 2568 if not theRest and (self.rc.autocall < 2) and not force_auto:
2543 2569 newcmd = '%s %s' % (iFun,theRest)
2544 2570 auto_rewrite = False
2545 2571 else:
2546 2572 if not force_auto and theRest.startswith('['):
2547 2573 if hasattr(obj,'__getitem__'):
2548 2574 # Don't autocall in this case: item access for an object
2549 2575 # which is BOTH callable and implements __getitem__.
2550 2576 newcmd = '%s %s' % (iFun,theRest)
2551 2577 auto_rewrite = False
2552 2578 else:
2553 2579 # if the object doesn't support [] access, go ahead and
2554 2580 # autocall
2555 2581 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2556 2582 elif theRest.endswith(';'):
2557 2583 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2558 2584 else:
2559 2585 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2560 2586
2561 2587 if auto_rewrite:
2562 2588 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2563 2589
2564 2590 try:
2565 2591 # plain ascii works better w/ pyreadline, on some machines, so
2566 2592 # we use it and only print uncolored rewrite if we have unicode
2567 2593 rw = str(rw)
2568 2594 print >>Term.cout, rw
2569 2595 except UnicodeEncodeError:
2570 2596 print "-------------->" + newcmd
2571 2597
2572 2598 # log what is now valid Python, not the actual user input (without the
2573 2599 # final newline)
2574 2600 self.log(line,newcmd,continue_prompt)
2575 2601 return newcmd
2576 2602
2577 2603 def handle_help(self, line_info):
2578 2604 """Try to get some help for the object.
2579 2605
2580 2606 obj? or ?obj -> basic information.
2581 2607 obj?? or ??obj -> more details.
2582 2608 """
2583 2609
2584 2610 line = line_info.line
2585 2611 # We need to make sure that we don't process lines which would be
2586 2612 # otherwise valid python, such as "x=1 # what?"
2587 2613 try:
2588 2614 codeop.compile_command(line)
2589 2615 except SyntaxError:
2590 2616 # We should only handle as help stuff which is NOT valid syntax
2591 2617 if line[0]==self.ESC_HELP:
2592 2618 line = line[1:]
2593 2619 elif line[-1]==self.ESC_HELP:
2594 2620 line = line[:-1]
2595 2621 self.log(line,'#?'+line,line_info.continue_prompt)
2596 2622 if line:
2597 2623 #print 'line:<%r>' % line # dbg
2598 2624 self.magic_pinfo(line)
2599 2625 else:
2600 2626 page(self.usage,screen_lines=self.rc.screen_length)
2601 2627 return '' # Empty string is needed here!
2602 2628 except:
2603 2629 # Pass any other exceptions through to the normal handler
2604 2630 return self.handle_normal(line_info)
2605 2631 else:
2606 2632 # If the code compiles ok, we should handle it normally
2607 2633 return self.handle_normal(line_info)
2608 2634
2609 2635 def getapi(self):
2610 2636 """ Get an IPApi object for this shell instance
2611 2637
2612 2638 Getting an IPApi object is always preferable to accessing the shell
2613 2639 directly, but this holds true especially for extensions.
2614 2640
2615 2641 It should always be possible to implement an extension with IPApi
2616 2642 alone. If not, contact maintainer to request an addition.
2617 2643
2618 2644 """
2619 2645 return self.api
2620 2646
2621 2647 def handle_emacs(self, line_info):
2622 2648 """Handle input lines marked by python-mode."""
2623 2649
2624 2650 # Currently, nothing is done. Later more functionality can be added
2625 2651 # here if needed.
2626 2652
2627 2653 # The input cache shouldn't be updated
2628 2654 return line_info.line
2629 2655
2630 2656
2631 2657 def mktempfile(self,data=None):
2632 2658 """Make a new tempfile and return its filename.
2633 2659
2634 2660 This makes a call to tempfile.mktemp, but it registers the created
2635 2661 filename internally so ipython cleans it up at exit time.
2636 2662
2637 2663 Optional inputs:
2638 2664
2639 2665 - data(None): if data is given, it gets written out to the temp file
2640 2666 immediately, and the file is closed again."""
2641 2667
2642 2668 filename = tempfile.mktemp('.py','ipython_edit_')
2643 2669 self.tempfiles.append(filename)
2644 2670
2645 2671 if data:
2646 2672 tmp_file = open(filename,'w')
2647 2673 tmp_file.write(data)
2648 2674 tmp_file.close()
2649 2675 return filename
2650 2676
2651 2677 def write(self,data):
2652 2678 """Write a string to the default output"""
2653 2679 Term.cout.write(data)
2654 2680
2655 2681 def write_err(self,data):
2656 2682 """Write a string to the default error output"""
2657 2683 Term.cerr.write(data)
2658 2684
2659 2685 def ask_exit(self):
2660 2686 """ Call for exiting. Can be overiden and used as a callback. """
2661 2687 self.exit_now = True
2662 2688
2663 2689 def exit(self):
2664 2690 """Handle interactive exit.
2665 2691
2666 2692 This method calls the ask_exit callback."""
2667 2693
2668 2694 if self.rc.confirm_exit:
2669 2695 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2670 2696 self.ask_exit()
2671 2697 else:
2672 2698 self.ask_exit()
2673 2699
2674 2700 def safe_execfile(self,fname,*where,**kw):
2675 2701 """A safe version of the builtin execfile().
2676 2702
2677 2703 This version will never throw an exception, and knows how to handle
2678 2704 ipython logs as well.
2679 2705
2680 2706 :Parameters:
2681 2707 fname : string
2682 2708 Name of the file to be executed.
2683 2709
2684 2710 where : tuple
2685 2711 One or two namespaces, passed to execfile() as (globals,locals).
2686 2712 If only one is given, it is passed as both.
2687 2713
2688 2714 :Keywords:
2689 2715 islog : boolean (False)
2690 2716
2691 2717 quiet : boolean (True)
2692 2718
2693 2719 exit_ignore : boolean (False)
2694 2720 """
2695 2721
2696 2722 def syspath_cleanup():
2697 2723 """Internal cleanup routine for sys.path."""
2698 2724 if add_dname:
2699 2725 try:
2700 2726 sys.path.remove(dname)
2701 2727 except ValueError:
2702 2728 # For some reason the user has already removed it, ignore.
2703 2729 pass
2704 2730
2705 2731 fname = os.path.expanduser(fname)
2706 2732
2707 2733 # Find things also in current directory. This is needed to mimic the
2708 2734 # behavior of running a script from the system command line, where
2709 2735 # Python inserts the script's directory into sys.path
2710 2736 dname = os.path.dirname(os.path.abspath(fname))
2711 2737 add_dname = False
2712 2738 if dname not in sys.path:
2713 2739 sys.path.insert(0,dname)
2714 2740 add_dname = True
2715 2741
2716 2742 try:
2717 2743 xfile = open(fname)
2718 2744 except:
2719 2745 print >> Term.cerr, \
2720 2746 'Could not open file <%s> for safe execution.' % fname
2721 2747 syspath_cleanup()
2722 2748 return None
2723 2749
2724 2750 kw.setdefault('islog',0)
2725 2751 kw.setdefault('quiet',1)
2726 2752 kw.setdefault('exit_ignore',0)
2727 2753
2728 2754 first = xfile.readline()
2729 2755 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2730 2756 xfile.close()
2731 2757 # line by line execution
2732 2758 if first.startswith(loghead) or kw['islog']:
2733 2759 print 'Loading log file <%s> one line at a time...' % fname
2734 2760 if kw['quiet']:
2735 2761 stdout_save = sys.stdout
2736 2762 sys.stdout = StringIO.StringIO()
2737 2763 try:
2738 2764 globs,locs = where[0:2]
2739 2765 except:
2740 2766 try:
2741 2767 globs = locs = where[0]
2742 2768 except:
2743 2769 globs = locs = globals()
2744 2770 badblocks = []
2745 2771
2746 2772 # we also need to identify indented blocks of code when replaying
2747 2773 # logs and put them together before passing them to an exec
2748 2774 # statement. This takes a bit of regexp and look-ahead work in the
2749 2775 # file. It's easiest if we swallow the whole thing in memory
2750 2776 # first, and manually walk through the lines list moving the
2751 2777 # counter ourselves.
2752 2778 indent_re = re.compile('\s+\S')
2753 2779 xfile = open(fname)
2754 2780 filelines = xfile.readlines()
2755 2781 xfile.close()
2756 2782 nlines = len(filelines)
2757 2783 lnum = 0
2758 2784 while lnum < nlines:
2759 2785 line = filelines[lnum]
2760 2786 lnum += 1
2761 2787 # don't re-insert logger status info into cache
2762 2788 if line.startswith('#log#'):
2763 2789 continue
2764 2790 else:
2765 2791 # build a block of code (maybe a single line) for execution
2766 2792 block = line
2767 2793 try:
2768 2794 next = filelines[lnum] # lnum has already incremented
2769 2795 except:
2770 2796 next = None
2771 2797 while next and indent_re.match(next):
2772 2798 block += next
2773 2799 lnum += 1
2774 2800 try:
2775 2801 next = filelines[lnum]
2776 2802 except:
2777 2803 next = None
2778 2804 # now execute the block of one or more lines
2779 2805 try:
2780 2806 exec block in globs,locs
2781 2807 except SystemExit:
2782 2808 pass
2783 2809 except:
2784 2810 badblocks.append(block.rstrip())
2785 2811 if kw['quiet']: # restore stdout
2786 2812 sys.stdout.close()
2787 2813 sys.stdout = stdout_save
2788 2814 print 'Finished replaying log file <%s>' % fname
2789 2815 if badblocks:
2790 2816 print >> sys.stderr, ('\nThe following lines/blocks in file '
2791 2817 '<%s> reported errors:' % fname)
2792 2818
2793 2819 for badline in badblocks:
2794 2820 print >> sys.stderr, badline
2795 2821 else: # regular file execution
2796 2822 try:
2797 2823 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2798 2824 # Work around a bug in Python for Windows. The bug was
2799 2825 # fixed in in Python 2.5 r54159 and 54158, but that's still
2800 2826 # SVN Python as of March/07. For details, see:
2801 2827 # http://projects.scipy.org/ipython/ipython/ticket/123
2802 2828 try:
2803 2829 globs,locs = where[0:2]
2804 2830 except:
2805 2831 try:
2806 2832 globs = locs = where[0]
2807 2833 except:
2808 2834 globs = locs = globals()
2809 2835 exec file(fname) in globs,locs
2810 2836 else:
2811 2837 execfile(fname,*where)
2812 2838 except SyntaxError:
2813 2839 self.showsyntaxerror()
2814 2840 warn('Failure executing file: <%s>' % fname)
2815 2841 except SystemExit,status:
2816 2842 # Code that correctly sets the exit status flag to success (0)
2817 2843 # shouldn't be bothered with a traceback. Note that a plain
2818 2844 # sys.exit() does NOT set the message to 0 (it's empty) so that
2819 2845 # will still get a traceback. Note that the structure of the
2820 2846 # SystemExit exception changed between Python 2.4 and 2.5, so
2821 2847 # the checks must be done in a version-dependent way.
2822 2848 show = False
2823 2849
2824 2850 if sys.version_info[:2] > (2,5):
2825 2851 if status.message!=0 and not kw['exit_ignore']:
2826 2852 show = True
2827 2853 else:
2828 2854 if status.code and not kw['exit_ignore']:
2829 2855 show = True
2830 2856 if show:
2831 2857 self.showtraceback()
2832 2858 warn('Failure executing file: <%s>' % fname)
2833 2859 except:
2834 2860 self.showtraceback()
2835 2861 warn('Failure executing file: <%s>' % fname)
2836 2862
2837 2863 syspath_cleanup()
2838 2864
2839 2865 #************************* end of file <iplib.py> *****************************
@@ -1,149 +1,151 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
6 6 # Standard library imports
7 7 import os
8 8 import sys
9 9
10 10 # Third-party imports
11 11 import nose.tools as nt
12 12
13 13 # From our own code
14 14 from IPython.testing import decorators as dec
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Test functions begin
18 18
19 19 def test_rehashx():
20 20 # clear up everything
21 21 _ip.IP.alias_table.clear()
22 22 del _ip.db['syscmdlist']
23 23
24 24 _ip.magic('rehashx')
25 25 # Practically ALL ipython development systems will have more than 10 aliases
26 26
27 27 assert len(_ip.IP.alias_table) > 10
28 28 for key, val in _ip.IP.alias_table.items():
29 29 # we must strip dots from alias names
30 30 assert '.' not in key
31 31
32 32 # rehashx must fill up syscmdlist
33 33 scoms = _ip.db['syscmdlist']
34 34 assert len(scoms) > 10
35 35
36 36
37 37 def doctest_run_ns():
38 38 """Classes declared %run scripts must be instantiable afterwards.
39 39
40 40 In [11]: run tclass foo
41 41
42 42 In [12]: isinstance(f(),foo)
43 43 Out[12]: True
44 44 """
45 45
46 46
47 47 def doctest_run_ns2():
48 48 """Classes declared %run scripts must be instantiable afterwards.
49 49
50 50 In [4]: run tclass C-first_pass
51 51
52 52 In [5]: run tclass C-second_pass
53 53 tclass.py: deleting object: C-first_pass
54 54 """
55 55
56 56
57 57 def doctest_hist_f():
58 58 """Test %hist -f with temporary filename.
59 59
60 60 In [9]: import tempfile
61 61
62 62 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
63 63
64 64 In [11]: %history -n -f $tfile 3
65 65 """
66 66
67 67
68 68 def doctest_hist_r():
69 69 """Test %hist -r
70 70
71 71 XXX - This test is not recording the output correctly. Not sure why...
72 72
73 73 In [6]: x=1
74 74
75 75 In [7]: hist -n -r 2
76 76 x=1 # random
77 77 hist -n -r 2 # random
78 78 """
79 79
80 80
81 81 def test_obj_del():
82 82 """Test that object's __del__ methods are called on exit."""
83 83 test_dir = os.path.dirname(__file__)
84 84 del_file = os.path.join(test_dir,'obj_del.py')
85 85 out = _ip.IP.getoutput('ipython %s' % del_file)
86 86 nt.assert_equals(out,'obj_del.py: object A deleted')
87 87
88 88
89 89 def test_shist():
90 90 # Simple tests of ShadowHist class - test generator.
91 91 import os, shutil, tempfile
92 92
93 93 from IPython.Extensions import pickleshare
94 94 from IPython.history import ShadowHist
95 95
96 96 tfile = tempfile.mktemp('','tmp-ipython-')
97 97
98 98 db = pickleshare.PickleShareDB(tfile)
99 99 s = ShadowHist(db)
100 100 s.add('hello')
101 101 s.add('world')
102 102 s.add('hello')
103 103 s.add('hello')
104 104 s.add('karhu')
105 105
106 106 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
107 107
108 108 yield nt.assert_equal,s.get(2),'world'
109 109
110 110 shutil.rmtree(tfile)
111 111
112 112 @dec.skipif_not_numpy
113 113 def test_numpy_clear_array_undec():
114 114 _ip.ex('import numpy as np')
115 115 _ip.ex('a = np.empty(2)')
116 116
117 117 yield nt.assert_true,'a' in _ip.user_ns
118 118 _ip.magic('clear array')
119 119 yield nt.assert_false,'a' in _ip.user_ns
120 120
121 121
122 122 @dec.skip()
123 123 def test_fail_dec(*a,**k):
124 124 yield nt.assert_true, False
125 125
126 126 @dec.skip('This one shouldn not run')
127 127 def test_fail_dec2(*a,**k):
128 128 yield nt.assert_true, False
129 129
130 130 @dec.skipknownfailure
131 131 def test_fail_dec3(*a,**k):
132 132 yield nt.assert_true, False
133 133
134 134
135 135 def doctest_refbug():
136 136 """Very nasty problem with references held by multiple runs of a script.
137 137 See: https://bugs.launchpad.net/ipython/+bug/269966
138 138
139 In [1]: _ip.IP.clear_main_mod_cache()
140
139 141 In [2]: run refbug
140 142
141 143 In [3]: call_f()
142 144 lowercased: hello
143 145
144 146 In [4]: run refbug
145 147
146 148 In [5]: call_f()
147 149 lowercased: hello
148 150 lowercased: hello
149 151 """
General Comments 0
You need to be logged in to leave comments. Login now