##// END OF EJS Templates
Wildcard system cleanup, ipmaker speedups, bugfix in globals handling...
fperez -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,2510 +1,2563 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 922 2005-11-13 10:21:08Z fperez $"""
4 $Id: Magic.py 923 2005-11-15 08:51:15Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time
25 25 try:
26 26 import profile,pstats
27 27 except ImportError:
28 28 profile = pstats = None
29 29 from getopt import getopt
30 30 from pprint import pprint, pformat
31 31 from cStringIO import StringIO
32 32
33 33 # Homebrewed
34 34 from IPython.Struct import Struct
35 35 from IPython.Itpl import Itpl, itpl, printpl,itplns
36 36 from IPython.FakeModule import FakeModule
37 37 from IPython.PyColorize import Parser
38 38 from IPython import OInspect
39 39 from IPython import wildcard
40 40 from IPython.genutils import *
41 41
42 42 # Globals to be set later by Magic constructor
43 43 MAGIC_PREFIX = ''
44 44 MAGIC_ESCAPE = ''
45 45
46 46 #***************************************************************************
47 47 # Utility functions
48 48 def magic2python(cmd):
49 49 """Convert a command string of magic syntax to valid Python code."""
50 50
51 51 if cmd.startswith('#'+MAGIC_ESCAPE) or \
52 52 cmd.startswith(MAGIC_ESCAPE):
53 53 if cmd[0]=='#':
54 54 cmd = cmd[1:]
55 55 # we need to return the proper line end later
56 56 if cmd[-1] == '\n':
57 57 endl = '\n'
58 58 else:
59 59 endl = ''
60 60 try:
61 61 func,args = cmd[1:].split(' ',1)
62 62 except:
63 63 func,args = cmd[1:].rstrip(),''
64 64 args = args.replace('"','\\"').replace("'","\\'").rstrip()
65 65 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
66 66 else:
67 67 return cmd
68 68
69 69 def on_off(tag):
70 70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
71 71 return ['OFF','ON'][tag]
72 72
73 73
74 74 #****************************************************************************
75 75 # Utility classes
76 76 class Macro:
77 77 """Simple class to store the value of macros as strings.
78 78
79 79 This allows us to later exec them by checking when something is an
80 80 instance of this class."""
81 81
82 82 def __init__(self,cmds):
83 83 """Build a macro from a list of commands."""
84 84
85 85 # Since the list may include multi-line entries, first make sure that
86 86 # they've been all broken up before passing it to magic2python
87 87 cmdlist = map(magic2python,''.join(cmds).split('\n'))
88 88 self.value = '\n'.join(cmdlist)
89 89
90 90 def __str__(self):
91 91 return self.value
92 92
93 93 #***************************************************************************
94 94 # Main class implementing Magic functionality
95 95 class Magic:
96 96 """Magic functions for InteractiveShell.
97 97
98 98 Shell functions which can be reached as %function_name. All magic
99 99 functions should accept a string, which they can parse for their own
100 100 needs. This can make some functions easier to type, eg `%cd ../`
101 101 vs. `%cd("../")`
102 102
103 103 ALL definitions MUST begin with the prefix magic_. The user won't need it
104 104 at the command line, but it is is needed in the definition. """
105 105
106 106 # class globals
107 107 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
108 108 'Automagic is ON, % prefix NOT needed for magic functions.']
109 109
110 110 #......................................................................
111 111 # some utility functions
112 112
113 113 def __init__(self,shell):
114 114 # XXX This is hackish, clean up later to avoid these messy globals
115 115 global MAGIC_PREFIX, MAGIC_ESCAPE
116 116
117 117 self.options_table = {}
118 118 MAGIC_PREFIX = shell.name+'.magic_'
119 119 MAGIC_ESCAPE = shell.ESC_MAGIC
120 120 if profile is None:
121 121 self.magic_prun = self.profile_missing_notice
122 122
123 123 def profile_missing_notice(self, *args, **kwargs):
124 124 error("""\
125 125 The profile module could not be found. If you are a Debian user,
126 126 it has been removed from the standard Debian package because of its non-free
127 127 license. To use profiling, please install"python2.3-profiler" from non-free.""")
128 128
129 129 def default_option(self,fn,optstr):
130 130 """Make an entry in the options_table for fn, with value optstr"""
131 131
132 132 if fn not in self.lsmagic():
133 133 error("%s is not a magic function" % fn)
134 134 self.options_table[fn] = optstr
135 135
136 136 def lsmagic(self):
137 137 """Return a list of currently available magic functions.
138 138
139 139 Gives a list of the bare names after mangling (['ls','cd', ...], not
140 140 ['magic_ls','magic_cd',...]"""
141 141
142 142 # FIXME. This needs a cleanup, in the way the magics list is built.
143 143
144 144 # magics in class definition
145 145 class_magic = lambda fn: fn.startswith('magic_') and \
146 146 callable(Magic.__dict__[fn])
147 147 # in instance namespace (run-time user additions)
148 148 inst_magic = lambda fn: fn.startswith('magic_') and \
149 149 callable(self.__dict__[fn])
150 150 # and bound magics by user (so they can access self):
151 151 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
152 152 callable(self.__class__.__dict__[fn])
153 153 magics = filter(class_magic,Magic.__dict__.keys()) + \
154 154 filter(inst_magic,self.__dict__.keys()) + \
155 155 filter(inst_bound_magic,self.__class__.__dict__.keys())
156 156 out = []
157 157 for fn in magics:
158 158 out.append(fn.replace('magic_','',1))
159 159 out.sort()
160 160 return out
161 161
162 162 def set_shell(self,shell):
163 163 self.shell = shell
164 164 self.alias_table = shell.alias_table
165 165
166 166 def extract_input_slices(self,slices):
167 167 """Return as a string a set of input history slices.
168 168
169 169 The set of slices is given as a list of strings (like ['1','4:8','9'],
170 170 since this function is for use by magic functions which get their
171 171 arguments as strings."""
172 172
173 173 cmds = []
174 174 for chunk in slices:
175 175 if ':' in chunk:
176 176 ini,fin = map(int,chunk.split(':'))
177 177 else:
178 178 ini = int(chunk)
179 179 fin = ini+1
180 180 cmds.append(self.shell.input_hist[ini:fin])
181 181 return cmds
182 182
183 183 def _ofind(self,oname):
184 184 """Find an object in the available namespaces.
185 185
186 186 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
187 187
188 188 Has special code to detect magic functions.
189 189 """
190 190
191 191 oname = oname.strip()
192 192
193 193 # Namespaces to search in:
194 194 user_ns = self.shell.user_ns
195 195 internal_ns = self.shell.internal_ns
196 196 builtin_ns = __builtin__.__dict__
197 197 alias_ns = self.shell.alias_table
198 198
199 199 # Put them in a list. The order is important so that we find things in
200 200 # the same order that Python finds them.
201 201 namespaces = [ ('Interactive',user_ns),
202 202 ('IPython internal',internal_ns),
203 203 ('Python builtin',builtin_ns),
204 204 ('Alias',alias_ns),
205 205 ]
206 206
207 207 # initialize results to 'null'
208 208 found = 0; obj = None; ospace = None; ds = None;
209 209 ismagic = 0; isalias = 0
210 210
211 211 # Look for the given name by splitting it in parts. If the head is
212 212 # found, then we look for all the remaining parts as members, and only
213 213 # declare success if we can find them all.
214 214 oname_parts = oname.split('.')
215 215 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
216 216 for nsname,ns in namespaces:
217 217 try:
218 218 obj = ns[oname_head]
219 219 except KeyError:
220 220 continue
221 221 else:
222 222 for part in oname_rest:
223 223 try:
224 224 obj = getattr(obj,part)
225 225 except:
226 226 # Blanket except b/c some badly implemented objects
227 227 # allow __getattr__ to raise exceptions other than
228 228 # AttributeError, which then crashes IPython.
229 229 break
230 230 else:
231 231 # If we finish the for loop (no break), we got all members
232 232 found = 1
233 233 ospace = nsname
234 234 if ns == alias_ns:
235 235 isalias = 1
236 236 break # namespace loop
237 237
238 238 # Try to see if it's magic
239 239 if not found:
240 240 if oname.startswith(self.shell.ESC_MAGIC):
241 241 oname = oname[1:]
242 242 obj = getattr(self,'magic_'+oname,None)
243 243 if obj is not None:
244 244 found = 1
245 245 ospace = 'IPython internal'
246 246 ismagic = 1
247 247
248 248 # Last try: special-case some literals like '', [], {}, etc:
249 249 if not found and oname_head in ["''",'""','[]','{}','()']:
250 250 obj = eval(oname_head)
251 251 found = 1
252 252 ospace = 'Interactive'
253 253
254 254 return {'found':found, 'obj':obj, 'namespace':ospace,
255 255 'ismagic':ismagic, 'isalias':isalias}
256 256
257 257 def arg_err(self,func):
258 258 """Print docstring if incorrect arguments were passed"""
259 259 print 'Error in arguments:'
260 260 print OInspect.getdoc(func)
261 261
262 262
263 263 def format_latex(self,str):
264 264 """Format a string for latex inclusion."""
265 265
266 266 # Characters that need to be escaped for latex:
267 267 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
268 268 # Magic command names as headers:
269 269 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
270 270 re.MULTILINE)
271 271 # Magic commands
272 272 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
273 273 re.MULTILINE)
274 274 # Paragraph continue
275 275 par_re = re.compile(r'\\$',re.MULTILINE)
276 276
277 277 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
278 278 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
279 279 str = par_re.sub(r'\\\\',str)
280 280 str = escape_re.sub(r'\\\1',str)
281 281 return str
282 282
283 283 def format_screen(self,str):
284 284 """Format a string for screen printing.
285 285
286 286 This removes some latex-type format codes."""
287 287 # Paragraph continue
288 288 par_re = re.compile(r'\\$',re.MULTILINE)
289 289 str = par_re.sub('',str)
290 290 return str
291 291
292 292 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
293 293 """Parse options passed to an argument string.
294 294
295 295 The interface is similar to that of getopt(), but it returns back a
296 296 Struct with the options as keys and the stripped argument string still
297 297 as a string.
298 298
299 arg_str is quoted as a true sys.argv vector by calling on the fly a
300 python process in a subshell. This allows us to easily expand
301 variables, glob files, quote arguments, etc, with all the power and
302 correctness of the underlying system shell.
299 arg_str is quoted as a true sys.argv vector by using shlex.split.
300 This allows us to easily expand variables, glob files, quote
301 arguments, etc.
303 302
304 303 Options:
305 304 -mode: default 'string'. If given as 'list', the argument string is
306 305 returned as a list (split on whitespace) instead of a string.
307 306
308 307 -list_all: put all option values in lists. Normally only options
309 308 appearing more than once are put in a list."""
310 309
311 310 # inject default options at the beginning of the input line
312 311 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
313 312 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
314 313
315 314 mode = kw.get('mode','string')
316 315 if mode not in ['string','list']:
317 316 raise ValueError,'incorrect mode given: %s' % mode
318 317 # Get options
319 318 list_all = kw.get('list_all',0)
320 319
321 320 # Check if we have more than one argument to warrant extra processing:
322 321 odict = {} # Dictionary with options
323 322 args = arg_str.split()
324 323 if len(args) >= 1:
325 324 # If the list of inputs only has 0 or 1 thing in it, there's no
326 325 # need to look for options
327 326 argv = shlex_split(arg_str)
328 327 # Do regular option processing
329 328 opts,args = getopt(argv,opt_str,*long_opts)
330 329 for o,a in opts:
331 330 if o.startswith('--'):
332 331 o = o[2:]
333 332 else:
334 333 o = o[1:]
335 334 try:
336 335 odict[o].append(a)
337 336 except AttributeError:
338 337 odict[o] = [odict[o],a]
339 338 except KeyError:
340 339 if list_all:
341 340 odict[o] = [a]
342 341 else:
343 342 odict[o] = a
344 343
345 344 # Prepare opts,args for return
346 345 opts = Struct(odict)
347 346 if mode == 'string':
348 347 args = ' '.join(args)
349 348
350 349 return opts,args
351 350
352 351 #......................................................................
353 352 # And now the actual magic functions
354 353
355 354 # Functions for IPython shell work (vars,funcs, config, etc)
356 355 def magic_lsmagic(self, parameter_s = ''):
357 356 """List currently available magic functions."""
358 357 mesc = self.shell.ESC_MAGIC
359 358 print 'Available magic functions:\n'+mesc+\
360 359 (' '+mesc).join(self.lsmagic())
361 360 print '\n' + Magic.auto_status[self.shell.rc.automagic]
362 361 return None
363 362
364 363 def magic_magic(self, parameter_s = ''):
365 364 """Print information about the magic function system."""
366 365
367 366 mode = ''
368 367 try:
369 368 if parameter_s.split()[0] == '-latex':
370 369 mode = 'latex'
371 370 except:
372 371 pass
373 372
374 373 magic_docs = []
375 374 for fname in self.lsmagic():
376 375 mname = 'magic_' + fname
377 376 for space in (Magic,self,self.__class__):
378 377 try:
379 378 fn = space.__dict__[mname]
380 379 except KeyError:
381 380 pass
382 381 else:
383 382 break
384 383 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
385 384 fname,fn.__doc__))
386 385 magic_docs = ''.join(magic_docs)
387 386
388 387 if mode == 'latex':
389 388 print self.format_latex(magic_docs)
390 389 return
391 390 else:
392 391 magic_docs = self.format_screen(magic_docs)
393 392
394 393 outmsg = """
395 394 IPython's 'magic' functions
396 395 ===========================
397 396
398 397 The magic function system provides a series of functions which allow you to
399 398 control the behavior of IPython itself, plus a lot of system-type
400 399 features. All these functions are prefixed with a % character, but parameters
401 400 are given without parentheses or quotes.
402 401
403 402 NOTE: If you have 'automagic' enabled (via the command line option or with the
404 403 %automagic function), you don't need to type in the % explicitly. By default,
405 404 IPython ships with automagic on, so you should only rarely need the % escape.
406 405
407 406 Example: typing '%cd mydir' (without the quotes) changes you working directory
408 407 to 'mydir', if it exists.
409 408
410 409 You can define your own magic functions to extend the system. See the supplied
411 410 ipythonrc and example-magic.py files for details (in your ipython
412 411 configuration directory, typically $HOME/.ipython/).
413 412
414 413 You can also define your own aliased names for magic functions. In your
415 414 ipythonrc file, placing a line like:
416 415
417 416 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
418 417
419 418 will define %pf as a new name for %profile.
420 419
421 420 You can also call magics in code using the ipmagic() function, which IPython
422 421 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
423 422
424 423 For a list of the available magic functions, use %lsmagic. For a description
425 424 of any of them, type %magic_name?, e.g. '%cd?'.
426 425
427 426 Currently the magic system has the following functions:\n"""
428 427
429 428 mesc = self.shell.ESC_MAGIC
430 429 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
431 430 "\n\n%s%s\n\n%s" % (outmsg,
432 431 magic_docs,mesc,mesc,
433 432 (' '+mesc).join(self.lsmagic()),
434 433 Magic.auto_status[self.shell.rc.automagic] ) )
435 434
436 435 page(outmsg,screen_lines=self.shell.rc.screen_length)
437 436
438 437 def magic_automagic(self, parameter_s = ''):
439 438 """Make magic functions callable without having to type the initial %.
440 439
441 440 Toggles on/off (when off, you must call it as %automagic, of
442 441 course). Note that magic functions have lowest priority, so if there's
443 442 a variable whose name collides with that of a magic fn, automagic
444 443 won't work for that function (you get the variable instead). However,
445 444 if you delete the variable (del var), the previously shadowed magic
446 445 function becomes visible to automagic again."""
447 446
448 447 rc = self.shell.rc
449 448 rc.automagic = not rc.automagic
450 449 print '\n' + Magic.auto_status[rc.automagic]
451 450
452 451 def magic_autocall(self, parameter_s = ''):
453 452 """Make functions callable without having to type parentheses.
454 453
455 454 This toggles the autocall command line option on and off."""
456 455
457 456 rc = self.shell.rc
458 457 rc.autocall = not rc.autocall
459 458 print "Automatic calling is:",['OFF','ON'][rc.autocall]
460 459
461 460 def magic_autoindent(self, parameter_s = ''):
462 461 """Toggle autoindent on/off (if available)."""
463 462
464 463 self.shell.set_autoindent()
465 464 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
466 465
467 466 def magic_system_verbose(self, parameter_s = ''):
468 467 """Toggle verbose printing of system calls on/off."""
469 468
470 469 self.shell.rc_set_toggle('system_verbose')
471 470 print "System verbose printing is:",\
472 471 ['OFF','ON'][self.shell.rc.system_verbose]
473 472
474 473 def magic_history(self, parameter_s = ''):
475 474 """Print input history (_i<n> variables), with most recent last.
476 475
477 476 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
478 477 %history [-n] n -> print at most n inputs\\
479 478 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
480 479
481 480 Each input's number <n> is shown, and is accessible as the
482 481 automatically generated variable _i<n>. Multi-line statements are
483 482 printed starting at a new line for easy copy/paste.
484 483
485 484 If option -n is used, input numbers are not printed. This is useful if
486 485 you want to get a printout of many lines which can be directly pasted
487 486 into a text editor.
488 487
489 488 This feature is only available if numbered prompts are in use."""
490 489
491 490 if not self.do_full_cache:
492 491 print 'This feature is only available if numbered prompts are in use.'
493 492 return
494 493 opts,args = self.parse_options(parameter_s,'n',mode='list')
495 494
496 495 default_length = 40
497 496 if len(args) == 0:
498 497 final = self.outputcache.prompt_count
499 498 init = max(1,final-default_length)
500 499 elif len(args) == 1:
501 500 final = self.outputcache.prompt_count
502 501 init = max(1,final-int(args[0]))
503 502 elif len(args) == 2:
504 503 init,final = map(int,args)
505 504 else:
506 505 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
507 506 print self.magic_hist.__doc__
508 507 return
509 508 width = len(str(final))
510 509 line_sep = ['','\n']
511 510 input_hist = self.shell.input_hist
512 511 print_nums = not opts.has_key('n')
513 512 for in_num in range(init,final):
514 513 inline = input_hist[in_num]
515 514 multiline = inline.count('\n') > 1
516 515 if print_nums:
517 516 print str(in_num).ljust(width)+':'+ line_sep[multiline],
518 517 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
519 518 inline.startswith('#!'):
520 519 print inline[1:],
521 520 else:
522 521 print inline,
523 522
524 523 def magic_hist(self, parameter_s=''):
525 524 """Alternate name for %history."""
526 525 return self.magic_history(parameter_s)
527 526
528 527 def magic_p(self, parameter_s=''):
529 528 """Just a short alias for Python's 'print'."""
530 529 exec 'print ' + parameter_s in self.shell.user_ns
531 530
532 531 def magic_r(self, parameter_s=''):
533 532 """Repeat previous input.
534 533
535 534 If given an argument, repeats the previous command which starts with
536 535 the same string, otherwise it just repeats the previous input.
537 536
538 537 Shell escaped commands (with ! as first character) are not recognized
539 538 by this system, only pure python code and magic commands.
540 539 """
541 540
542 541 start = parameter_s.strip()
543 542 esc_magic = self.shell.ESC_MAGIC
544 543 # Identify magic commands even if automagic is on (which means
545 544 # the in-memory version is different from that typed by the user).
546 545 if self.shell.rc.automagic:
547 546 start_magic = esc_magic+start
548 547 else:
549 548 start_magic = start
550 549 # Look through the input history in reverse
551 550 for n in range(len(self.shell.input_hist)-2,0,-1):
552 551 input = self.shell.input_hist[n]
553 552 # skip plain 'r' lines so we don't recurse to infinity
554 553 if input != 'ipmagic("r")\n' and \
555 554 (input.startswith(start) or input.startswith(start_magic)):
556 555 #print 'match',`input` # dbg
557 556 if input.startswith(esc_magic):
558 557 input = magic2python(input)
559 558 #print 'modified',`input` # dbg
560 559 print 'Executing:',input,
561 560 exec input in self.shell.user_ns
562 561 return
563 562 print 'No previous input matching `%s` found.' % start
564 563
565 564 def magic_page(self, parameter_s=''):
566 565 """Pretty print the object and display it through a pager.
567 566
568 567 If no parameter is given, use _ (last output)."""
569 568 # After a function contributed by Olivier Aubert, slightly modified.
570 569
571 570 oname = parameter_s and parameter_s or '_'
572 571 info = self._ofind(oname)
573 572 if info['found']:
574 573 page(pformat(info['obj']))
575 574 else:
576 575 print 'Object `%s` not found' % oname
577 576
578 577 def magic_profile(self, parameter_s=''):
579 578 """Print your currently active IPyhton profile."""
580 579 if self.shell.rc.profile:
581 580 printpl('Current IPython profile: $self.shell.rc.profile.')
582 581 else:
583 582 print 'No profile active.'
584 583
585 584 def _inspect(self,meth,oname,**kw):
586 585 """Generic interface to the inspector system.
587 586
588 587 This function is meant to be called by pdef, pdoc & friends."""
589 588
590 589 oname = oname.strip()
591 590 info = Struct(self._ofind(oname))
592 591 if info.found:
593 592 pmethod = getattr(self.shell.inspector,meth)
594 593 formatter = info.ismagic and self.format_screen or None
595 594 if meth == 'pdoc':
596 595 pmethod(info.obj,oname,formatter)
597 596 elif meth == 'pinfo':
598 597 pmethod(info.obj,oname,formatter,info,**kw)
599 598 else:
600 599 pmethod(info.obj,oname)
601 600 else:
602 601 print 'Object `%s` not found.' % oname
603 602 return 'not found' # so callers can take other action
604 603
605 604 def magic_pdef(self, parameter_s=''):
606 605 """Print the definition header for any callable object.
607 606
608 607 If the object is a class, print the constructor information."""
609 608 self._inspect('pdef',parameter_s)
610 609
611 610 def magic_pdoc(self, parameter_s=''):
612 611 """Print the docstring for an object.
613 612
614 613 If the given object is a class, it will print both the class and the
615 614 constructor docstrings."""
616 615 self._inspect('pdoc',parameter_s)
617 616
618 617 def magic_psource(self, parameter_s=''):
619 618 """Print (or run through pager) the source code for an object."""
620 619 self._inspect('psource',parameter_s)
621 620
622 621 def magic_pfile(self, parameter_s=''):
623 622 """Print (or run through pager) the file where an object is defined.
624 623
625 624 The file opens at the line where the object definition begins. IPython
626 625 will honor the environment variable PAGER if set, and otherwise will
627 626 do its best to print the file in a convenient form.
628 627
629 628 If the given argument is not an object currently defined, IPython will
630 629 try to interpret it as a filename (automatically adding a .py extension
631 630 if needed). You can thus use %pfile as a syntax highlighting code
632 631 viewer."""
633 632
634 633 # first interpret argument as an object name
635 634 out = self._inspect('pfile',parameter_s)
636 635 # if not, try the input as a filename
637 636 if out == 'not found':
638 637 try:
639 638 filename = get_py_filename(parameter_s)
640 639 except IOError,msg:
641 640 print msg
642 641 return
643 642 page(self.shell.inspector.format(file(filename).read()))
644 643
645 644 def magic_pinfo(self, parameter_s=''):
646 645 """Provide detailed information about an object.
647 646
648 647 '%pinfo object' is just a synonym for object? or ?object."""
649 648
650 649 #print 'pinfo par: <%s>' % parameter_s # dbg
651 650
652 651 # detail_level: 0 -> obj? , 1 -> obj??
653 652 detail_level = 0
654 653 # We need to detect if we got called as 'pinfo pinfo foo', which can
655 654 # happen if the user types 'pinfo foo?' at the cmd line.
656 655 pinfo,qmark1,oname,qmark2 = \
657 656 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
658 657 if pinfo or qmark1 or qmark2:
659 658 detail_level = 1
660 659 if "*" in oname:
661 660 self.magic_psearch(oname)
662 661 else:
663 662 self._inspect('pinfo',oname,detail_level=detail_level)
664 663
665 664 def magic_psearch(self, parameter_s=''):
666 665 """Search for object in namespaces by wildcard.
667 666
668 %psearch PATTERN [OBJECT TYPE] [-NAMESPACE]* [+NAMESPACE]* [-a] [-c]
667 %psearch [options] PATTERN [OBJECT TYPE]
669 668
670 669 Note: ? can be used as a synonym for %psearch, at the beginning or at
671 the end: both a*? and ?a* are equivalent to '%psearch a*'.
672
673 PATTERN
674
675 where PATTERN is a string containing * as a wildcard similar to its
676 use in a shell. The pattern is matched in all namespaces on the
677 search path. By default objects starting with a single _ are not
678 matched, many IPython generated objects have a single underscore. The
679 default is case insensitive matching. Matching is also done on the
680 attributes of objects and not only on the objects in a module.
681
682 [OBJECT TYPE]
683 Is the name of a python type from the types module. The name is given
684 in lowercase without the ending type, ex. StringType is written
685 string. By adding a type here only objects matching the given type are
686 matched. Using all here makes the pattern match all types (this is the
687 default).
688
689 [-NAMESPACE]* [+NAMESPACE]*
690 The possible namespaces are builtin, user, internal, alias. Where
691 builtin and user are default. Builtin contains the python module
692 builtin, user contains all imported namespaces, alias only contain the
693 shell aliases and no python objects, internal contains objects used by
694 IPython. The namespaces on the search path are removed by -namespace
695 and added by +namespace.
696
697 [-a] makes the pattern match even objects with a single underscore.
698 [-c] makes the pattern case sensitive.
670 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
671 rest of the command line must be unchanged (options come first), so
672 for example the following forms are equivalent
673
674 %psearch -i a* function
675 -i a* function?
676 ?-i a* function
677
678 Arguments:
679
680 PATTERN
681
682 where PATTERN is a string containing * as a wildcard similar to its
683 use in a shell. The pattern is matched in all namespaces on the
684 search path. By default objects starting with a single _ are not
685 matched, many IPython generated objects have a single
686 underscore. The default is case insensitive matching. Matching is
687 also done on the attributes of objects and not only on the objects
688 in a module.
689
690 [OBJECT TYPE]
691
692 Is the name of a python type from the types module. The name is
693 given in lowercase without the ending type, ex. StringType is
694 written string. By adding a type here only objects matching the
695 given type are matched. Using all here makes the pattern match all
696 types (this is the default).
697
698 Options:
699
700 -a: makes the pattern match even objects whose names start with a
701 single underscore. These names are normally ommitted from the
702 search.
703
704 -i/-c: make the pattern case insensitive/sensitive. If neither of
705 these options is given, the default is read from your ipythonrc
706 file. The option name which sets this value is
707 'wildcards_case_sensitive'. If this option is not specified in your
708 ipythonrc file, IPython's internal default is to do a case sensitive
709 search.
710
711 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
712 specifiy can be searched in any of the following namespaces:
713 'builtin', 'user', 'user_global','internal', 'alias', where
714 'builtin' and 'user' are the search defaults. Note that you should
715 not use quotes when specifying namespaces.
716
717 'Builtin' contains the python module builtin, 'user' contains all
718 user data, 'alias' only contain the shell aliases and no python
719 objects, 'internal' contains objects used by IPython. The
720 'user_global' namespace is only used by embedded IPython instances,
721 and it contains module-level globals. You can add namespaces to the
722 search with -s or exclude them with -e (these options can be given
723 more than once).
699 724
700 725 Examples:
701 726
702 %psearch a* list objects beginning with an a
703 %psearch a* function list all functions beginning with an a
704 %psearch re.e* list objects beginning with an e in module re
705 %psearch r*.e* list objects that starts with e in modules starting in r
706 %psearch r*.* string list all strings in modules beginning with r
727 %psearch a* -> objects beginning with an a
728 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
729 %psearch a* function -> all functions beginning with an a
730 %psearch re.e* -> objects beginning with an e in module re
731 %psearch r*.e* -> objects that start with e in modules starting in r
732 %psearch r*.* string -> all strings in modules beginning with r
707 733
708 734 Case sensitve search:
709 735
710 %psearch a* -c list all object beginning with lower case a
736 %psearch -c a* list all object beginning with lower case a
711 737
712 738 Show objects beginning with a single _:
713 739
714 %psearch _* -a list objects beginning with underscore"""
740 %psearch -a _* list objects beginning with a single underscore"""
741
742 # default namespaces to be searched
743 def_search = ['user','builtin']
744
745 # Process options/args
746 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
747 opt = opts.get
748 shell = self.shell
749 psearch = shell.inspector.psearch
715 750
716 self.shell.inspector.psearch(parameter_s,shell=self.shell)
751 # select case options
752 if opts.has_key('i'):
753 ignore_case = True
754 elif opts.has_key('c'):
755 ignore_case = False
756 else:
757 ignore_case = not shell.rc.wildcards_case_sensitive
758
759 # Build list of namespaces to search from user options
760 def_search.extend(opt('s',[]))
761 ns_exclude = ns_exclude=opt('e',[])
762 ns_search = [nm for nm in def_search if nm not in ns_exclude]
763
764 # Call the actual search
765 try:
766 psearch(args,shell.ns_table,ns_search,
767 show_all=opt('a'),ignore_case=ignore_case)
768 except:
769 shell.showtraceback()
717 770
718 771 def magic_who_ls(self, parameter_s=''):
719 772 """Return a sorted list of all interactive variables.
720 773
721 774 If arguments are given, only variables of types matching these
722 775 arguments are returned."""
723 776
724 777 user_ns = self.shell.user_ns
725 778 out = []
726 779 typelist = parameter_s.split()
727 780 for i in self.shell.user_ns.keys():
728 781 if not (i.startswith('_') or i.startswith('_i')) \
729 782 and not (self.internal_ns.has_key(i) or
730 783 self.user_config_ns.has_key(i)):
731 784 if typelist:
732 785 if type(user_ns[i]).__name__ in typelist:
733 786 out.append(i)
734 787 else:
735 788 out.append(i)
736 789 out.sort()
737 790 return out
738 791
739 792 def magic_who(self, parameter_s=''):
740 793 """Print all interactive variables, with some minimal formatting.
741 794
742 795 If any arguments are given, only variables whose type matches one of
743 796 these are printed. For example:
744 797
745 798 %who function str
746 799
747 800 will only list functions and strings, excluding all other types of
748 801 variables. To find the proper type names, simply use type(var) at a
749 802 command line to see how python prints type names. For example:
750 803
751 804 In [1]: type('hello')\\
752 805 Out[1]: <type 'str'>
753 806
754 807 indicates that the type name for strings is 'str'.
755 808
756 809 %who always excludes executed names loaded through your configuration
757 810 file and things which are internal to IPython.
758 811
759 812 This is deliberate, as typically you may load many modules and the
760 813 purpose of %who is to show you only what you've manually defined."""
761 814
762 815 varlist = self.magic_who_ls(parameter_s)
763 816 if not varlist:
764 817 print 'Interactive namespace is empty.'
765 818 return
766 819
767 820 # if we have variables, move on...
768 821
769 822 # stupid flushing problem: when prompts have no separators, stdout is
770 823 # getting lost. I'm starting to think this is a python bug. I'm having
771 824 # to force a flush with a print because even a sys.stdout.flush
772 825 # doesn't seem to do anything!
773 826
774 827 count = 0
775 828 for i in varlist:
776 829 print i+'\t',
777 830 count += 1
778 831 if count > 8:
779 832 count = 0
780 833 print
781 834 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
782 835
783 836 print # well, this does force a flush at the expense of an extra \n
784 837
785 838 def magic_whos(self, parameter_s=''):
786 839 """Like %who, but gives some extra information about each variable.
787 840
788 841 The same type filtering of %who can be applied here.
789 842
790 843 For all variables, the type is printed. Additionally it prints:
791 844
792 845 - For {},[],(): their length.
793 846
794 847 - For Numeric arrays, a summary with shape, number of elements,
795 848 typecode and size in memory.
796 849
797 850 - Everything else: a string representation, snipping their middle if
798 851 too long."""
799 852
800 853 varnames = self.magic_who_ls(parameter_s)
801 854 if not varnames:
802 855 print 'Interactive namespace is empty.'
803 856 return
804 857
805 858 # if we have variables, move on...
806 859
807 860 # for these types, show len() instead of data:
808 861 seq_types = [types.DictType,types.ListType,types.TupleType]
809 862
810 863 # for Numeric arrays, display summary info
811 864 try:
812 865 import Numeric
813 866 except ImportError:
814 867 array_type = None
815 868 else:
816 869 array_type = Numeric.ArrayType.__name__
817 870
818 871 # Find all variable names and types so we can figure out column sizes
819 872 get_vars = lambda i: self.shell.user_ns[i]
820 873 type_name = lambda v: type(v).__name__
821 874 varlist = map(get_vars,varnames)
822 875 typelist = map(type_name,varlist)
823 876 # column labels and # of spaces as separator
824 877 varlabel = 'Variable'
825 878 typelabel = 'Type'
826 879 datalabel = 'Data/Info'
827 880 colsep = 3
828 881 # variable format strings
829 882 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
830 883 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
831 884 aformat = "%s: %s elems, type `%s`, %s bytes"
832 885 # find the size of the columns to format the output nicely
833 886 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
834 887 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
835 888 # table header
836 889 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
837 890 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
838 891 # and the table itself
839 892 kb = 1024
840 893 Mb = 1048576 # kb**2
841 894 for vname,var,vtype in zip(varnames,varlist,typelist):
842 895 print itpl(vformat),
843 896 if vtype in seq_types:
844 897 print len(var)
845 898 elif vtype==array_type:
846 899 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
847 900 vsize = Numeric.size(var)
848 901 vbytes = vsize*var.itemsize()
849 902 if vbytes < 100000:
850 903 print aformat % (vshape,vsize,var.typecode(),vbytes)
851 904 else:
852 905 print aformat % (vshape,vsize,var.typecode(),vbytes),
853 906 if vbytes < Mb:
854 907 print '(%s kb)' % (vbytes/kb,)
855 908 else:
856 909 print '(%s Mb)' % (vbytes/Mb,)
857 910 else:
858 911 vstr = str(var)
859 912 if len(vstr) < 50:
860 913 print vstr
861 914 else:
862 915 printpl(vfmt_short)
863 916
864 917 def magic_reset(self, parameter_s=''):
865 918 """Resets the namespace by removing all names defined by the user.
866 919
867 920 Input/Output history are left around in case you need them."""
868 921
869 922 ans = raw_input(
870 923 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
871 924 if not ans.lower() == 'y':
872 925 print 'Nothing done.'
873 926 return
874 927 user_ns = self.shell.user_ns
875 928 for i in self.magic_who_ls():
876 929 del(user_ns[i])
877 930
878 931 def magic_config(self,parameter_s=''):
879 932 """Show IPython's internal configuration."""
880 933
881 934 page('Current configuration structure:\n'+
882 935 pformat(self.shell.rc.dict()))
883 936
884 937 def magic_logstart(self,parameter_s=''):
885 938 """Start logging anywhere in a session.
886 939
887 940 %logstart [log_name [log_mode]]
888 941
889 942 If no name is given, it defaults to a file named 'ipython.log' in your
890 943 current directory, in 'rotate' mode (see below).
891 944
892 945 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
893 946 history up to that point and then continues logging.
894 947
895 948 %logstart takes a second optional parameter: logging mode. This can be one
896 949 of (note that the modes are given unquoted):\\
897 950 over: overwrite existing log.\\
898 951 backup: rename (if exists) to name~ and start name.\\
899 952 append: well, that says it.\\
900 953 rotate: create rotating logs name.1~, name.2~, etc.
901 954 """
902 955
903 956 #FIXME. This function should all be moved to the Logger class.
904 957
905 958 valid_modes = qw('over backup append rotate')
906 959 if self.LOG:
907 960 print 'Logging is already in place. Logfile:',self.LOG
908 961 return
909 962
910 963 par = parameter_s.strip()
911 964 if not par:
912 965 logname = self.LOGDEF
913 966 logmode = 'rotate' # use rotate for the auto-generated logs
914 967 else:
915 968 try:
916 969 logname,logmode = par.split()
917 970 except:
918 971 try:
919 972 logname = par
920 973 logmode = 'backup'
921 974 except:
922 975 warn('Usage: %log [log_name [log_mode]]')
923 976 return
924 977 if not logmode in valid_modes:
925 978 warn('Logging NOT activated.\n'
926 979 'Usage: %log [log_name [log_mode]]\n'
927 980 'Valid modes: '+str(valid_modes))
928 981 return
929 982
930 983 # If we made it this far, I think we're ok:
931 984 print 'Activating auto-logging.'
932 985 print 'Current session state plus future input saved to:',logname
933 986 print 'Logging mode: ',logmode
934 987 # put logname into rc struct as if it had been called on the command line,
935 988 # so it ends up saved in the log header
936 989 # Save it in case we need to restore it...
937 990 old_logfile = self.shell.rc.opts.get('logfile','')
938 991 logname = os.path.expanduser(logname)
939 992 self.shell.rc.opts.logfile = logname
940 993 self.LOGMODE = logmode # FIXME: this should be set through a function.
941 994 try:
942 995 header = str(self.LOGHEAD)
943 996 self.create_log(header,logname)
944 997 self.logstart(header,logname)
945 998 except:
946 999 self.LOG = '' # we are NOT logging, something went wrong
947 1000 self.shell.rc.opts.logfile = old_logfile
948 1001 warn("Couldn't start log: "+str(sys.exc_info()[1]))
949 1002 else: # log input history up to this point
950 1003 self.logfile.write(self.shell.user_ns['_ih'][1:])
951 1004 self.logfile.flush()
952 1005
953 1006 def magic_logoff(self,parameter_s=''):
954 1007 """Temporarily stop logging.
955 1008
956 1009 You must have previously started logging."""
957 1010 self.switch_log(0)
958 1011
959 1012 def magic_logon(self,parameter_s=''):
960 1013 """Restart logging.
961 1014
962 1015 This function is for restarting logging which you've temporarily
963 1016 stopped with %logoff. For starting logging for the first time, you
964 1017 must use the %logstart function, which allows you to specify an
965 1018 optional log filename."""
966 1019
967 1020 self.switch_log(1)
968 1021
969 1022 def magic_logstate(self,parameter_s=''):
970 1023 """Print the status of the logging system."""
971 1024
972 1025 self.logstate()
973 1026
974 1027 def magic_pdb(self, parameter_s=''):
975 1028 """Control the calling of the pdb interactive debugger.
976 1029
977 1030 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
978 1031 argument it works as a toggle.
979 1032
980 1033 When an exception is triggered, IPython can optionally call the
981 1034 interactive pdb debugger after the traceback printout. %pdb toggles
982 1035 this feature on and off."""
983 1036
984 1037 par = parameter_s.strip().lower()
985 1038
986 1039 if par:
987 1040 try:
988 1041 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
989 1042 except KeyError:
990 1043 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
991 1044 return
992 1045 else:
993 1046 self.shell.InteractiveTB.call_pdb = pdb
994 1047 else:
995 1048 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
996 1049 print 'Automatic pdb calling has been turned',\
997 1050 on_off(self.shell.InteractiveTB.call_pdb)
998 1051
999 1052
1000 1053 def magic_prun(self, parameter_s ='',user_mode=1,
1001 1054 opts=None,arg_lst=None,prog_ns=None):
1002 1055
1003 1056 """Run a statement through the python code profiler.
1004 1057
1005 1058 Usage:\\
1006 1059 %prun [options] statement
1007 1060
1008 1061 The given statement (which doesn't require quote marks) is run via the
1009 1062 python profiler in a manner similar to the profile.run() function.
1010 1063 Namespaces are internally managed to work correctly; profile.run
1011 1064 cannot be used in IPython because it makes certain assumptions about
1012 1065 namespaces which do not hold under IPython.
1013 1066
1014 1067 Options:
1015 1068
1016 1069 -l <limit>: you can place restrictions on what or how much of the
1017 1070 profile gets printed. The limit value can be:
1018 1071
1019 1072 * A string: only information for function names containing this string
1020 1073 is printed.
1021 1074
1022 1075 * An integer: only these many lines are printed.
1023 1076
1024 1077 * A float (between 0 and 1): this fraction of the report is printed
1025 1078 (for example, use a limit of 0.4 to see the topmost 40% only).
1026 1079
1027 1080 You can combine several limits with repeated use of the option. For
1028 1081 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1029 1082 information about class constructors.
1030 1083
1031 1084 -r: return the pstats.Stats object generated by the profiling. This
1032 1085 object has all the information about the profile in it, and you can
1033 1086 later use it for further analysis or in other functions.
1034 1087
1035 1088 Since magic functions have a particular form of calling which prevents
1036 1089 you from writing something like:\\
1037 1090 In [1]: p = %prun -r print 4 # invalid!\\
1038 1091 you must instead use IPython's automatic variables to assign this:\\
1039 1092 In [1]: %prun -r print 4 \\
1040 1093 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1041 1094 In [2]: stats = _
1042 1095
1043 1096 If you really need to assign this value via an explicit function call,
1044 1097 you can always tap directly into the true name of the magic function
1045 1098 by using the ipmagic function (which IPython automatically adds to the
1046 1099 builtins):\\
1047 1100 In [3]: stats = ipmagic('prun','-r print 4')
1048 1101
1049 1102 You can type ipmagic? for more details on ipmagic.
1050 1103
1051 1104 -s <key>: sort profile by given key. You can provide more than one key
1052 1105 by using the option several times: '-s key1 -s key2 -s key3...'. The
1053 1106 default sorting key is 'time'.
1054 1107
1055 1108 The following is copied verbatim from the profile documentation
1056 1109 referenced below:
1057 1110
1058 1111 When more than one key is provided, additional keys are used as
1059 1112 secondary criteria when the there is equality in all keys selected
1060 1113 before them.
1061 1114
1062 1115 Abbreviations can be used for any key names, as long as the
1063 1116 abbreviation is unambiguous. The following are the keys currently
1064 1117 defined:
1065 1118
1066 1119 Valid Arg Meaning\\
1067 1120 "calls" call count\\
1068 1121 "cumulative" cumulative time\\
1069 1122 "file" file name\\
1070 1123 "module" file name\\
1071 1124 "pcalls" primitive call count\\
1072 1125 "line" line number\\
1073 1126 "name" function name\\
1074 1127 "nfl" name/file/line\\
1075 1128 "stdname" standard name\\
1076 1129 "time" internal time
1077 1130
1078 1131 Note that all sorts on statistics are in descending order (placing
1079 1132 most time consuming items first), where as name, file, and line number
1080 1133 searches are in ascending order (i.e., alphabetical). The subtle
1081 1134 distinction between "nfl" and "stdname" is that the standard name is a
1082 1135 sort of the name as printed, which means that the embedded line
1083 1136 numbers get compared in an odd way. For example, lines 3, 20, and 40
1084 1137 would (if the file names were the same) appear in the string order
1085 1138 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1086 1139 line numbers. In fact, sort_stats("nfl") is the same as
1087 1140 sort_stats("name", "file", "line").
1088 1141
1089 1142 -T <filename>: save profile results as shown on screen to a text
1090 1143 file. The profile is still shown on screen.
1091 1144
1092 1145 -D <filename>: save (via dump_stats) profile statistics to given
1093 1146 filename. This data is in a format understod by the pstats module, and
1094 1147 is generated by a call to the dump_stats() method of profile
1095 1148 objects. The profile is still shown on screen.
1096 1149
1097 1150 If you want to run complete programs under the profiler's control, use
1098 1151 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1099 1152 contains profiler specific options as described here.
1100 1153
1101 1154 You can read the complete documentation for the profile module with:\\
1102 1155 In [1]: import profile; profile.help() """
1103 1156
1104 1157 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1105 1158 # protect user quote marks
1106 1159 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1107 1160
1108 1161 if user_mode: # regular user call
1109 1162 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1110 1163 list_all=1)
1111 1164 namespace = self.shell.user_ns
1112 1165 else: # called to run a program by %run -p
1113 1166 try:
1114 1167 filename = get_py_filename(arg_lst[0])
1115 1168 except IOError,msg:
1116 1169 error(msg)
1117 1170 return
1118 1171
1119 1172 arg_str = 'execfile(filename,prog_ns)'
1120 1173 namespace = locals()
1121 1174
1122 1175 opts.merge(opts_def)
1123 1176
1124 1177 prof = profile.Profile()
1125 1178 try:
1126 1179 prof = prof.runctx(arg_str,namespace,namespace)
1127 1180 sys_exit = ''
1128 1181 except SystemExit:
1129 1182 sys_exit = """*** SystemExit exception caught in code being profiled."""
1130 1183
1131 1184 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1132 1185
1133 1186 lims = opts.l
1134 1187 if lims:
1135 1188 lims = [] # rebuild lims with ints/floats/strings
1136 1189 for lim in opts.l:
1137 1190 try:
1138 1191 lims.append(int(lim))
1139 1192 except ValueError:
1140 1193 try:
1141 1194 lims.append(float(lim))
1142 1195 except ValueError:
1143 1196 lims.append(lim)
1144 1197
1145 1198 # trap output
1146 1199 sys_stdout = sys.stdout
1147 1200 stdout_trap = StringIO()
1148 1201 try:
1149 1202 sys.stdout = stdout_trap
1150 1203 stats.print_stats(*lims)
1151 1204 finally:
1152 1205 sys.stdout = sys_stdout
1153 1206 output = stdout_trap.getvalue()
1154 1207 output = output.rstrip()
1155 1208
1156 1209 page(output,screen_lines=self.shell.rc.screen_length)
1157 1210 print sys_exit,
1158 1211
1159 1212 dump_file = opts.D[0]
1160 1213 text_file = opts.T[0]
1161 1214 if dump_file:
1162 1215 prof.dump_stats(dump_file)
1163 1216 print '\n*** Profile stats marshalled to file',\
1164 1217 `dump_file`+'.',sys_exit
1165 1218 if text_file:
1166 1219 file(text_file,'w').write(output)
1167 1220 print '\n*** Profile printout saved to text file',\
1168 1221 `text_file`+'.',sys_exit
1169 1222
1170 1223 if opts.has_key('r'):
1171 1224 return stats
1172 1225 else:
1173 1226 return None
1174 1227
1175 1228 def magic_run(self, parameter_s ='',runner=None):
1176 1229 """Run the named file inside IPython as a program.
1177 1230
1178 1231 Usage:\\
1179 1232 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1180 1233
1181 1234 Parameters after the filename are passed as command-line arguments to
1182 1235 the program (put in sys.argv). Then, control returns to IPython's
1183 1236 prompt.
1184 1237
1185 1238 This is similar to running at a system prompt:\\
1186 1239 $ python file args\\
1187 1240 but with the advantage of giving you IPython's tracebacks, and of
1188 1241 loading all variables into your interactive namespace for further use
1189 1242 (unless -p is used, see below).
1190 1243
1191 1244 The file is executed in a namespace initially consisting only of
1192 1245 __name__=='__main__' and sys.argv constructed as indicated. It thus
1193 1246 sees its environment as if it were being run as a stand-alone
1194 1247 program. But after execution, the IPython interactive namespace gets
1195 1248 updated with all variables defined in the program (except for __name__
1196 1249 and sys.argv). This allows for very convenient loading of code for
1197 1250 interactive work, while giving each program a 'clean sheet' to run in.
1198 1251
1199 1252 Options:
1200 1253
1201 1254 -n: __name__ is NOT set to '__main__', but to the running file's name
1202 1255 without extension (as python does under import). This allows running
1203 1256 scripts and reloading the definitions in them without calling code
1204 1257 protected by an ' if __name__ == "__main__" ' clause.
1205 1258
1206 1259 -i: run the file in IPython's namespace instead of an empty one. This
1207 1260 is useful if you are experimenting with code written in a text editor
1208 1261 which depends on variables defined interactively.
1209 1262
1210 1263 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1211 1264 being run. This is particularly useful if IPython is being used to
1212 1265 run unittests, which always exit with a sys.exit() call. In such
1213 1266 cases you are interested in the output of the test results, not in
1214 1267 seeing a traceback of the unittest module.
1215 1268
1216 1269 -t: print timing information at the end of the run. IPython will give
1217 1270 you an estimated CPU time consumption for your script, which under
1218 1271 Unix uses the resource module to avoid the wraparound problems of
1219 1272 time.clock(). Under Unix, an estimate of time spent on system tasks
1220 1273 is also given (for Windows platforms this is reported as 0.0).
1221 1274
1222 1275 If -t is given, an additional -N<N> option can be given, where <N>
1223 1276 must be an integer indicating how many times you want the script to
1224 1277 run. The final timing report will include total and per run results.
1225 1278
1226 1279 For example (testing the script uniq_stable.py):
1227 1280
1228 1281 In [1]: run -t uniq_stable
1229 1282
1230 1283 IPython CPU timings (estimated):\\
1231 1284 User : 0.19597 s.\\
1232 1285 System: 0.0 s.\\
1233 1286
1234 1287 In [2]: run -t -N5 uniq_stable
1235 1288
1236 1289 IPython CPU timings (estimated):\\
1237 1290 Total runs performed: 5\\
1238 1291 Times : Total Per run\\
1239 1292 User : 0.910862 s, 0.1821724 s.\\
1240 1293 System: 0.0 s, 0.0 s.
1241 1294
1242 1295 -d: run your program under the control of pdb, the Python debugger.
1243 1296 This allows you to execute your program step by step, watch variables,
1244 1297 etc. Internally, what IPython does is similar to calling:
1245 1298
1246 1299 pdb.run('execfile("YOURFILENAME")')
1247 1300
1248 1301 with a breakpoint set on line 1 of your file. You can change the line
1249 1302 number for this automatic breakpoint to be <N> by using the -bN option
1250 1303 (where N must be an integer). For example:
1251 1304
1252 1305 %run -d -b40 myscript
1253 1306
1254 1307 will set the first breakpoint at line 40 in myscript.py. Note that
1255 1308 the first breakpoint must be set on a line which actually does
1256 1309 something (not a comment or docstring) for it to stop execution.
1257 1310
1258 1311 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1259 1312 first enter 'c' (without qoutes) to start execution up to the first
1260 1313 breakpoint.
1261 1314
1262 1315 Entering 'help' gives information about the use of the debugger. You
1263 1316 can easily see pdb's full documentation with "import pdb;pdb.help()"
1264 1317 at a prompt.
1265 1318
1266 1319 -p: run program under the control of the Python profiler module (which
1267 1320 prints a detailed report of execution times, function calls, etc).
1268 1321
1269 1322 You can pass other options after -p which affect the behavior of the
1270 1323 profiler itself. See the docs for %prun for details.
1271 1324
1272 1325 In this mode, the program's variables do NOT propagate back to the
1273 1326 IPython interactive namespace (because they remain in the namespace
1274 1327 where the profiler executes them).
1275 1328
1276 1329 Internally this triggers a call to %prun, see its documentation for
1277 1330 details on the options available specifically for profiling."""
1278 1331
1279 1332 # get arguments and set sys.argv for program to be run.
1280 1333 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1281 1334 mode='list',list_all=1)
1282 1335
1283 1336 try:
1284 1337 filename = get_py_filename(arg_lst[0])
1285 1338 except IndexError:
1286 1339 warn('you must provide at least a filename.')
1287 1340 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1288 1341 return
1289 1342 except IOError,msg:
1290 1343 error(msg)
1291 1344 return
1292 1345
1293 1346 # Control the response to exit() calls made by the script being run
1294 1347 exit_ignore = opts.has_key('e')
1295 1348
1296 1349 # Make sure that the running script gets a proper sys.argv as if it
1297 1350 # were run from a system shell.
1298 1351 save_argv = sys.argv # save it for later restoring
1299 1352 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1300 1353
1301 1354 if opts.has_key('i'):
1302 1355 prog_ns = self.shell.user_ns
1303 1356 __name__save = self.shell.user_ns['__name__']
1304 1357 prog_ns['__name__'] = '__main__'
1305 1358 else:
1306 1359 if opts.has_key('n'):
1307 1360 name = os.path.splitext(os.path.basename(filename))[0]
1308 1361 else:
1309 1362 name = '__main__'
1310 1363 prog_ns = {'__name__':name}
1311 1364
1312 1365 # pickle fix. See iplib for an explanation
1313 1366 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1314 1367
1315 1368 stats = None
1316 1369 try:
1317 1370 if opts.has_key('p'):
1318 1371 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1319 1372 else:
1320 1373 if opts.has_key('d'):
1321 1374 deb = pdb.Pdb()
1322 1375 # reset Breakpoint state, which is moronically kept
1323 1376 # in a class
1324 1377 bdb.Breakpoint.next = 1
1325 1378 bdb.Breakpoint.bplist = {}
1326 1379 bdb.Breakpoint.bpbynumber = [None]
1327 1380 # Set an initial breakpoint to stop execution
1328 1381 maxtries = 10
1329 1382 bp = int(opts.get('b',[1])[0])
1330 1383 checkline = deb.checkline(filename,bp)
1331 1384 if not checkline:
1332 1385 for bp in range(bp+1,bp+maxtries+1):
1333 1386 if deb.checkline(filename,bp):
1334 1387 break
1335 1388 else:
1336 1389 msg = ("\nI failed to find a valid line to set "
1337 1390 "a breakpoint\n"
1338 1391 "after trying up to line: %s.\n"
1339 1392 "Please set a valid breakpoint manually "
1340 1393 "with the -b option." % bp)
1341 1394 error(msg)
1342 1395 return
1343 1396 # if we find a good linenumber, set the breakpoint
1344 1397 deb.do_break('%s:%s' % (filename,bp))
1345 1398 # Start file run
1346 1399 print "NOTE: Enter 'c' at the",
1347 1400 print "(Pdb) prompt to start your script."
1348 1401 deb.run('execfile("%s")' % filename,prog_ns)
1349 1402 else:
1350 1403 if runner is None:
1351 1404 runner = self.shell.safe_execfile
1352 1405 if opts.has_key('t'):
1353 1406 try:
1354 1407 nruns = int(opts['N'][0])
1355 1408 if nruns < 1:
1356 1409 error('Number of runs must be >=1')
1357 1410 return
1358 1411 except (KeyError):
1359 1412 nruns = 1
1360 1413 if nruns == 1:
1361 1414 t0 = clock2()
1362 1415 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1363 1416 t1 = clock2()
1364 1417 t_usr = t1[0]-t0[0]
1365 1418 t_sys = t1[1]-t1[1]
1366 1419 print "\nIPython CPU timings (estimated):"
1367 1420 print " User : %10s s." % t_usr
1368 1421 print " System: %10s s." % t_sys
1369 1422 else:
1370 1423 runs = range(nruns)
1371 1424 t0 = clock2()
1372 1425 for nr in runs:
1373 1426 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1374 1427 t1 = clock2()
1375 1428 t_usr = t1[0]-t0[0]
1376 1429 t_sys = t1[1]-t1[1]
1377 1430 print "\nIPython CPU timings (estimated):"
1378 1431 print "Total runs performed:",nruns
1379 1432 print " Times : %10s %10s" % ('Total','Per run')
1380 1433 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1381 1434 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1382 1435
1383 1436 else:
1384 1437 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1385 1438 if opts.has_key('i'):
1386 1439 self.shell.user_ns['__name__'] = __name__save
1387 1440 else:
1388 1441 # update IPython interactive namespace
1389 1442 del prog_ns['__name__']
1390 1443 self.shell.user_ns.update(prog_ns)
1391 1444 finally:
1392 1445 sys.argv = save_argv
1393 1446 return stats
1394 1447
1395 1448 def magic_runlog(self, parameter_s =''):
1396 1449 """Run files as logs.
1397 1450
1398 1451 Usage:\\
1399 1452 %runlog file1 file2 ...
1400 1453
1401 1454 Run the named files (treating them as log files) in sequence inside
1402 1455 the interpreter, and return to the prompt. This is much slower than
1403 1456 %run because each line is executed in a try/except block, but it
1404 1457 allows running files with syntax errors in them.
1405 1458
1406 1459 Normally IPython will guess when a file is one of its own logfiles, so
1407 1460 you can typically use %run even for logs. This shorthand allows you to
1408 1461 force any file to be treated as a log file."""
1409 1462
1410 1463 for f in parameter_s.split():
1411 1464 self.shell.safe_execfile(f,self.shell.user_ns,
1412 1465 self.shell.user_ns,islog=1)
1413 1466
1414 1467 def magic_time(self,parameter_s = ''):
1415 1468 """Time execution of a Python statement or expression.
1416 1469
1417 1470 The CPU and wall clock times are printed, and the value of the
1418 1471 expression (if any) is returned. Note that under Win32, system time
1419 1472 is always reported as 0, since it can not be measured.
1420 1473
1421 1474 This function provides very basic timing functionality. In Python
1422 1475 2.3, the timeit module offers more control and sophistication, but for
1423 1476 now IPython supports Python 2.2, so we can not rely on timeit being
1424 1477 present.
1425 1478
1426 1479 Some examples:
1427 1480
1428 1481 In [1]: time 2**128
1429 1482 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1430 1483 Wall time: 0.00
1431 1484 Out[1]: 340282366920938463463374607431768211456L
1432 1485
1433 1486 In [2]: n = 1000000
1434 1487
1435 1488 In [3]: time sum(range(n))
1436 1489 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1437 1490 Wall time: 1.37
1438 1491 Out[3]: 499999500000L
1439 1492
1440 1493 In [4]: time print 'hello world'
1441 1494 hello world
1442 1495 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1443 1496 Wall time: 0.00
1444 1497 """
1445 1498
1446 1499 # fail immediately if the given expression can't be compiled
1447 1500 try:
1448 1501 mode = 'eval'
1449 1502 code = compile(parameter_s,'<timed eval>',mode)
1450 1503 except SyntaxError:
1451 1504 mode = 'exec'
1452 1505 code = compile(parameter_s,'<timed exec>',mode)
1453 1506 # skew measurement as little as possible
1454 1507 glob = self.shell.user_ns
1455 1508 clk = clock2
1456 1509 wtime = time.time
1457 1510 # time execution
1458 1511 wall_st = wtime()
1459 1512 if mode=='eval':
1460 1513 st = clk()
1461 1514 out = eval(code,glob)
1462 1515 end = clk()
1463 1516 else:
1464 1517 st = clk()
1465 1518 exec code in glob
1466 1519 end = clk()
1467 1520 out = None
1468 1521 wall_end = wtime()
1469 1522 # Compute actual times and report
1470 1523 wall_time = wall_end-wall_st
1471 1524 cpu_user = end[0]-st[0]
1472 1525 cpu_sys = end[1]-st[1]
1473 1526 cpu_tot = cpu_user+cpu_sys
1474 1527 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1475 1528 (cpu_user,cpu_sys,cpu_tot)
1476 1529 print "Wall time: %.2f" % wall_time
1477 1530 return out
1478 1531
1479 1532 def magic_macro(self,parameter_s = ''):
1480 1533 """Define a set of input lines as a macro for future re-execution.
1481 1534
1482 1535 Usage:\\
1483 1536 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1484 1537
1485 1538 This will define a global variable called `name` which is a string
1486 1539 made of joining the slices and lines you specify (n1,n2,... numbers
1487 1540 above) from your input history into a single string. This variable
1488 1541 acts like an automatic function which re-executes those lines as if
1489 1542 you had typed them. You just type 'name' at the prompt and the code
1490 1543 executes.
1491 1544
1492 1545 Note that the slices use the standard Python slicing notation (5:8
1493 1546 means include lines numbered 5,6,7).
1494 1547
1495 1548 For example, if your history contains (%hist prints it):
1496 1549
1497 1550 44: x=1\\
1498 1551 45: y=3\\
1499 1552 46: z=x+y\\
1500 1553 47: print x\\
1501 1554 48: a=5\\
1502 1555 49: print 'x',x,'y',y\\
1503 1556
1504 1557 you can create a macro with lines 44 through 47 (included) and line 49
1505 1558 called my_macro with:
1506 1559
1507 1560 In [51]: %macro my_macro 44:48 49
1508 1561
1509 1562 Now, typing `my_macro` (without quotes) will re-execute all this code
1510 1563 in one pass.
1511 1564
1512 1565 You don't need to give the line-numbers in order, and any given line
1513 1566 number can appear multiple times. You can assemble macros with any
1514 1567 lines from your input history in any order.
1515 1568
1516 1569 The macro is a simple object which holds its value in an attribute,
1517 1570 but IPython's display system checks for macros and executes them as
1518 1571 code instead of printing them when you type their name.
1519 1572
1520 1573 You can view a macro's contents by explicitly printing it with:
1521 1574
1522 1575 'print macro_name'.
1523 1576
1524 1577 For one-off cases which DON'T contain magic function calls in them you
1525 1578 can obtain similar results by explicitly executing slices from your
1526 1579 input history with:
1527 1580
1528 1581 In [60]: exec In[44:48]+In[49]"""
1529 1582
1530 1583 args = parameter_s.split()
1531 1584 name,ranges = args[0], args[1:]
1532 1585 #print 'rng',ranges # dbg
1533 1586 cmds = self.extract_input_slices(ranges)
1534 1587 macro = Macro(cmds)
1535 1588 self.shell.user_ns.update({name:macro})
1536 1589 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1537 1590 print 'Macro contents:'
1538 1591 print str(macro).rstrip(),
1539 1592
1540 1593 def magic_save(self,parameter_s = ''):
1541 1594 """Save a set of lines to a given filename.
1542 1595
1543 1596 Usage:\\
1544 1597 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1545 1598
1546 1599 This function uses the same syntax as %macro for line extraction, but
1547 1600 instead of creating a macro it saves the resulting string to the
1548 1601 filename you specify.
1549 1602
1550 1603 It adds a '.py' extension to the file if you don't do so yourself, and
1551 1604 it asks for confirmation before overwriting existing files."""
1552 1605
1553 1606 args = parameter_s.split()
1554 1607 fname,ranges = args[0], args[1:]
1555 1608 if not fname.endswith('.py'):
1556 1609 fname += '.py'
1557 1610 if os.path.isfile(fname):
1558 1611 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1559 1612 if ans.lower() not in ['y','yes']:
1560 1613 print 'Operation cancelled.'
1561 1614 return
1562 1615 cmds = ''.join(self.extract_input_slices(ranges))
1563 1616 f = file(fname,'w')
1564 1617 f.write(cmds)
1565 1618 f.close()
1566 1619 print 'The following commands were written to file `%s`:' % fname
1567 1620 print cmds
1568 1621
1569 1622 def magic_ed(self,parameter_s = ''):
1570 1623 """Alias to %edit."""
1571 1624 return self.magic_edit(parameter_s)
1572 1625
1573 1626 def magic_edit(self,parameter_s = '',last_call=['','']):
1574 1627 """Bring up an editor and execute the resulting code.
1575 1628
1576 1629 Usage:
1577 1630 %edit [options] [args]
1578 1631
1579 1632 %edit runs IPython's editor hook. The default version of this hook is
1580 1633 set to call the __IPYTHON__.rc.editor command. This is read from your
1581 1634 environment variable $EDITOR. If this isn't found, it will default to
1582 1635 vi under Linux/Unix and to notepad under Windows. See the end of this
1583 1636 docstring for how to change the editor hook.
1584 1637
1585 1638 You can also set the value of this editor via the command line option
1586 1639 '-editor' or in your ipythonrc file. This is useful if you wish to use
1587 1640 specifically for IPython an editor different from your typical default
1588 1641 (and for Windows users who typically don't set environment variables).
1589 1642
1590 1643 This command allows you to conveniently edit multi-line code right in
1591 1644 your IPython session.
1592 1645
1593 1646 If called without arguments, %edit opens up an empty editor with a
1594 1647 temporary file and will execute the contents of this file when you
1595 1648 close it (don't forget to save it!).
1596 1649
1597 1650 Options:
1598 1651
1599 1652 -p: this will call the editor with the same data as the previous time
1600 1653 it was used, regardless of how long ago (in your current session) it
1601 1654 was.
1602 1655
1603 1656 -x: do not execute the edited code immediately upon exit. This is
1604 1657 mainly useful if you are editing programs which need to be called with
1605 1658 command line arguments, which you can then do using %run.
1606 1659
1607 1660 Arguments:
1608 1661
1609 1662 If arguments are given, the following possibilites exist:
1610 1663
1611 1664 - The arguments are numbers or pairs of colon-separated numbers (like
1612 1665 1 4:8 9). These are interpreted as lines of previous input to be
1613 1666 loaded into the editor. The syntax is the same of the %macro command.
1614 1667
1615 1668 - If the argument doesn't start with a number, it is evaluated as a
1616 1669 variable and its contents loaded into the editor. You can thus edit
1617 1670 any string which contains python code (including the result of
1618 1671 previous edits).
1619 1672
1620 1673 - If the argument is the name of an object (other than a string),
1621 1674 IPython will try to locate the file where it was defined and open the
1622 1675 editor at the point where it is defined. You can use `%edit function`
1623 1676 to load an editor exactly at the point where 'function' is defined,
1624 1677 edit it and have the file be executed automatically.
1625 1678
1626 1679 Note: opening at an exact line is only supported under Unix, and some
1627 1680 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1628 1681 '+NUMBER' parameter necessary for this feature. Good editors like
1629 1682 (X)Emacs, vi, jed, pico and joe all do.
1630 1683
1631 1684 - If the argument is not found as a variable, IPython will look for a
1632 1685 file with that name (adding .py if necessary) and load it into the
1633 1686 editor. It will execute its contents with execfile() when you exit,
1634 1687 loading any code in the file into your interactive namespace.
1635 1688
1636 1689 After executing your code, %edit will return as output the code you
1637 1690 typed in the editor (except when it was an existing file). This way
1638 1691 you can reload the code in further invocations of %edit as a variable,
1639 1692 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1640 1693 the output.
1641 1694
1642 1695 Note that %edit is also available through the alias %ed.
1643 1696
1644 1697 This is an example of creating a simple function inside the editor and
1645 1698 then modifying it. First, start up the editor:
1646 1699
1647 1700 In [1]: ed\\
1648 1701 Editing... done. Executing edited code...\\
1649 1702 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1650 1703
1651 1704 We can then call the function foo():
1652 1705
1653 1706 In [2]: foo()\\
1654 1707 foo() was defined in an editing session
1655 1708
1656 1709 Now we edit foo. IPython automatically loads the editor with the
1657 1710 (temporary) file where foo() was previously defined:
1658 1711
1659 1712 In [3]: ed foo\\
1660 1713 Editing... done. Executing edited code...
1661 1714
1662 1715 And if we call foo() again we get the modified version:
1663 1716
1664 1717 In [4]: foo()\\
1665 1718 foo() has now been changed!
1666 1719
1667 1720 Here is an example of how to edit a code snippet successive
1668 1721 times. First we call the editor:
1669 1722
1670 1723 In [8]: ed\\
1671 1724 Editing... done. Executing edited code...\\
1672 1725 hello\\
1673 1726 Out[8]: "print 'hello'\\n"
1674 1727
1675 1728 Now we call it again with the previous output (stored in _):
1676 1729
1677 1730 In [9]: ed _\\
1678 1731 Editing... done. Executing edited code...\\
1679 1732 hello world\\
1680 1733 Out[9]: "print 'hello world'\\n"
1681 1734
1682 1735 Now we call it with the output #8 (stored in _8, also as Out[8]):
1683 1736
1684 1737 In [10]: ed _8\\
1685 1738 Editing... done. Executing edited code...\\
1686 1739 hello again\\
1687 1740 Out[10]: "print 'hello again'\\n"
1688 1741
1689 1742
1690 1743 Changing the default editor hook:
1691 1744
1692 1745 If you wish to write your own editor hook, you can put it in a
1693 1746 configuration file which you load at startup time. The default hook
1694 1747 is defined in the IPython.hooks module, and you can use that as a
1695 1748 starting example for further modifications. That file also has
1696 1749 general instructions on how to set a new hook for use once you've
1697 1750 defined it."""
1698 1751
1699 1752 # FIXME: This function has become a convoluted mess. It needs a
1700 1753 # ground-up rewrite with clean, simple logic.
1701 1754
1702 1755 def make_filename(arg):
1703 1756 "Make a filename from the given args"
1704 1757 try:
1705 1758 filename = get_py_filename(arg)
1706 1759 except IOError:
1707 1760 if args.endswith('.py'):
1708 1761 filename = arg
1709 1762 else:
1710 1763 filename = None
1711 1764 return filename
1712 1765
1713 1766 # custom exceptions
1714 1767 class DataIsObject(Exception): pass
1715 1768
1716 1769 opts,args = self.parse_options(parameter_s,'px')
1717 1770
1718 1771 # Default line number value
1719 1772 lineno = None
1720 1773 if opts.has_key('p'):
1721 1774 args = '_%s' % last_call[0]
1722 1775 if not self.shell.user_ns.has_key(args):
1723 1776 args = last_call[1]
1724 1777
1725 1778 # use last_call to remember the state of the previous call, but don't
1726 1779 # let it be clobbered by successive '-p' calls.
1727 1780 try:
1728 1781 last_call[0] = self.shell.outputcache.prompt_count
1729 1782 if not opts.has_key('p'):
1730 1783 last_call[1] = parameter_s
1731 1784 except:
1732 1785 pass
1733 1786
1734 1787 # by default this is done with temp files, except when the given
1735 1788 # arg is a filename
1736 1789 use_temp = 1
1737 1790
1738 1791 if re.match(r'\d',args):
1739 1792 # Mode where user specifies ranges of lines, like in %macro.
1740 1793 # This means that you can't edit files whose names begin with
1741 1794 # numbers this way. Tough.
1742 1795 ranges = args.split()
1743 1796 data = ''.join(self.extract_input_slices(ranges))
1744 1797 elif args.endswith('.py'):
1745 1798 filename = make_filename(args)
1746 1799 data = ''
1747 1800 use_temp = 0
1748 1801 elif args:
1749 1802 try:
1750 1803 # Load the parameter given as a variable. If not a string,
1751 1804 # process it as an object instead (below)
1752 1805
1753 1806 #print '*** args',args,'type',type(args) # dbg
1754 1807 data = eval(args,self.shell.user_ns)
1755 1808 if not type(data) in StringTypes:
1756 1809 raise DataIsObject
1757 1810 except (NameError,SyntaxError):
1758 1811 # given argument is not a variable, try as a filename
1759 1812 filename = make_filename(args)
1760 1813 if filename is None:
1761 1814 warn("Argument given (%s) can't be found as a variable "
1762 1815 "or as a filename." % args)
1763 1816 return
1764 1817 data = ''
1765 1818 use_temp = 0
1766 1819 except DataIsObject:
1767 1820 # For objects, try to edit the file where they are defined
1768 1821 try:
1769 1822 filename = inspect.getabsfile(data)
1770 1823 datafile = 1
1771 1824 except TypeError:
1772 1825 filename = make_filename(args)
1773 1826 datafile = 1
1774 1827 warn('Could not find file where `%s` is defined.\n'
1775 1828 'Opening a file named `%s`' % (args,filename))
1776 1829 # Now, make sure we can actually read the source (if it was in
1777 1830 # a temp file it's gone by now).
1778 1831 if datafile:
1779 1832 try:
1780 1833 lineno = inspect.getsourcelines(data)[1]
1781 1834 except IOError:
1782 1835 filename = make_filename(args)
1783 1836 if filename is None:
1784 1837 warn('The file `%s` where `%s` was defined cannot '
1785 1838 'be read.' % (filename,data))
1786 1839 return
1787 1840 use_temp = 0
1788 1841 else:
1789 1842 data = ''
1790 1843
1791 1844 if use_temp:
1792 1845 filename = tempfile.mktemp('.py')
1793 1846 self.shell.tempfiles.append(filename)
1794 1847
1795 1848 if data and use_temp:
1796 1849 tmp_file = open(filename,'w')
1797 1850 tmp_file.write(data)
1798 1851 tmp_file.close()
1799 1852
1800 1853 # do actual editing here
1801 1854 print 'Editing...',
1802 1855 sys.stdout.flush()
1803 1856 self.shell.hooks.editor(filename,lineno)
1804 1857 if opts.has_key('x'): # -x prevents actual execution
1805 1858 print
1806 1859 else:
1807 1860 print 'done. Executing edited code...'
1808 1861 try:
1809 1862 execfile(filename,self.shell.user_ns)
1810 1863 except IOError,msg:
1811 1864 if msg.filename == filename:
1812 1865 warn('File not found. Did you forget to save?')
1813 1866 return
1814 1867 else:
1815 1868 self.shell.showtraceback()
1816 1869 except:
1817 1870 self.shell.showtraceback()
1818 1871 if use_temp:
1819 1872 contents = open(filename).read()
1820 1873 return contents
1821 1874
1822 1875 def magic_xmode(self,parameter_s = ''):
1823 1876 """Switch modes for the exception handlers.
1824 1877
1825 1878 Valid modes: Plain, Context and Verbose.
1826 1879
1827 1880 If called without arguments, acts as a toggle."""
1828 1881
1829 1882 new_mode = parameter_s.strip().capitalize()
1830 1883 try:
1831 1884 self.InteractiveTB.set_mode(mode = new_mode)
1832 1885 print 'Exception reporting mode:',self.InteractiveTB.mode
1833 1886 except:
1834 1887 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1835 1888
1836 1889 def magic_colors(self,parameter_s = ''):
1837 1890 """Switch color scheme for prompts, info system and exception handlers.
1838 1891
1839 1892 Currently implemented schemes: NoColor, Linux, LightBG.
1840 1893
1841 1894 Color scheme names are not case-sensitive."""
1842 1895
1843 1896 new_scheme = parameter_s.strip()
1844 1897 if not new_scheme:
1845 1898 print 'You must specify a color scheme.'
1846 1899 return
1847 1900 # Under Windows, check for Gary Bishop's readline, which is necessary
1848 1901 # for ANSI coloring
1849 1902 if os.name in ['nt','dos']:
1850 1903 try:
1851 1904 import readline
1852 1905 except ImportError:
1853 1906 has_readline = 0
1854 1907 else:
1855 1908 try:
1856 1909 readline.GetOutputFile()
1857 1910 except AttributeError:
1858 1911 has_readline = 0
1859 1912 else:
1860 1913 has_readline = 1
1861 1914 if not has_readline:
1862 1915 msg = """\
1863 1916 Proper color support under MS Windows requires Gary Bishop's readline library.
1864 1917 You can find it at:
1865 1918 http://sourceforge.net/projects/uncpythontools
1866 1919 Gary's readline needs the ctypes module, from:
1867 1920 http://starship.python.net/crew/theller/ctypes
1868 1921
1869 1922 Defaulting color scheme to 'NoColor'"""
1870 1923 new_scheme = 'NoColor'
1871 1924 warn(msg)
1872 1925
1873 1926 # Set prompt colors
1874 1927 try:
1875 1928 self.shell.outputcache.set_colors(new_scheme)
1876 1929 except:
1877 1930 warn('Error changing prompt color schemes.\n'
1878 1931 + str(sys.exc_info()[1]))
1879 1932 else:
1880 1933 self.shell.rc.colors = \
1881 1934 self.shell.outputcache.color_table.active_scheme_name
1882 1935 # Set exception colors
1883 1936 try:
1884 1937 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1885 1938 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1886 1939 except:
1887 1940 warn('Error changing exception color schemes.\n'
1888 1941 + str(sys.exc_info()[1]))
1889 1942 # Set info (for 'object?') colors
1890 1943 if self.shell.rc.color_info:
1891 1944 try:
1892 1945 self.shell.inspector.set_active_scheme(new_scheme)
1893 1946 except:
1894 1947 warn('Error changing object inspector color schemes.\n'
1895 1948 + str(sys.exc_info()[1]))
1896 1949 else:
1897 1950 self.shell.inspector.set_active_scheme('NoColor')
1898 1951
1899 1952 def magic_color_info(self,parameter_s = ''):
1900 1953 """Toggle color_info.
1901 1954
1902 1955 The color_info configuration parameter controls whether colors are
1903 1956 used for displaying object details (by things like %psource, %pfile or
1904 1957 the '?' system). This function toggles this value with each call.
1905 1958
1906 1959 Note that unless you have a fairly recent pager (less works better
1907 1960 than more) in your system, using colored object information displays
1908 1961 will not work properly. Test it and see."""
1909 1962
1910 1963 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1911 1964 self.magic_colors(self.shell.rc.colors)
1912 1965 print 'Object introspection functions have now coloring:',
1913 1966 print ['OFF','ON'][self.shell.rc.color_info]
1914 1967
1915 1968 def magic_Pprint(self, parameter_s=''):
1916 1969 """Toggle pretty printing on/off."""
1917 1970
1918 1971 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1919 1972 print 'Pretty printing has been turned', \
1920 1973 ['OFF','ON'][self.shell.outputcache.Pprint]
1921 1974
1922 1975 def magic_Exit(self, parameter_s=''):
1923 1976 """Exit IPython without confirmation."""
1924 1977
1925 1978 self.shell.exit_now = True
1926 1979
1927 1980 def magic_Quit(self, parameter_s=''):
1928 1981 """Exit IPython without confirmation (like %Exit)."""
1929 1982
1930 1983 self.shell.exit_now = True
1931 1984
1932 1985 #......................................................................
1933 1986 # Functions to implement unix shell-type things
1934 1987
1935 1988 def magic_alias(self, parameter_s = ''):
1936 1989 """Define an alias for a system command.
1937 1990
1938 1991 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1939 1992
1940 1993 Then, typing 'alias_name params' will execute the system command 'cmd
1941 1994 params' (from your underlying operating system).
1942 1995
1943 1996 Aliases have lower precedence than magic functions and Python normal
1944 1997 variables, so if 'foo' is both a Python variable and an alias, the
1945 1998 alias can not be executed until 'del foo' removes the Python variable.
1946 1999
1947 2000 You can use the %l specifier in an alias definition to represent the
1948 2001 whole line when the alias is called. For example:
1949 2002
1950 2003 In [2]: alias all echo "Input in brackets: <%l>"\\
1951 2004 In [3]: all hello world\\
1952 2005 Input in brackets: <hello world>
1953 2006
1954 2007 You can also define aliases with parameters using %s specifiers (one
1955 2008 per parameter):
1956 2009
1957 2010 In [1]: alias parts echo first %s second %s\\
1958 2011 In [2]: %parts A B\\
1959 2012 first A second B\\
1960 2013 In [3]: %parts A\\
1961 2014 Incorrect number of arguments: 2 expected.\\
1962 2015 parts is an alias to: 'echo first %s second %s'
1963 2016
1964 2017 Note that %l and %s are mutually exclusive. You can only use one or
1965 2018 the other in your aliases.
1966 2019
1967 2020 Aliases expand Python variables just like system calls using ! or !!
1968 2021 do: all expressions prefixed with '$' get expanded. For details of
1969 2022 the semantic rules, see PEP-215:
1970 2023 http://www.python.org/peps/pep-0215.html. This is the library used by
1971 2024 IPython for variable expansion. If you want to access a true shell
1972 2025 variable, an extra $ is necessary to prevent its expansion by IPython:
1973 2026
1974 2027 In [6]: alias show echo\\
1975 2028 In [7]: PATH='A Python string'\\
1976 2029 In [8]: show $PATH\\
1977 2030 A Python string\\
1978 2031 In [9]: show $$PATH\\
1979 2032 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1980 2033
1981 2034 You can use the alias facility to acess all of $PATH. See the %rehash
1982 2035 and %rehashx functions, which automatically create aliases for the
1983 2036 contents of your $PATH.
1984 2037
1985 2038 If called with no parameters, %alias prints the current alias table."""
1986 2039
1987 2040 par = parameter_s.strip()
1988 2041 if not par:
1989 2042 if self.shell.rc.automagic:
1990 2043 prechar = ''
1991 2044 else:
1992 2045 prechar = self.shell.ESC_MAGIC
1993 2046 print 'Alias\t\tSystem Command\n'+'-'*30
1994 2047 atab = self.shell.alias_table
1995 2048 aliases = atab.keys()
1996 2049 aliases.sort()
1997 2050 for alias in aliases:
1998 2051 print prechar+alias+'\t\t'+atab[alias][1]
1999 2052 print '-'*30+'\nTotal number of aliases:',len(aliases)
2000 2053 return
2001 2054 try:
2002 2055 alias,cmd = par.split(None,1)
2003 2056 except:
2004 2057 print OInspect.getdoc(self.magic_alias)
2005 2058 else:
2006 2059 nargs = cmd.count('%s')
2007 2060 if nargs>0 and cmd.find('%l')>=0:
2008 2061 error('The %s and %l specifiers are mutually exclusive '
2009 2062 'in alias definitions.')
2010 2063 else: # all looks OK
2011 2064 self.shell.alias_table[alias] = (nargs,cmd)
2012 2065 self.shell.alias_table_validate(verbose=1)
2013 2066 # end magic_alias
2014 2067
2015 2068 def magic_unalias(self, parameter_s = ''):
2016 2069 """Remove an alias"""
2017 2070
2018 2071 aname = parameter_s.strip()
2019 2072 if aname in self.shell.alias_table:
2020 2073 del self.shell.alias_table[aname]
2021 2074
2022 2075 def magic_rehash(self, parameter_s = ''):
2023 2076 """Update the alias table with all entries in $PATH.
2024 2077
2025 2078 This version does no checks on execute permissions or whether the
2026 2079 contents of $PATH are truly files (instead of directories or something
2027 2080 else). For such a safer (but slower) version, use %rehashx."""
2028 2081
2029 2082 # This function (and rehashx) manipulate the alias_table directly
2030 2083 # rather than calling magic_alias, for speed reasons. A rehash on a
2031 2084 # typical Linux box involves several thousand entries, so efficiency
2032 2085 # here is a top concern.
2033 2086
2034 2087 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2035 2088 alias_table = self.shell.alias_table
2036 2089 for pdir in path:
2037 2090 for ff in os.listdir(pdir):
2038 2091 # each entry in the alias table must be (N,name), where
2039 2092 # N is the number of positional arguments of the alias.
2040 2093 alias_table[ff] = (0,ff)
2041 2094 # Make sure the alias table doesn't contain keywords or builtins
2042 2095 self.shell.alias_table_validate()
2043 2096 # Call again init_auto_alias() so we get 'rm -i' and other modified
2044 2097 # aliases since %rehash will probably clobber them
2045 2098 self.shell.init_auto_alias()
2046 2099
2047 2100 def magic_rehashx(self, parameter_s = ''):
2048 2101 """Update the alias table with all executable files in $PATH.
2049 2102
2050 2103 This version explicitly checks that every entry in $PATH is a file
2051 2104 with execute access (os.X_OK), so it is much slower than %rehash.
2052 2105
2053 2106 Under Windows, it checks executability as a match agains a
2054 2107 '|'-separated string of extensions, stored in the IPython config
2055 2108 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2056 2109
2057 2110 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2058 2111 alias_table = self.shell.alias_table
2059 2112
2060 2113 if os.name == 'posix':
2061 2114 isexec = lambda fname:os.path.isfile(fname) and \
2062 2115 os.access(fname,os.X_OK)
2063 2116 else:
2064 2117
2065 2118 try:
2066 2119 winext = os.environ['pathext'].replace(';','|').replace('.','')
2067 2120 except KeyError:
2068 2121 winext = 'exe|com|bat'
2069 2122
2070 2123 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2071 2124 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2072 2125 savedir = os.getcwd()
2073 2126 try:
2074 2127 # write the whole loop for posix/Windows so we don't have an if in
2075 2128 # the innermost part
2076 2129 if os.name == 'posix':
2077 2130 for pdir in path:
2078 2131 os.chdir(pdir)
2079 2132 for ff in os.listdir(pdir):
2080 2133 if isexec(ff):
2081 2134 # each entry in the alias table must be (N,name),
2082 2135 # where N is the number of positional arguments of the
2083 2136 # alias.
2084 2137 alias_table[ff] = (0,ff)
2085 2138 else:
2086 2139 for pdir in path:
2087 2140 os.chdir(pdir)
2088 2141 for ff in os.listdir(pdir):
2089 2142 if isexec(ff):
2090 2143 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2091 2144 # Make sure the alias table doesn't contain keywords or builtins
2092 2145 self.shell.alias_table_validate()
2093 2146 # Call again init_auto_alias() so we get 'rm -i' and other
2094 2147 # modified aliases since %rehashx will probably clobber them
2095 2148 self.shell.init_auto_alias()
2096 2149 finally:
2097 2150 os.chdir(savedir)
2098 2151
2099 2152 def magic_pwd(self, parameter_s = ''):
2100 2153 """Return the current working directory path."""
2101 2154 return os.getcwd()
2102 2155
2103 2156 def magic_cd(self, parameter_s=''):
2104 2157 """Change the current working directory.
2105 2158
2106 2159 This command automatically maintains an internal list of directories
2107 2160 you visit during your IPython session, in the variable _dh. The
2108 2161 command %dhist shows this history nicely formatted.
2109 2162
2110 2163 Usage:
2111 2164
2112 2165 cd 'dir': changes to directory 'dir'.
2113 2166
2114 2167 cd -: changes to the last visited directory.
2115 2168
2116 2169 cd -<n>: changes to the n-th directory in the directory history.
2117 2170
2118 2171 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2119 2172 (note: cd <bookmark_name> is enough if there is no
2120 2173 directory <bookmark_name>, but a bookmark with the name exists.)
2121 2174
2122 2175 Options:
2123 2176
2124 2177 -q: quiet. Do not print the working directory after the cd command is
2125 2178 executed. By default IPython's cd command does print this directory,
2126 2179 since the default prompts do not display path information.
2127 2180
2128 2181 Note that !cd doesn't work for this purpose because the shell where
2129 2182 !command runs is immediately discarded after executing 'command'."""
2130 2183
2131 2184 parameter_s = parameter_s.strip()
2132 2185 bkms = self.shell.persist.get("bookmarks",{})
2133 2186
2134 2187 numcd = re.match(r'(-)(\d+)$',parameter_s)
2135 2188 # jump in directory history by number
2136 2189 if numcd:
2137 2190 nn = int(numcd.group(2))
2138 2191 try:
2139 2192 ps = self.shell.user_ns['_dh'][nn]
2140 2193 except IndexError:
2141 2194 print 'The requested directory does not exist in history.'
2142 2195 return
2143 2196 else:
2144 2197 opts = {}
2145 2198 else:
2146 2199 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2147 2200 # jump to previous
2148 2201 if ps == '-':
2149 2202 try:
2150 2203 ps = self.shell.user_ns['_dh'][-2]
2151 2204 except IndexError:
2152 2205 print 'No previous directory to change to.'
2153 2206 return
2154 2207 # jump to bookmark
2155 2208 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2156 2209 if bkms.has_key(ps):
2157 2210 target = bkms[ps]
2158 2211 print '(bookmark:%s) -> %s' % (ps,target)
2159 2212 ps = target
2160 2213 else:
2161 2214 if bkms:
2162 2215 error("Bookmark '%s' not found. "
2163 2216 "Use '%bookmark -l' to see your bookmarks." % ps)
2164 2217 else:
2165 2218 print "Bookmarks not set - use %bookmark <bookmarkname>"
2166 2219 return
2167 2220
2168 2221 # at this point ps should point to the target dir
2169 2222 if ps:
2170 2223 try:
2171 2224 os.chdir(os.path.expanduser(ps))
2172 2225 except OSError:
2173 2226 print sys.exc_info()[1]
2174 2227 else:
2175 2228 self.shell.user_ns['_dh'].append(os.getcwd())
2176 2229 else:
2177 2230 os.chdir(self.home_dir)
2178 2231 self.shell.user_ns['_dh'].append(os.getcwd())
2179 2232 if not 'q' in opts:
2180 2233 print self.shell.user_ns['_dh'][-1]
2181 2234
2182 2235 def magic_dhist(self, parameter_s=''):
2183 2236 """Print your history of visited directories.
2184 2237
2185 2238 %dhist -> print full history\\
2186 2239 %dhist n -> print last n entries only\\
2187 2240 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2188 2241
2189 2242 This history is automatically maintained by the %cd command, and
2190 2243 always available as the global list variable _dh. You can use %cd -<n>
2191 2244 to go to directory number <n>."""
2192 2245
2193 2246 dh = self.shell.user_ns['_dh']
2194 2247 if parameter_s:
2195 2248 try:
2196 2249 args = map(int,parameter_s.split())
2197 2250 except:
2198 2251 self.arg_err(Magic.magic_dhist)
2199 2252 return
2200 2253 if len(args) == 1:
2201 2254 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2202 2255 elif len(args) == 2:
2203 2256 ini,fin = args
2204 2257 else:
2205 2258 self.arg_err(Magic.magic_dhist)
2206 2259 return
2207 2260 else:
2208 2261 ini,fin = 0,len(dh)
2209 2262 nlprint(dh,
2210 2263 header = 'Directory history (kept in _dh)',
2211 2264 start=ini,stop=fin)
2212 2265
2213 2266 def magic_env(self, parameter_s=''):
2214 2267 """List environment variables."""
2215 2268
2216 2269 # environ is an instance of UserDict
2217 2270 return os.environ.data
2218 2271
2219 2272 def magic_pushd(self, parameter_s=''):
2220 2273 """Place the current dir on stack and change directory.
2221 2274
2222 2275 Usage:\\
2223 2276 %pushd ['dirname']
2224 2277
2225 2278 %pushd with no arguments does a %pushd to your home directory.
2226 2279 """
2227 2280 if parameter_s == '': parameter_s = '~'
2228 2281 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2229 2282 os.path.expanduser(self.dir_stack[0]):
2230 2283 try:
2231 2284 self.magic_cd(parameter_s)
2232 2285 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2233 2286 self.magic_dirs()
2234 2287 except:
2235 2288 print 'Invalid directory'
2236 2289 else:
2237 2290 print 'You are already there!'
2238 2291
2239 2292 def magic_popd(self, parameter_s=''):
2240 2293 """Change to directory popped off the top of the stack.
2241 2294 """
2242 2295 if len (self.dir_stack) > 1:
2243 2296 self.dir_stack.pop(0)
2244 2297 self.magic_cd(self.dir_stack[0])
2245 2298 print self.dir_stack[0]
2246 2299 else:
2247 2300 print "You can't remove the starting directory from the stack:",\
2248 2301 self.dir_stack
2249 2302
2250 2303 def magic_dirs(self, parameter_s=''):
2251 2304 """Return the current directory stack."""
2252 2305
2253 2306 return self.dir_stack[:]
2254 2307
2255 2308 def magic_sc(self, parameter_s=''):
2256 2309 """Shell capture - execute a shell command and capture its output.
2257 2310
2258 2311 %sc [options] varname=command
2259 2312
2260 2313 IPython will run the given command using commands.getoutput(), and
2261 2314 will then update the user's interactive namespace with a variable
2262 2315 called varname, containing the value of the call. Your command can
2263 2316 contain shell wildcards, pipes, etc.
2264 2317
2265 2318 The '=' sign in the syntax is mandatory, and the variable name you
2266 2319 supply must follow Python's standard conventions for valid names.
2267 2320
2268 2321 Options:
2269 2322
2270 2323 -l: list output. Split the output on newlines into a list before
2271 2324 assigning it to the given variable. By default the output is stored
2272 2325 as a single string.
2273 2326
2274 2327 -v: verbose. Print the contents of the variable.
2275 2328
2276 2329 In most cases you should not need to split as a list, because the
2277 2330 returned value is a special type of string which can automatically
2278 2331 provide its contents either as a list (split on newlines) or as a
2279 2332 space-separated string. These are convenient, respectively, either
2280 2333 for sequential processing or to be passed to a shell command.
2281 2334
2282 2335 For example:
2283 2336
2284 2337 # Capture into variable a
2285 2338 In [9]: sc a=ls *py
2286 2339
2287 2340 # a is a string with embedded newlines
2288 2341 In [10]: a
2289 2342 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2290 2343
2291 2344 # which can be seen as a list:
2292 2345 In [11]: a.l
2293 2346 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2294 2347
2295 2348 # or as a whitespace-separated string:
2296 2349 In [12]: a.s
2297 2350 Out[12]: 'setup.py win32_manual_post_install.py'
2298 2351
2299 2352 # a.s is useful to pass as a single command line:
2300 2353 In [13]: !wc -l $a.s
2301 2354 146 setup.py
2302 2355 130 win32_manual_post_install.py
2303 2356 276 total
2304 2357
2305 2358 # while the list form is useful to loop over:
2306 2359 In [14]: for f in a.l:
2307 2360 ....: !wc -l $f
2308 2361 ....:
2309 2362 146 setup.py
2310 2363 130 win32_manual_post_install.py
2311 2364
2312 2365 Similiarly, the lists returned by the -l option are also special, in
2313 2366 the sense that you can equally invoke the .s attribute on them to
2314 2367 automatically get a whitespace-separated string from their contents:
2315 2368
2316 2369 In [1]: sc -l b=ls *py
2317 2370
2318 2371 In [2]: b
2319 2372 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2320 2373
2321 2374 In [3]: b.s
2322 2375 Out[3]: 'setup.py win32_manual_post_install.py'
2323 2376
2324 2377 In summary, both the lists and strings used for ouptut capture have
2325 2378 the following special attributes:
2326 2379
2327 2380 .l (or .list) : value as list.
2328 2381 .n (or .nlstr): value as newline-separated string.
2329 2382 .s (or .spstr): value as space-separated string.
2330 2383 """
2331 2384
2332 2385 opts,args = self.parse_options(parameter_s,'lv')
2333 2386 # Try to get a variable name and command to run
2334 2387 try:
2335 2388 # the variable name must be obtained from the parse_options
2336 2389 # output, which uses shlex.split to strip options out.
2337 2390 var,_ = args.split('=',1)
2338 2391 var = var.strip()
2339 2392 # But the the command has to be extracted from the original input
2340 2393 # parameter_s, not on what parse_options returns, to avoid the
2341 2394 # quote stripping which shlex.split performs on it.
2342 2395 _,cmd = parameter_s.split('=',1)
2343 2396 except ValueError:
2344 2397 var,cmd = '',''
2345 2398 if not var:
2346 2399 error('you must specify a variable to assign the command to.')
2347 2400 return
2348 2401 # If all looks ok, proceed
2349 2402 out,err = self.shell.getoutputerror(cmd)
2350 2403 if err:
2351 2404 print >> Term.cerr,err
2352 2405 if opts.has_key('l'):
2353 2406 out = SList(out.split('\n'))
2354 2407 else:
2355 2408 out = LSString(out)
2356 2409 if opts.has_key('v'):
2357 2410 print '%s ==\n%s' % (var,pformat(out))
2358 2411 self.shell.user_ns.update({var:out})
2359 2412
2360 2413 def magic_sx(self, parameter_s=''):
2361 2414 """Shell execute - run a shell command and capture its output.
2362 2415
2363 2416 %sx command
2364 2417
2365 2418 IPython will run the given command using commands.getoutput(), and
2366 2419 return the result formatted as a list (split on '\\n'). Since the
2367 2420 output is _returned_, it will be stored in ipython's regular output
2368 2421 cache Out[N] and in the '_N' automatic variables.
2369 2422
2370 2423 Notes:
2371 2424
2372 2425 1) If an input line begins with '!!', then %sx is automatically
2373 2426 invoked. That is, while:
2374 2427 !ls
2375 2428 causes ipython to simply issue system('ls'), typing
2376 2429 !!ls
2377 2430 is a shorthand equivalent to:
2378 2431 %sx ls
2379 2432
2380 2433 2) %sx differs from %sc in that %sx automatically splits into a list,
2381 2434 like '%sc -l'. The reason for this is to make it as easy as possible
2382 2435 to process line-oriented shell output via further python commands.
2383 2436 %sc is meant to provide much finer control, but requires more
2384 2437 typing.
2385 2438
2386 2439 3) Just like %sc -l, this is a list with special attributes:
2387 2440
2388 2441 .l (or .list) : value as list.
2389 2442 .n (or .nlstr): value as newline-separated string.
2390 2443 .s (or .spstr): value as whitespace-separated string.
2391 2444
2392 2445 This is very useful when trying to use such lists as arguments to
2393 2446 system commands."""
2394 2447
2395 2448 if parameter_s:
2396 2449 out,err = self.shell.getoutputerror(parameter_s)
2397 2450 if err:
2398 2451 print >> Term.cerr,err
2399 2452 return SList(out.split('\n'))
2400 2453
2401 2454 def magic_bg(self, parameter_s=''):
2402 2455 """Run a job in the background, in a separate thread.
2403 2456
2404 2457 For example,
2405 2458
2406 2459 %bg myfunc(x,y,z=1)
2407 2460
2408 2461 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2409 2462 execution starts, a message will be printed indicating the job
2410 2463 number. If your job number is 5, you can use
2411 2464
2412 2465 myvar = jobs.result(5) or myvar = jobs[5].result
2413 2466
2414 2467 to assign this result to variable 'myvar'.
2415 2468
2416 2469 IPython has a job manager, accessible via the 'jobs' object. You can
2417 2470 type jobs? to get more information about it, and use jobs.<TAB> to see
2418 2471 its attributes. All attributes not starting with an underscore are
2419 2472 meant for public use.
2420 2473
2421 2474 In particular, look at the jobs.new() method, which is used to create
2422 2475 new jobs. This magic %bg function is just a convenience wrapper
2423 2476 around jobs.new(), for expression-based jobs. If you want to create a
2424 2477 new job with an explicit function object and arguments, you must call
2425 2478 jobs.new() directly.
2426 2479
2427 2480 The jobs.new docstring also describes in detail several important
2428 2481 caveats associated with a thread-based model for background job
2429 2482 execution. Type jobs.new? for details.
2430 2483
2431 2484 You can check the status of all jobs with jobs.status().
2432 2485
2433 2486 The jobs variable is set by IPython into the Python builtin namespace.
2434 2487 If you ever declare a variable named 'jobs', you will shadow this
2435 2488 name. You can either delete your global jobs variable to regain
2436 2489 access to the job manager, or make a new name and assign it manually
2437 2490 to the manager (stored in IPython's namespace). For example, to
2438 2491 assign the job manager to the Jobs name, use:
2439 2492
2440 2493 Jobs = __builtins__.jobs"""
2441 2494
2442 2495 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2443 2496
2444 2497 def magic_bookmark(self, parameter_s=''):
2445 2498 """Manage IPython's bookmark system.
2446 2499
2447 2500 %bookmark <name> - set bookmark to current dir
2448 2501 %bookmark <name> <dir> - set bookmark to <dir>
2449 2502 %bookmark -l - list all bookmarks
2450 2503 %bookmark -d <name> - remove bookmark
2451 2504 %bookmark -r - remove all bookmarks
2452 2505
2453 2506 You can later on access a bookmarked folder with:
2454 2507 %cd -b <name>
2455 2508 or simply '%cd <name>' if there is no directory called <name> AND
2456 2509 there is such a bookmark defined.
2457 2510
2458 2511 Your bookmarks persist through IPython sessions, but they are
2459 2512 associated with each profile."""
2460 2513
2461 2514 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2462 2515 if len(args) > 2:
2463 2516 error('You can only give at most two arguments')
2464 2517 return
2465 2518
2466 2519 bkms = self.shell.persist.get('bookmarks',{})
2467 2520
2468 2521 if opts.has_key('d'):
2469 2522 try:
2470 2523 todel = args[0]
2471 2524 except IndexError:
2472 2525 error('You must provide a bookmark to delete')
2473 2526 else:
2474 2527 try:
2475 2528 del bkms[todel]
2476 2529 except:
2477 2530 error("Can't delete bookmark '%s'" % todel)
2478 2531 elif opts.has_key('r'):
2479 2532 bkms = {}
2480 2533 elif opts.has_key('l'):
2481 2534 bks = bkms.keys()
2482 2535 bks.sort()
2483 2536 if bks:
2484 2537 size = max(map(len,bks))
2485 2538 else:
2486 2539 size = 0
2487 2540 fmt = '%-'+str(size)+'s -> %s'
2488 2541 print 'Current bookmarks:'
2489 2542 for bk in bks:
2490 2543 print fmt % (bk,bkms[bk])
2491 2544 else:
2492 2545 if not args:
2493 2546 error("You must specify the bookmark name")
2494 2547 elif len(args)==1:
2495 2548 bkms[args[0]] = os.getcwd()
2496 2549 elif len(args)==2:
2497 2550 bkms[args[0]] = args[1]
2498 2551 self.persist['bookmarks'] = bkms
2499 2552
2500 2553 def magic_pycat(self, parameter_s=''):
2501 2554 """Show a syntax-highlighted file through a pager.
2502 2555
2503 2556 This magic is similar to the cat utility, but it will assume the file
2504 2557 to be Python source and will show it with syntax highlighting. """
2505 2558
2506 2559 filename = get_py_filename(parameter_s)
2507 2560 page(self.shell.colorize(file_read(filename)),
2508 2561 screen_lines=self.shell.rc.screen_length)
2509 2562
2510 2563 # end Magic
@@ -1,442 +1,455 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tools for inspecting Python objects.
3 3
4 4 Uses syntax highlighting for presenting the various information elements.
5 5
6 6 Similar in spirit to the inspect module, but all calls take a name argument to
7 7 reference the name under which an object is being read.
8 8
9 $Id: OInspect.py 922 2005-11-13 10:21:08Z fperez $
9 $Id: OInspect.py 923 2005-11-15 08:51:15Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #*****************************************************************************
18 18
19 19 from IPython import Release
20 20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 21 __license__ = Release.license
22 22
23 23 __all__ = ['Inspector','InspectColors']
24 24
25 25 # stdlib modules
26 import __builtin__
26 27 import inspect,linecache,types,StringIO,string
27 28
28 29 # IPython's own
29 30 from IPython import PyColorize
30 31 from IPython.Itpl import itpl
31 from IPython.wildcard import choose_namespaces,list_namespace
32 from IPython.genutils import page,indent,Term
32 from IPython.wildcard import list_namespace
33 from IPython.genutils import page,indent,Term,mkdict
33 34 from IPython.ColorANSI import *
34 35
35 36 #****************************************************************************
36 37 # Builtin color schemes
37 38
38 39 Colors = TermColors # just a shorthand
39 40
40 41 # Build a few color schemes
41 42 NoColor = ColorScheme(
42 43 'NoColor',{
43 44 'header' : Colors.NoColor,
44 45 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
45 46 } )
46 47
47 48 LinuxColors = ColorScheme(
48 49 'Linux',{
49 50 'header' : Colors.LightRed,
50 51 'normal' : Colors.Normal # color off (usu. Colors.Normal)
51 52 } )
52 53
53 54 LightBGColors = ColorScheme(
54 55 'LightBG',{
55 56 'header' : Colors.Red,
56 57 'normal' : Colors.Normal # color off (usu. Colors.Normal)
57 58 } )
58 59
59 60 # Build table of color schemes (needed by the parser)
60 61 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
61 62 'Linux')
62 63
63 64 #****************************************************************************
64 65 # Auxiliary functions
65 66 def getdoc(obj):
66 67 """Stable wrapper around inspect.getdoc.
67 68
68 69 This can't crash because of attribute problems.
69 70
70 71 It also attempts to call a getdoc() method on the given object. This
71 72 allows objects which provide their docstrings via non-standard mechanisms
72 73 (like Pyro proxies) to still be inspected by ipython's ? system."""
73 74
74 75 ds = None # default return value
75 76 try:
76 77 ds = inspect.getdoc(obj)
77 78 except:
78 79 # Harden against an inspect failure, which can occur with
79 80 # SWIG-wrapped extensions.
80 81 pass
81 82 # Allow objects to offer customized documentation via a getdoc method:
82 83 try:
83 84 ds2 = obj.getdoc()
84 85 except:
85 86 pass
86 87 else:
87 88 # if we get extra info, we add it to the normal docstring.
88 89 if ds is None:
89 90 ds = ds2
90 91 else:
91 92 ds = '%s\n%s' % (ds,ds2)
92 93 return ds
93 94
94 95 #****************************************************************************
95 96 # Class definitions
96 97
97 98 class myStringIO(StringIO.StringIO):
98 99 """Adds a writeln method to normal StringIO."""
99 100 def writeln(self,*arg,**kw):
100 101 """Does a write() and then a write('\n')"""
101 102 self.write(*arg,**kw)
102 103 self.write('\n')
103 104
104 105 class Inspector:
105 106 def __init__(self,color_table,code_color_table,scheme):
106 107 self.color_table = color_table
107 108 self.parser = PyColorize.Parser(code_color_table,out='str')
108 109 self.format = self.parser.format
109 110 self.set_active_scheme(scheme)
110 111
111 112 def __getargspec(self,obj):
112 113 """Get the names and default values of a function's arguments.
113 114
114 115 A tuple of four things is returned: (args, varargs, varkw, defaults).
115 116 'args' is a list of the argument names (it may contain nested lists).
116 117 'varargs' and 'varkw' are the names of the * and ** arguments or None.
117 118 'defaults' is an n-tuple of the default values of the last n arguments.
118 119
119 120 Modified version of inspect.getargspec from the Python Standard
120 121 Library."""
121 122
122 123 if inspect.isfunction(obj):
123 124 func_obj = obj
124 125 elif inspect.ismethod(obj):
125 126 func_obj = obj.im_func
126 127 else:
127 128 raise TypeError, 'arg is not a Python function'
128 129 args, varargs, varkw = inspect.getargs(func_obj.func_code)
129 130 return args, varargs, varkw, func_obj.func_defaults
130 131
131 132 def __getdef(self,obj,oname=''):
132 133 """Return the definition header for any callable object.
133 134
134 135 If any exception is generated, None is returned instead and the
135 136 exception is suppressed."""
136 137
137 138 try:
138 139 return oname + inspect.formatargspec(*self.__getargspec(obj))
139 140 except:
140 141 return None
141 142
142 143 def __head(self,h):
143 144 """Return a header string with proper colors."""
144 145 return '%s%s%s' % (self.color_table.active_colors.header,h,
145 146 self.color_table.active_colors.normal)
146 147
147 148 def set_active_scheme(self,scheme):
148 149 self.color_table.set_active_scheme(scheme)
149 150 self.parser.color_table.set_active_scheme(scheme)
150 151
151 152 def noinfo(self,msg,oname):
152 153 """Generic message when no information is found."""
153 154 print 'No %s found' % msg,
154 155 if oname:
155 156 print 'for %s' % oname
156 157 else:
157 158 print
158 159
159 160 def pdef(self,obj,oname=''):
160 161 """Print the definition header for any callable object.
161 162
162 163 If the object is a class, print the constructor information."""
163 164
164 165 if not callable(obj):
165 166 print 'Object is not callable.'
166 167 return
167 168
168 169 header = ''
169 170 if type(obj) is types.ClassType:
170 171 header = self.__head('Class constructor information:\n')
171 172 obj = obj.__init__
172 173 elif type(obj) is types.InstanceType:
173 174 obj = obj.__call__
174 175
175 176 output = self.__getdef(obj,oname)
176 177 if output is None:
177 178 self.noinfo('definition header',oname)
178 179 else:
179 180 print >>Term.cout, header,self.format(output),
180 181
181 182 def pdoc(self,obj,oname='',formatter = None):
182 183 """Print the docstring for any object.
183 184
184 185 Optional:
185 186 -formatter: a function to run the docstring through for specially
186 187 formatted docstrings."""
187 188
188 189 head = self.__head # so that itpl can find it even if private
189 190 ds = getdoc(obj)
190 191 if formatter:
191 192 ds = formatter(ds)
192 193 if type(obj) is types.ClassType:
193 194 init_ds = getdoc(obj.__init__)
194 195 output = itpl('$head("Class Docstring:")\n'
195 196 '$indent(ds)\n'
196 197 '$head("Constructor Docstring"):\n'
197 198 '$indent(init_ds)')
198 199 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
199 200 call_ds = getdoc(obj.__call__)
200 201 if call_ds:
201 202 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
202 203 '$head("Calling Docstring:")\n$indent(call_ds)')
203 204 else:
204 205 output = ds
205 206 else:
206 207 output = ds
207 208 if output is None:
208 209 self.noinfo('documentation',oname)
209 210 return
210 211 page(output)
211 212
212 213 def psource(self,obj,oname=''):
213 214 """Print the source code for an object."""
214 215
215 216 # Flush the source cache because inspect can return out-of-date source
216 217 linecache.checkcache()
217 218 try:
218 219 src = inspect.getsource(obj)
219 220 except:
220 221 self.noinfo('source',oname)
221 222 else:
222 223 page(self.format(src))
223 224
224 225 def pfile(self,obj,oname=''):
225 226 """Show the whole file where an object was defined."""
226 227 try:
227 228 sourcelines,lineno = inspect.getsourcelines(obj)
228 229 except:
229 230 self.noinfo('file',oname)
230 231 else:
231 232 # run contents of file through pager starting at line
232 233 # where the object is defined
233 234 page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
234 235
235 236 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
236 237 """Show detailed information about an object.
237 238
238 239 Optional arguments:
239 240
240 241 - oname: name of the variable pointing to the object.
241 242
242 243 - formatter: special formatter for docstrings (see pdoc)
243 244
244 245 - info: a structure with some information fields which may have been
245 246 precomputed already.
246 247
247 248 - detail_level: if set to 1, more information is given.
248 249 """
249 250
250 251 obj_type = type(obj)
251 252
252 253 header = self.__head
253 254 if info is None:
254 255 ismagic = 0
255 256 isalias = 0
256 257 ospace = ''
257 258 else:
258 259 ismagic = info.ismagic
259 260 isalias = info.isalias
260 261 ospace = info.namespace
261 262 # Get docstring, special-casing aliases:
262 263 if isalias:
263 264 ds = "Alias to the system command:\n %s" % obj[1]
264 265 else:
265 266 ds = getdoc(obj)
266 267 if formatter is not None:
267 268 ds = formatter(ds)
268 269
269 270 # store output in a list which gets joined with \n at the end.
270 271 out = myStringIO()
271 272
272 273 string_max = 200 # max size of strings to show (snipped if longer)
273 274 shalf = int((string_max -5)/2)
274 275
275 276 if ismagic:
276 277 obj_type_name = 'Magic function'
277 278 elif isalias:
278 279 obj_type_name = 'System alias'
279 280 else:
280 281 obj_type_name = obj_type.__name__
281 282 out.writeln(header('Type:\t\t')+obj_type_name)
282 283
283 284 try:
284 285 bclass = obj.__class__
285 286 out.writeln(header('Base Class:\t')+str(bclass))
286 287 except: pass
287 288
288 289 # String form, but snip if too long in ? form (full in ??)
289 290 try:
290 291 ostr = str(obj)
291 292 str_head = 'String Form:'
292 293 if not detail_level and len(ostr)>string_max:
293 294 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
294 295 ostr = ("\n" + " " * len(str_head.expandtabs())).\
295 296 join(map(string.strip,ostr.split("\n")))
296 297 if ostr.find('\n') > -1:
297 298 # Print multi-line strings starting at the next line.
298 299 str_sep = '\n'
299 300 else:
300 301 str_sep = '\t'
301 302 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
302 303 except:
303 304 pass
304 305
305 306 if ospace:
306 307 out.writeln(header('Namespace:\t')+ospace)
307 308
308 309 # Length (for strings and lists)
309 310 try:
310 311 length = str(len(obj))
311 312 out.writeln(header('Length:\t\t')+length)
312 313 except: pass
313 314
314 315 # Filename where object was defined
315 316 try:
316 317 file = inspect.getabsfile(obj)
317 318 if file.endswith('<string>'):
318 319 file = 'Dynamically generated function. No source code available.'
319 320 out.writeln(header('File:\t\t')+file)
320 321 except: pass
321 322
322 323 # reconstruct the function definition and print it:
323 324 defln = self.__getdef(obj,oname)
324 325 if defln:
325 326 out.write(header('Definition:\t')+self.format(defln))
326 327
327 328 # Docstrings only in detail 0 mode, since source contains them (we
328 329 # avoid repetitions). If source fails, we add them back, see below.
329 330 if ds and detail_level == 0:
330 331 out.writeln(header('Docstring:\n') + indent(ds))
331 332
332 333 # Original source code for any callable
333 334 if detail_level:
334 335 # Flush the source cache because inspect can return out-of-date source
335 336 linecache.checkcache()
336 337 try:
337 338 source = self.format(inspect.getsource(obj))
338 339 out.write(header('Source:\n')+source.rstrip())
339 340 except:
340 341 if ds:
341 342 out.writeln(header('Docstring:\n') + indent(ds))
342 343
343 344 # Constructor docstring for classes
344 345 if obj_type is types.ClassType:
345 346 # reconstruct the function definition and print it:
346 347 try:
347 348 obj_init = obj.__init__
348 349 except AttributeError:
349 350 init_def = init_ds = None
350 351 else:
351 352 init_def = self.__getdef(obj_init,oname)
352 353 init_ds = getdoc(obj_init)
353 354
354 355 if init_def or init_ds:
355 356 out.writeln(header('\nConstructor information:'))
356 357 if init_def:
357 358 out.write(header('Definition:\t')+ self.format(init_def))
358 359 if init_ds:
359 360 out.writeln(header('Docstring:\n') + indent(init_ds))
360 361 # and class docstring for instances:
361 362 elif obj_type is types.InstanceType:
362 363
363 364 # First, check whether the instance docstring is identical to the
364 365 # class one, and print it separately if they don't coincide. In
365 366 # most cases they will, but it's nice to print all the info for
366 367 # objects which use instance-customized docstrings.
367 368 if ds:
368 369 class_ds = getdoc(obj.__class__)
369 370 if class_ds and ds != class_ds:
370 371 out.writeln(header('Class Docstring:\n') +
371 372 indent(class_ds))
372 373
373 374 # Next, try to show constructor docstrings
374 375 try:
375 376 init_ds = getdoc(obj.__init__)
376 377 except AttributeError:
377 378 init_ds = None
378 379 if init_ds:
379 380 out.writeln(header('Constructor Docstring:\n') +
380 381 indent(init_ds))
381 382
382 383 # Call form docstring for callable instances
383 384 if hasattr(obj,'__call__'):
384 385 out.writeln(header('Callable:\t')+'Yes')
385 386 call_def = self.__getdef(obj.__call__,oname)
386 387 if call_def is None:
387 388 out.write(header('Call def:\t')+
388 389 'Calling definition not available.')
389 390 else:
390 391 out.write(header('Call def:\t')+self.format(call_def))
391 392 call_ds = getdoc(obj.__call__)
392 393 if call_ds:
393 394 out.writeln(header('Call docstring:\n') + indent(call_ds))
394 395
395 396 # Finally send to printer/pager
396 397 output = out.getvalue()
397 398 if output:
398 399 page(output)
399 400 # end pinfo
400 401
401 def psearch(self,oname='',formatter=None,shell=None):
402 def psearch(self,pattern,ns_table,ns_search=[],
403 ignore_case=False,show_all=False):
402 404 """Search namespaces with wildcards for objects.
403 405
406 Arguments:
407
408 - pattern: string containing shell-like wildcards to use in namespace
409 searches and optionally a type specification to narrow the search to
410 objects of that type.
411
412 - ns_table: dict of name->namespaces for search.
413
404 414 Optional arguments:
405 415
406 - oname: rest of the commandline containging pattern and options.
416 - ns_search: list of namespace names to include in search.
407 417
408 - formatter: Not used.
418 - ignore_case(False): make the search case-insensitive.
409 419
410 - shell: The shell object from the Magic class. Needed to access
411 the namespaces.
420 - show_all(False): show all names, including those starting with
421 underscores.
412 422 """
413 option_list = ['-c','-a']
414 cmds = oname.split()
415 filter = ''
423 # defaults
416 424 type_pattern = 'all'
417 options = [x for x in cmds if x in option_list]
418 ignorecase = '-c' not in options
419 showhidden = '-a' in options
420 ns_cmds = [x for x in cmds if x[0] in '-+' and x not in option_list]
421 cmds = [x for x in cmds if x[0] not in '-+']
425 filter = ''
426
427 cmds = pattern.split()
422 428 len_cmds = len(cmds)
423 429 if len_cmds == 1:
424 filter = cmds[0].strip()
430 # Only filter pattern given
431 filter = cmds[0]
425 432 elif len_cmds == 2:
433 # Both filter and type specified
426 434 filter,type_pattern = cmds
427 elif len_cmds>2:
428 # assume we want to choose name spaces. Rather poor design forces
429 #the use of a typepattern in order to choose name spaces
430 cmds = cmds[:2]
435 else:
436 raise ValueError('invalid argument string for psearch: <%s>' %
437 pattern)
431 438
432 do_list = choose_namespaces(shell,ns_cmds)
439 # filter search namespaces
440 for name in ns_search:
441 if name not in ns_table:
442 raise ValueError('invalid namespace <%s>. Valid names: %s' %
443 (name,ns_table.keys()))
433 444
445 #print 'type_pattern:',type_pattern # dbg
434 446 search_result = []
435 for ns in do_list:
447 for ns_name in ns_search:
448 ns = ns_table[ns_name]
436 449 tmp_res = list(list_namespace(ns,type_pattern,filter,
437 ignorecase=ignorecase,
438 showhidden=showhidden))
450 ignore_case=ignore_case,
451 show_all=show_all))
439 452 search_result.extend(tmp_res)
440 453 search_result.sort()
441 454
442 455 page('\n'.join(search_result))
@@ -1,880 +1,877 b''
1 1 # -*- coding: utf-8 -*-
2 2 """IPython Shell classes.
3 3
4 4 All the matplotlib support code was co-developed with John Hunter,
5 5 matplotlib's author.
6 6
7 $Id: Shell.py 921 2005-11-13 06:51:34Z fperez $"""
7 $Id: Shell.py 923 2005-11-15 08:51:15Z fperez $"""
8 8
9 9 #*****************************************************************************
10 10 # Copyright (C) 2001-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 from IPython import Release
17 17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 18 __license__ = Release.license
19 19
20 20 # Code begins
21 21 import __main__
22 22 import __builtin__
23 23 import sys
24 24 import os
25 25 import code
26 26 import threading
27 27 import signal
28 28
29 29 import IPython
30 30 from IPython.iplib import InteractiveShell
31 31 from IPython.ipmaker import make_IPython
32 32 from IPython.genutils import Term,warn,error,flag_calls
33 33 from IPython.Struct import Struct
34 34 from IPython.Magic import Magic
35 35 from IPython import ultraTB
36 36
37 37 # global flag to pass around information about Ctrl-C without exceptions
38 38 KBINT = False
39 39
40 40 # global flag to turn on/off Tk support.
41 41 USE_TK = False
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # This class is trivial now, but I want to have it in to publish a clean
45 45 # interface. Later when the internals are reorganized, code that uses this
46 46 # shouldn't have to change.
47 47
48 48 class IPShell:
49 49 """Create an IPython instance."""
50 50
51 51 def __init__(self,argv=None,user_ns=None,debug=1,
52 52 shell_class=InteractiveShell):
53 53 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
54 54 shell_class=shell_class)
55 55
56 56 def mainloop(self,sys_exit=0,banner=None):
57 57 self.IP.mainloop(banner)
58 58 if sys_exit:
59 59 sys.exit()
60 60
61 61 #-----------------------------------------------------------------------------
62 62 class IPShellEmbed:
63 63 """Allow embedding an IPython shell into a running program.
64 64
65 65 Instances of this class are callable, with the __call__ method being an
66 66 alias to the embed() method of an InteractiveShell instance.
67 67
68 68 Usage (see also the example-embed.py file for a running example):
69 69
70 70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
71 71
72 72 - argv: list containing valid command-line options for IPython, as they
73 73 would appear in sys.argv[1:].
74 74
75 75 For example, the following command-line options:
76 76
77 77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
78 78
79 79 would be passed in the argv list as:
80 80
81 81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
82 82
83 83 - banner: string which gets printed every time the interpreter starts.
84 84
85 85 - exit_msg: string which gets printed every time the interpreter exits.
86 86
87 87 - rc_override: a dict or Struct of configuration options such as those
88 88 used by IPython. These options are read from your ~/.ipython/ipythonrc
89 89 file when the Shell object is created. Passing an explicit rc_override
90 90 dict with any options you want allows you to override those values at
91 91 creation time without having to modify the file. This way you can create
92 92 embeddable instances configured in any way you want without editing any
93 93 global files (thus keeping your interactive IPython configuration
94 94 unchanged).
95 95
96 96 Then the ipshell instance can be called anywhere inside your code:
97 97
98 98 ipshell(header='') -> Opens up an IPython shell.
99 99
100 100 - header: string printed by the IPython shell upon startup. This can let
101 101 you know where in your code you are when dropping into the shell. Note
102 102 that 'banner' gets prepended to all calls, so header is used for
103 103 location-specific information.
104 104
105 105 For more details, see the __call__ method below.
106 106
107 107 When the IPython shell is exited with Ctrl-D, normal program execution
108 108 resumes.
109 109
110 110 This functionality was inspired by a posting on comp.lang.python by cmkl
111 111 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
112 112 by the IDL stop/continue commands."""
113 113
114 114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
115 115 """Note that argv here is a string, NOT a list."""
116 116 self.set_banner(banner)
117 117 self.set_exit_msg(exit_msg)
118 118 self.set_dummy_mode(0)
119 119
120 120 # sys.displayhook is a global, we need to save the user's original
121 121 # Don't rely on __displayhook__, as the user may have changed that.
122 122 self.sys_displayhook_ori = sys.displayhook
123 123
124 124 # save readline completer status
125 125 try:
126 126 #print 'Save completer',sys.ipcompleter # dbg
127 127 self.sys_ipcompleter_ori = sys.ipcompleter
128 128 except:
129 129 pass # not nested with IPython
130 130
131 131 # FIXME. Passing user_ns breaks namespace handling.
132 132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
134 134
135 # mark this as an embedded instance so we know if we get a crash
136 # post-mortem
137 self.IP.rc.embedded = 1
138 135 # copy our own displayhook also
139 136 self.sys_displayhook_embed = sys.displayhook
140 137 # and leave the system's display hook clean
141 138 sys.displayhook = self.sys_displayhook_ori
142 139 # don't use the ipython crash handler so that user exceptions aren't
143 140 # trapped
144 141 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
145 142 mode = self.IP.rc.xmode,
146 143 call_pdb = self.IP.rc.pdb)
147 144 self.restore_system_completer()
148 145
149 146 def restore_system_completer(self):
150 147 """Restores the readline completer which was in place.
151 148
152 149 This allows embedded IPython within IPython not to disrupt the
153 150 parent's completion.
154 151 """
155 152
156 153 try:
157 154 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
158 155 sys.ipcompleter = self.sys_ipcompleter_ori
159 156 except:
160 157 pass
161 158
162 159 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
163 160 """Activate the interactive interpreter.
164 161
165 162 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
166 163 the interpreter shell with the given local and global namespaces, and
167 164 optionally print a header string at startup.
168 165
169 166 The shell can be globally activated/deactivated using the
170 167 set/get_dummy_mode methods. This allows you to turn off a shell used
171 168 for debugging globally.
172 169
173 170 However, *each* time you call the shell you can override the current
174 171 state of dummy_mode with the optional keyword parameter 'dummy'. For
175 172 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
176 173 can still have a specific call work by making it as IPShell(dummy=0).
177 174
178 175 The optional keyword parameter dummy controls whether the call
179 176 actually does anything. """
180 177
181 178 # Allow the dummy parameter to override the global __dummy_mode
182 179 if dummy or (dummy != 0 and self.__dummy_mode):
183 180 return
184 181
185 182 # Set global subsystems (display,completions) to our values
186 183 sys.displayhook = self.sys_displayhook_embed
187 184 if self.IP.has_readline:
188 185 self.IP.readline.set_completer(self.IP.Completer.complete)
189 186
190 187 if self.banner and header:
191 188 format = '%s\n%s\n'
192 189 else:
193 190 format = '%s%s\n'
194 191 banner = format % (self.banner,header)
195 192
196 193 # Call the embedding code with a stack depth of 1 so it can skip over
197 194 # our call and get the original caller's namespaces.
198 195 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
199 196
200 197 if self.exit_msg:
201 198 print self.exit_msg
202 199
203 200 # Restore global systems (display, completion)
204 201 sys.displayhook = self.sys_displayhook_ori
205 202 self.restore_system_completer()
206 203
207 204 def set_dummy_mode(self,dummy):
208 205 """Sets the embeddable shell's dummy mode parameter.
209 206
210 207 set_dummy_mode(dummy): dummy = 0 or 1.
211 208
212 209 This parameter is persistent and makes calls to the embeddable shell
213 210 silently return without performing any action. This allows you to
214 211 globally activate or deactivate a shell you're using with a single call.
215 212
216 213 If you need to manually"""
217 214
218 215 if dummy not in [0,1]:
219 216 raise ValueError,'dummy parameter must be 0 or 1'
220 217 self.__dummy_mode = dummy
221 218
222 219 def get_dummy_mode(self):
223 220 """Return the current value of the dummy mode parameter.
224 221 """
225 222 return self.__dummy_mode
226 223
227 224 def set_banner(self,banner):
228 225 """Sets the global banner.
229 226
230 227 This banner gets prepended to every header printed when the shell
231 228 instance is called."""
232 229
233 230 self.banner = banner
234 231
235 232 def set_exit_msg(self,exit_msg):
236 233 """Sets the global exit_msg.
237 234
238 235 This exit message gets printed upon exiting every time the embedded
239 236 shell is called. It is None by default. """
240 237
241 238 self.exit_msg = exit_msg
242 239
243 240 #-----------------------------------------------------------------------------
244 241 def sigint_handler (signum,stack_frame):
245 242 """Sigint handler for threaded apps.
246 243
247 244 This is a horrible hack to pass information about SIGINT _without_ using
248 245 exceptions, since I haven't been able to properly manage cross-thread
249 246 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
250 247 that's my understanding from a c.l.py thread where this was discussed)."""
251 248
252 249 global KBINT
253 250
254 251 print '\nKeyboardInterrupt - Press <Enter> to continue.',
255 252 Term.cout.flush()
256 253 # Set global flag so that runsource can know that Ctrl-C was hit
257 254 KBINT = True
258 255
259 256 class MTInteractiveShell(InteractiveShell):
260 257 """Simple multi-threaded shell."""
261 258
262 259 # Threading strategy taken from:
263 260 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
264 261 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
265 262 # from the pygtk mailing list, to avoid lockups with system calls.
266 263
267 264 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
268 265 user_ns = None, banner2='',**kw):
269 266 """Similar to the normal InteractiveShell, but with threading control"""
270 267
271 268 IPython.iplib.InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2)
272 269
273 270 # Locking control variable
274 271 self.thread_ready = threading.Condition()
275 272
276 273 # Stuff to do at closing time
277 274 self._kill = False
278 275 on_kill = kw.get('on_kill')
279 276 if on_kill is None:
280 277 on_kill = []
281 278 # Check that all things to kill are callable:
282 279 for t in on_kill:
283 280 if not callable(t):
284 281 raise TypeError,'on_kill must be a list of callables'
285 282 self.on_kill = on_kill
286 283
287 284 def runsource(self, source, filename="<input>", symbol="single"):
288 285 """Compile and run some source in the interpreter.
289 286
290 287 Modified version of code.py's runsource(), to handle threading issues.
291 288 See the original for full docstring details."""
292 289
293 290 global KBINT
294 291
295 292 # If Ctrl-C was typed, we reset the flag and return right away
296 293 if KBINT:
297 294 KBINT = False
298 295 return False
299 296
300 297 try:
301 298 code = self.compile(source, filename, symbol)
302 299 except (OverflowError, SyntaxError, ValueError):
303 300 # Case 1
304 301 self.showsyntaxerror(filename)
305 302 return False
306 303
307 304 if code is None:
308 305 # Case 2
309 306 return True
310 307
311 308 # Case 3
312 309 # Store code in self, so the execution thread can handle it
313 310 self.thread_ready.acquire()
314 311 self.code_to_run = code
315 312 self.thread_ready.wait() # Wait until processed in timeout interval
316 313 self.thread_ready.release()
317 314
318 315 return False
319 316
320 317 def runcode(self):
321 318 """Execute a code object.
322 319
323 320 Multithreaded wrapper around IPython's runcode()."""
324 321
325 322 # lock thread-protected stuff
326 323 self.thread_ready.acquire()
327 324
328 325 # Install sigint handler
329 326 try:
330 327 signal.signal(signal.SIGINT, sigint_handler)
331 328 except SystemError:
332 329 # This happens under Windows, which seems to have all sorts
333 330 # of problems with signal handling. Oh well...
334 331 pass
335 332
336 333 if self._kill:
337 334 print >>Term.cout, 'Closing threads...',
338 335 Term.cout.flush()
339 336 for tokill in self.on_kill:
340 337 tokill()
341 338 print >>Term.cout, 'Done.'
342 339
343 340 # Run pending code by calling parent class
344 341 if self.code_to_run is not None:
345 342 self.thread_ready.notify()
346 343 InteractiveShell.runcode(self,self.code_to_run)
347 344
348 345 # We're done with thread-protected variables
349 346 self.thread_ready.release()
350 347 # This MUST return true for gtk threading to work
351 348 return True
352 349
353 350 def kill (self):
354 351 """Kill the thread, returning when it has been shut down."""
355 352 self.thread_ready.acquire()
356 353 self._kill = True
357 354 self.thread_ready.release()
358 355
359 356 class MatplotlibShellBase:
360 357 """Mixin class to provide the necessary modifications to regular IPython
361 358 shell classes for matplotlib support.
362 359
363 360 Given Python's MRO, this should be used as the FIRST class in the
364 361 inheritance hierarchy, so that it overrides the relevant methods."""
365 362
366 363 def _matplotlib_config(self,name):
367 364 """Return various items needed to setup the user's shell with matplotlib"""
368 365
369 366 # Initialize matplotlib to interactive mode always
370 367 import matplotlib
371 368 from matplotlib import backends
372 369 matplotlib.interactive(True)
373 370
374 371 def use(arg):
375 372 """IPython wrapper for matplotlib's backend switcher.
376 373
377 374 In interactive use, we can not allow switching to a different
378 375 interactive backend, since thread conflicts will most likely crash
379 376 the python interpreter. This routine does a safety check first,
380 377 and refuses to perform a dangerous switch. It still allows
381 378 switching to non-interactive backends."""
382 379
383 380 if arg in backends.interactive_bk and arg != self.mpl_backend:
384 381 m=('invalid matplotlib backend switch.\n'
385 382 'This script attempted to switch to the interactive '
386 383 'backend: `%s`\n'
387 384 'Your current choice of interactive backend is: `%s`\n\n'
388 385 'Switching interactive matplotlib backends at runtime\n'
389 386 'would crash the python interpreter, '
390 387 'and IPython has blocked it.\n\n'
391 388 'You need to either change your choice of matplotlib backend\n'
392 389 'by editing your .matplotlibrc file, or run this script as a \n'
393 390 'standalone file from the command line, not using IPython.\n' %
394 391 (arg,self.mpl_backend) )
395 392 raise RuntimeError, m
396 393 else:
397 394 self.mpl_use(arg)
398 395 self.mpl_use._called = True
399 396
400 397 self.matplotlib = matplotlib
401 398 self.mpl_backend = matplotlib.rcParams['backend']
402 399
403 400 # we also need to block switching of interactive backends by use()
404 401 self.mpl_use = matplotlib.use
405 402 self.mpl_use._called = False
406 403 # overwrite the original matplotlib.use with our wrapper
407 404 matplotlib.use = use
408 405
409 406
410 407 # This must be imported last in the matplotlib series, after
411 408 # backend/interactivity choices have been made
412 409 try:
413 410 import matplotlib.pylab as pylab
414 411 self.pylab = pylab
415 412 self.pylab_name = 'pylab'
416 413 except ImportError:
417 414 import matplotlib.matlab as matlab
418 415 self.pylab = matlab
419 416 self.pylab_name = 'matlab'
420 417
421 418 self.pylab.show._needmain = False
422 419 # We need to detect at runtime whether show() is called by the user.
423 420 # For this, we wrap it into a decorator which adds a 'called' flag.
424 421 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
425 422
426 423 # Build a user namespace initialized with matplotlib/matlab features.
427 424 user_ns = {'__name__':'__main__',
428 425 '__builtins__' : __builtin__ }
429 426
430 427 # Be careful not to remove the final \n in the code string below, or
431 428 # things will break badly with py22 (I think it's a python bug, 2.3 is
432 429 # OK).
433 430 pname = self.pylab_name # Python can't interpolate dotted var names
434 431 exec ("import matplotlib\n"
435 432 "import matplotlib.%(pname)s as %(pname)s\n"
436 433 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
437 434
438 435 # Build matplotlib info banner
439 436 b="""
440 437 Welcome to pylab, a matplotlib-based Python environment.
441 438 For more information, type 'help(pylab)'.
442 439 """
443 440 return user_ns,b
444 441
445 442 def mplot_exec(self,fname,*where,**kw):
446 443 """Execute a matplotlib script.
447 444
448 445 This is a call to execfile(), but wrapped in safeties to properly
449 446 handle interactive rendering and backend switching."""
450 447
451 448 #print '*** Matplotlib runner ***' # dbg
452 449 # turn off rendering until end of script
453 450 isInteractive = self.matplotlib.rcParams['interactive']
454 451 self.matplotlib.interactive(False)
455 452 self.safe_execfile(fname,*where,**kw)
456 453 self.matplotlib.interactive(isInteractive)
457 454 # make rendering call now, if the user tried to do it
458 455 if self.pylab.draw_if_interactive.called:
459 456 self.pylab.draw()
460 457 self.pylab.draw_if_interactive.called = False
461 458
462 459 # if a backend switch was performed, reverse it now
463 460 if self.mpl_use._called:
464 461 self.matplotlib.rcParams['backend'] = self.mpl_backend
465 462
466 463 def magic_run(self,parameter_s=''):
467 464 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
468 465
469 466 # Fix the docstring so users see the original as well
470 467 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
471 468 "\n *** Modified %run for Matplotlib,"
472 469 " with proper interactive handling ***")
473 470
474 471 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
475 472 # and multithreaded. Note that these are meant for internal use, the IPShell*
476 473 # classes below are the ones meant for public consumption.
477 474
478 475 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
479 476 """Single-threaded shell with matplotlib support."""
480 477
481 478 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
482 479 user_ns = None, **kw):
483 480 user_ns,b2 = self._matplotlib_config(name)
484 481 InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
485 482
486 483 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
487 484 """Multi-threaded shell with matplotlib support."""
488 485
489 486 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
490 487 user_ns = None, **kw):
491 488 user_ns,b2 = self._matplotlib_config(name)
492 489 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
493 490
494 491 #-----------------------------------------------------------------------------
495 492 # Utility functions for the different GUI enabled IPShell* classes.
496 493
497 494 def get_tk():
498 495 """Tries to import Tkinter and returns a withdrawn Tkinter root
499 496 window. If Tkinter is already imported or not available, this
500 497 returns None. This function calls `hijack_tk` underneath.
501 498 """
502 499 if not USE_TK or sys.modules.has_key('Tkinter'):
503 500 return None
504 501 else:
505 502 try:
506 503 import Tkinter
507 504 except ImportError:
508 505 return None
509 506 else:
510 507 hijack_tk()
511 508 r = Tkinter.Tk()
512 509 r.withdraw()
513 510 return r
514 511
515 512 def hijack_tk():
516 513 """Modifies Tkinter's mainloop with a dummy so when a module calls
517 514 mainloop, it does not block.
518 515
519 516 """
520 517 def misc_mainloop(self, n=0):
521 518 pass
522 519 def tkinter_mainloop(n=0):
523 520 pass
524 521
525 522 import Tkinter
526 523 Tkinter.Misc.mainloop = misc_mainloop
527 524 Tkinter.mainloop = tkinter_mainloop
528 525
529 526 def update_tk(tk):
530 527 """Updates the Tkinter event loop. This is typically called from
531 528 the respective WX or GTK mainloops.
532 529 """
533 530 if tk:
534 531 tk.update()
535 532
536 533 def hijack_wx():
537 534 """Modifies wxPython's MainLoop with a dummy so user code does not
538 535 block IPython. The hijacked mainloop function is returned.
539 536 """
540 537 def dummy_mainloop(*args, **kw):
541 538 pass
542 539 import wxPython
543 540 ver = wxPython.__version__
544 541 orig_mainloop = None
545 542 if ver[:3] >= '2.5':
546 543 import wx
547 544 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
548 545 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
549 546 else: raise AttributeError('Could not find wx core module')
550 547 orig_mainloop = core.PyApp_MainLoop
551 548 core.PyApp_MainLoop = dummy_mainloop
552 549 elif ver[:3] == '2.4':
553 550 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
554 551 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
555 552 else:
556 553 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
557 554 return orig_mainloop
558 555
559 556 def hijack_gtk():
560 557 """Modifies pyGTK's mainloop with a dummy so user code does not
561 558 block IPython. This function returns the original `gtk.mainloop`
562 559 function that has been hijacked.
563 560 """
564 561 def dummy_mainloop(*args, **kw):
565 562 pass
566 563 import gtk
567 564 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
568 565 else: orig_mainloop = gtk.mainloop
569 566 gtk.mainloop = dummy_mainloop
570 567 gtk.main = dummy_mainloop
571 568 return orig_mainloop
572 569
573 570 #-----------------------------------------------------------------------------
574 571 # The IPShell* classes below are the ones meant to be run by external code as
575 572 # IPython instances. Note that unless a specific threading strategy is
576 573 # desired, the factory function start() below should be used instead (it
577 574 # selects the proper threaded class).
578 575
579 576 class IPShellGTK(threading.Thread):
580 577 """Run a gtk mainloop() in a separate thread.
581 578
582 579 Python commands can be passed to the thread where they will be executed.
583 580 This is implemented by periodically checking for passed code using a
584 581 GTK timeout callback."""
585 582
586 583 TIMEOUT = 100 # Millisecond interval between timeouts.
587 584
588 585 def __init__(self,argv=None,user_ns=None,debug=1,
589 586 shell_class=MTInteractiveShell):
590 587
591 588 import gtk
592 589
593 590 self.gtk = gtk
594 591 self.gtk_mainloop = hijack_gtk()
595 592
596 593 # Allows us to use both Tk and GTK.
597 594 self.tk = get_tk()
598 595
599 596 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
600 597 else: mainquit = self.gtk.mainquit
601 598
602 599 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
603 600 shell_class=shell_class,
604 601 on_kill=[mainquit])
605 602 threading.Thread.__init__(self)
606 603
607 604 def run(self):
608 605 self.IP.mainloop()
609 606 self.IP.kill()
610 607
611 608 def mainloop(self):
612 609
613 610 if self.gtk.pygtk_version >= (2,4,0):
614 611 import gobject
615 612 gobject.idle_add(self.on_timer)
616 613 else:
617 614 self.gtk.idle_add(self.on_timer)
618 615
619 616 if sys.platform != 'win32':
620 617 try:
621 618 if self.gtk.gtk_version[0] >= 2:
622 619 self.gtk.threads_init()
623 620 except AttributeError:
624 621 pass
625 622 except RuntimeError:
626 623 error('Your pyGTK likely has not been compiled with '
627 624 'threading support.\n'
628 625 'The exception printout is below.\n'
629 626 'You can either rebuild pyGTK with threads, or '
630 627 'try using \n'
631 628 'matplotlib with a different backend (like Tk or WX).\n'
632 629 'Note that matplotlib will most likely not work in its '
633 630 'current state!')
634 631 self.IP.InteractiveTB()
635 632 self.start()
636 633 self.gtk.threads_enter()
637 634 self.gtk_mainloop()
638 635 self.gtk.threads_leave()
639 636 self.join()
640 637
641 638 def on_timer(self):
642 639 update_tk(self.tk)
643 640 return self.IP.runcode()
644 641
645 642
646 643 class IPShellWX(threading.Thread):
647 644 """Run a wx mainloop() in a separate thread.
648 645
649 646 Python commands can be passed to the thread where they will be executed.
650 647 This is implemented by periodically checking for passed code using a
651 648 GTK timeout callback."""
652 649
653 650 TIMEOUT = 100 # Millisecond interval between timeouts.
654 651
655 652 def __init__(self,argv=None,user_ns=None,debug=1,
656 653 shell_class=MTInteractiveShell):
657 654
658 655 import wxPython.wx as wx
659 656
660 657 threading.Thread.__init__(self)
661 658 self.wx = wx
662 659 self.wx_mainloop = hijack_wx()
663 660
664 661 # Allows us to use both Tk and GTK.
665 662 self.tk = get_tk()
666 663
667 664 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
668 665 shell_class=shell_class,
669 666 on_kill=[self.wxexit])
670 667 self.app = None
671 668
672 669 def wxexit(self, *args):
673 670 if self.app is not None:
674 671 self.app.agent.timer.Stop()
675 672 self.app.ExitMainLoop()
676 673
677 674 def run(self):
678 675 self.IP.mainloop()
679 676 self.IP.kill()
680 677
681 678 def mainloop(self):
682 679
683 680 self.start()
684 681
685 682 class TimerAgent(self.wx.wxMiniFrame):
686 683 wx = self.wx
687 684 IP = self.IP
688 685 tk = self.tk
689 686 def __init__(self, parent, interval):
690 687 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
691 688 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
692 689 size=(100, 100),style=style)
693 690 self.Show(False)
694 691 self.interval = interval
695 692 self.timerId = self.wx.wxNewId()
696 693
697 694 def StartWork(self):
698 695 self.timer = self.wx.wxTimer(self, self.timerId)
699 696 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
700 697 self.timer.Start(self.interval)
701 698
702 699 def OnTimer(self, event):
703 700 update_tk(self.tk)
704 701 self.IP.runcode()
705 702
706 703 class App(self.wx.wxApp):
707 704 wx = self.wx
708 705 TIMEOUT = self.TIMEOUT
709 706 def OnInit(self):
710 707 'Create the main window and insert the custom frame'
711 708 self.agent = TimerAgent(None, self.TIMEOUT)
712 709 self.agent.Show(self.wx.false)
713 710 self.agent.StartWork()
714 711 return self.wx.true
715 712
716 713 self.app = App(redirect=False)
717 714 self.wx_mainloop(self.app)
718 715 self.join()
719 716
720 717
721 718 class IPShellQt(threading.Thread):
722 719 """Run a Qt event loop in a separate thread.
723 720
724 721 Python commands can be passed to the thread where they will be executed.
725 722 This is implemented by periodically checking for passed code using a
726 723 Qt timer / slot."""
727 724
728 725 TIMEOUT = 100 # Millisecond interval between timeouts.
729 726
730 727 def __init__(self,argv=None,user_ns=None,debug=0,
731 728 shell_class=MTInteractiveShell):
732 729
733 730 import qt
734 731
735 732 class newQApplication:
736 733 def __init__( self ):
737 734 self.QApplication = qt.QApplication
738 735
739 736 def __call__( *args, **kwargs ):
740 737 return qt.qApp
741 738
742 739 def exec_loop( *args, **kwargs ):
743 740 pass
744 741
745 742 def __getattr__( self, name ):
746 743 return getattr( self.QApplication, name )
747 744
748 745 qt.QApplication = newQApplication()
749 746
750 747 # Allows us to use both Tk and QT.
751 748 self.tk = get_tk()
752 749
753 750 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
754 751 shell_class=shell_class,
755 752 on_kill=[qt.qApp.exit])
756 753
757 754 threading.Thread.__init__(self)
758 755
759 756 def run(self):
760 757 #sys.excepthook = self.IP.excepthook # dbg
761 758 self.IP.mainloop()
762 759 self.IP.kill()
763 760
764 761 def mainloop(self):
765 762 import qt, sys
766 763 if qt.QApplication.startingUp():
767 764 a = qt.QApplication.QApplication( sys.argv )
768 765 self.timer = qt.QTimer()
769 766 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
770 767
771 768 self.start()
772 769 self.timer.start( self.TIMEOUT, True )
773 770 while True:
774 771 if self.IP._kill: break
775 772 qt.qApp.exec_loop()
776 773 self.join()
777 774
778 775 def on_timer(self):
779 776 update_tk(self.tk)
780 777 result = self.IP.runcode()
781 778 self.timer.start( self.TIMEOUT, True )
782 779 return result
783 780
784 781 # A set of matplotlib public IPython shell classes, for single-threaded
785 782 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
786 783 class IPShellMatplotlib(IPShell):
787 784 """Subclass IPShell with MatplotlibShell as the internal shell.
788 785
789 786 Single-threaded class, meant for the Tk* and FLTK* backends.
790 787
791 788 Having this on a separate class simplifies the external driver code."""
792 789
793 790 def __init__(self,argv=None,user_ns=None,debug=1):
794 791 IPShell.__init__(self,argv,user_ns,debug,shell_class=MatplotlibShell)
795 792
796 793 class IPShellMatplotlibGTK(IPShellGTK):
797 794 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
798 795
799 796 Multi-threaded class, meant for the GTK* backends."""
800 797
801 798 def __init__(self,argv=None,user_ns=None,debug=1):
802 799 IPShellGTK.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
803 800
804 801 class IPShellMatplotlibWX(IPShellWX):
805 802 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
806 803
807 804 Multi-threaded class, meant for the WX* backends."""
808 805
809 806 def __init__(self,argv=None,user_ns=None,debug=1):
810 807 IPShellWX.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
811 808
812 809 class IPShellMatplotlibQt(IPShellQt):
813 810 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
814 811
815 812 Multi-threaded class, meant for the Qt* backends."""
816 813
817 814 def __init__(self,argv=None,user_ns=None,debug=1):
818 815 IPShellQt.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
819 816
820 817 #-----------------------------------------------------------------------------
821 818 # Factory functions to actually start the proper thread-aware shell
822 819
823 820 def _matplotlib_shell_class():
824 821 """Factory function to handle shell class selection for matplotlib.
825 822
826 823 The proper shell class to use depends on the matplotlib backend, since
827 824 each backend requires a different threading strategy."""
828 825
829 826 try:
830 827 import matplotlib
831 828 except ImportError:
832 829 error('matplotlib could NOT be imported! Starting normal IPython.')
833 830 sh_class = IPShell
834 831 else:
835 832 backend = matplotlib.rcParams['backend']
836 833 if backend.startswith('GTK'):
837 834 sh_class = IPShellMatplotlibGTK
838 835 elif backend.startswith('WX'):
839 836 sh_class = IPShellMatplotlibWX
840 837 elif backend.startswith('Qt'):
841 838 sh_class = IPShellMatplotlibQt
842 839 else:
843 840 sh_class = IPShellMatplotlib
844 841 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
845 842 return sh_class
846 843
847 844 # This is the one which should be called by external code.
848 845 def start():
849 846 """Return a running shell instance, dealing with threading options.
850 847
851 848 This is a factory function which will instantiate the proper IPython shell
852 849 based on the user's threading choice. Such a selector is needed because
853 850 different GUI toolkits require different thread handling details."""
854 851
855 852 global USE_TK
856 853 # Crude sys.argv hack to extract the threading options.
857 854 if len(sys.argv) > 1:
858 855 if len(sys.argv) > 2:
859 856 arg2 = sys.argv[2]
860 857 if arg2.endswith('-tk'):
861 858 USE_TK = True
862 859 arg1 = sys.argv[1]
863 860 if arg1.endswith('-gthread'):
864 861 shell = IPShellGTK
865 862 elif arg1.endswith( '-qthread' ):
866 863 shell = IPShellQt
867 864 elif arg1.endswith('-wthread'):
868 865 shell = IPShellWX
869 866 elif arg1.endswith('-pylab'):
870 867 shell = _matplotlib_shell_class()
871 868 else:
872 869 shell = IPShell
873 870 else:
874 871 shell = IPShell
875 872 return shell()
876 873
877 874 # Some aliases for backwards compatibility
878 875 IPythonShell = IPShell
879 876 IPythonShellEmbed = IPShellEmbed
880 877 #************************ End of file <Shell.py> ***************************
@@ -1,550 +1,558 b''
1 1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 633 2005-07-17 01:03:15Z tzanko $
2 # $Id: ipythonrc 923 2005-11-15 08:51:15Z fperez $
3 3
4 4 #***************************************************************************
5 5 #
6 6 # Configuration file for IPython -- ipythonrc format
7 7 #
8 8 # The format of this file is simply one of 'key value' lines.
9 9 # Lines containing only whitespace at the beginning and then a # are ignored
10 10 # as comments. But comments can NOT be put on lines with data.
11 11
12 12 # The meaning and use of each key are explained below.
13 13
14 14 #---------------------------------------------------------------------------
15 15 # Section: included files
16 16
17 17 # Put one or more *config* files (with the syntax of this file) you want to
18 18 # include. For keys with a unique value the outermost file has precedence. For
19 19 # keys with multiple values, they all get assembled into a list which then
20 20 # gets loaded by IPython.
21 21
22 22 # In this file, all lists of things should simply be space-separated.
23 23
24 24 # This allows you to build hierarchies of files which recursively load
25 25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
26 26 # should only keep here basic things you always want available. Then you can
27 27 # include it in every other special-purpose config file you create.
28 28 include
29 29
30 30 #---------------------------------------------------------------------------
31 31 # Section: startup setup
32 32
33 33 # These are mostly things which parallel a command line option of the same
34 34 # name.
35 35
36 36 # Keys in this section should only appear once. If any key from this section
37 37 # is encountered more than once, the last value remains, all earlier ones get
38 38 # discarded.
39 39
40 40 # Automatic calling of callable objects. If set to true, callable objects are
41 41 # automatically called when invoked at the command line, even if you don't
42 42 # type parentheses. IPython adds the parentheses for you. For example:
43 43
44 44 #In [1]: str 45
45 45 #------> str(45)
46 46 #Out[1]: '45'
47 47
48 48 # IPython reprints your line with '---->' indicating that it added
49 49 # parentheses. While this option is very convenient for interactive use, it
50 50 # may occasionally cause problems with objects which have side-effects if
51 51 # called unexpectedly. Set it to 0 if you want to disable it.
52 52
53 53 # Note that even with autocall off, you can still use '/' at the start of a
54 54 # line to treat the first argument on the command line as a function and add
55 55 # parentheses to it:
56 56
57 57 #In [8]: /str 43
58 58 #------> str(43)
59 59 #Out[8]: '43'
60 60
61 61 autocall 1
62 62
63 63 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
64 64 # line, while also un-indenting automatically after 'raise' or 'return'.
65 65
66 66 # This feature uses the readline library, so it will honor your ~/.inputrc
67 67 # configuration (or whatever file your INPUTRC variable points to). Adding
68 68 # the following lines to your .inputrc file can make indent/unindenting more
69 69 # convenient (M-i indents, M-u unindents):
70 70
71 71 # $if Python
72 72 # "\M-i": " "
73 73 # "\M-u": "\d\d\d\d"
74 74 # $endif
75 75
76 76 # The feature is potentially a bit dangerous, because it can cause problems
77 77 # with pasting of indented code (the pasted code gets re-indented on each
78 78 # line). But it's a huge time-saver when working interactively. The magic
79 79 # function @autoindent allows you to toggle it on/off at runtime.
80 80
81 81 autoindent 1
82 82
83 83 # Auto-magic. This gives you access to all the magic functions without having
84 84 # to prepend them with an @ sign. If you define a variable with the same name
85 85 # as a magic function (say who=1), you will need to access the magic function
86 86 # with @ (@who in this example). However, if later you delete your variable
87 87 # (del who), you'll recover the automagic calling form.
88 88
89 89 # Considering that many magic functions provide a lot of shell-like
90 90 # functionality, automagic gives you something close to a full Python+system
91 91 # shell environment (and you can extend it further if you want).
92 92
93 93 automagic 1
94 94
95 95 # Size of the output cache. After this many entries are stored, the cache will
96 96 # get flushed. Depending on the size of your intermediate calculations, you
97 97 # may have memory problems if you make it too big, since keeping things in the
98 98 # cache prevents Python from reclaiming the memory for old results. Experiment
99 99 # with a value that works well for you.
100 100
101 101 # If you choose cache_size 0 IPython will revert to python's regular >>>
102 102 # unnumbered prompt. You will still have _, __ and ___ for your last three
103 103 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
104 104 # you are running on a slow machine or with very limited memory, this may
105 105 # help.
106 106
107 107 cache_size 1000
108 108
109 109 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
110 110 # but that's your choice! Classic 1 -> same as IPython -classic.
111 111 # Note that this is _not_ the normal python interpreter, it's simply
112 112 # IPython emulating most of the classic interpreter's behavior.
113 113 classic 0
114 114
115 115 # colors - Coloring option for prompts and traceback printouts.
116 116
117 117 # Currently available schemes: NoColor, Linux, LightBG.
118 118
119 119 # This option allows coloring the prompts and traceback printouts. This
120 120 # requires a terminal which can properly handle color escape sequences. If you
121 121 # are having problems with this, use the NoColor scheme (uses no color escapes
122 122 # at all).
123 123
124 124 # The Linux option works well in linux console type environments: dark
125 125 # background with light fonts.
126 126
127 127 # LightBG is similar to Linux but swaps dark/light colors to be more readable
128 128 # in light background terminals.
129 129
130 130 # keep uncommented only the one you want:
131 131 colors Linux
132 132 #colors LightBG
133 133 #colors NoColor
134 134
135 135 ########################
136 136 # Note to Windows users
137 137 #
138 138 # Color and readline support is avaialble to Windows users via Gary Bishop's
139 139 # readline library. You can find Gary's tools at
140 140 # http://sourceforge.net/projects/uncpythontools.
141 141 # Note that his readline module requires in turn the ctypes library, available
142 142 # at http://starship.python.net/crew/theller/ctypes.
143 143 ########################
144 144
145 145 # color_info: IPython can display information about objects via a set of
146 146 # functions, and optionally can use colors for this, syntax highlighting
147 147 # source code and various other elements. This information is passed through a
148 148 # pager (it defaults to 'less' if $PAGER is not set).
149 149
150 150 # If your pager has problems, try to setting it to properly handle escapes
151 151 # (see the less manpage for detail), or disable this option. The magic
152 152 # function @color_info allows you to toggle this interactively for testing.
153 153
154 154 color_info 1
155 155
156 156 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
157 157 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
158 158 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
159 159 # any confirmation.
160 160
161 161 confirm_exit 1
162 162
163 163 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
164 164 # still available as dreload() and appears as a builtin.
165 165
166 166 deep_reload 0
167 167
168 168 # Which editor to use with the @edit command. If you leave this at 0, IPython
169 169 # will honor your EDITOR environment variable. Since this editor is invoked on
170 170 # the fly by ipython and is meant for editing small code snippets, you may
171 171 # want to use a small, lightweight editor here.
172 172
173 173 # For Emacs users, setting up your Emacs server properly as described in the
174 174 # manual is a good idea. An alternative is to use jed, a very light editor
175 175 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
176 176
177 177 editor 0
178 178
179 179 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
180 180 log 0
181 181
182 182 # Same as ipython -Logfile YourLogfileName.
183 183 # Don't use with log 1 (use one or the other)
184 184 logfile ''
185 185
186 186 # banner 0 -> same as ipython -nobanner
187 187 banner 1
188 188
189 189 # messages 0 -> same as ipython -nomessages
190 190 messages 1
191 191
192 192 # Automatically call the pdb debugger after every uncaught exception. If you
193 193 # are used to debugging using pdb, this puts you automatically inside of it
194 194 # after any call (either in IPython or in code called by it) which triggers an
195 195 # exception which goes uncaught.
196 196 pdb 0
197 197
198 198 # Enable the pprint module for printing. pprint tends to give a more readable
199 199 # display (than print) for complex nested data structures.
200 200 pprint 1
201 201
202 202 # Prompt strings
203 203
204 204 # Most bash-like escapes can be used to customize IPython's prompts, as well as
205 205 # a few additional ones which are IPython-specific. All valid prompt escapes
206 206 # are described in detail in the Customization section of the IPython HTML/PDF
207 207 # manual.
208 208
209 209 # Use \# to represent the current prompt number, and quote them to protect
210 210 # spaces.
211 211 prompt_in1 'In [\#]: '
212 212
213 213 # \D is replaced by as many dots as there are digits in the
214 214 # current value of \#.
215 215 prompt_in2 ' .\D.: '
216 216
217 217 prompt_out 'Out[\#]: '
218 218
219 219 # Select whether to left-pad the output prompts to match the length of the
220 220 # input ones. This allows you for example to use a simple '>' as an output
221 221 # prompt, and yet have the output line up with the input. If set to false,
222 222 # the output prompts will be unpadded (flush left).
223 223 prompts_pad_left 1
224 224
225 225 # quick 1 -> same as ipython -quick
226 226 quick 0
227 227
228 228 # Use the readline library (1) or not (0). Most users will want this on, but
229 229 # if you experience strange problems with line management (mainly when using
230 230 # IPython inside Emacs buffers) you may try disabling it. Not having it on
231 231 # prevents you from getting command history with the arrow keys, searching and
232 232 # name completion using TAB.
233 233
234 234 readline 1
235 235
236 236 # Screen Length: number of lines of your screen. This is used to control
237 237 # printing of very long strings. Strings longer than this number of lines will
238 238 # be paged with the less command instead of directly printed.
239 239
240 240 # The default value for this is 0, which means IPython will auto-detect your
241 241 # screen size every time it needs to print. If for some reason this isn't
242 242 # working well (it needs curses support), specify it yourself. Otherwise don't
243 243 # change the default.
244 244
245 245 screen_length 0
246 246
247 247 # Prompt separators for input and output.
248 248 # Use \n for newline explicitly, without quotes.
249 249 # Use 0 (like at the cmd line) to turn off a given separator.
250 250
251 251 # The structure of prompt printing is:
252 252 # (SeparateIn)Input....
253 253 # (SeparateOut)Output...
254 254 # (SeparateOut2), # that is, no newline is printed after Out2
255 255 # By choosing these you can organize your output any way you want.
256 256
257 257 separate_in \n
258 258 separate_out 0
259 259 separate_out2 0
260 260
261 261 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
262 262 # Simply removes all input/output separators, overriding the choices above.
263 263 nosep 0
264 264
265 # Wildcard searches - IPython has a system for searching names using
266 # shell-like wildcards; type %psearch? for details. This variables sets
267 # whether by default such searches should be case sensitive or not. You can
268 # always override the default at the system command line or the IPython
269 # prompt.
270
271 wildcards_case_sensitive 1
272
265 273 # xmode - Exception reporting mode.
266 274
267 275 # Valid modes: Plain, Context and Verbose.
268 276
269 277 # Plain: similar to python's normal traceback printing.
270 278
271 279 # Context: prints 5 lines of context source code around each line in the
272 280 # traceback.
273 281
274 282 # Verbose: similar to Context, but additionally prints the variables currently
275 283 # visible where the exception happened (shortening their strings if too
276 284 # long). This can potentially be very slow, if you happen to have a huge data
277 285 # structure whose string representation is complex to compute. Your computer
278 286 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
279 287 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
280 288
281 289 #xmode Plain
282 290 xmode Context
283 291 #xmode Verbose
284 292
285 293 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
286 294 # !cmd) to be used in multi-line input (like for loops). For example, if you
287 295 # have this active, the following is valid in IPython:
288 296 #
289 297 #In [17]: for i in range(3):
290 298 # ....: mkdir $i
291 299 # ....: !touch $i/hello
292 300 # ....: ls -l $i
293 301
294 302 multi_line_specials 1
295 303
296 304 #---------------------------------------------------------------------------
297 305 # Section: Readline configuration (readline is not available for MS-Windows)
298 306
299 307 # This is done via the following options:
300 308
301 309 # (i) readline_parse_and_bind: this option can appear as many times as you
302 310 # want, each time defining a string to be executed via a
303 311 # readline.parse_and_bind() command. The syntax for valid commands of this
304 312 # kind can be found by reading the documentation for the GNU readline library,
305 313 # as these commands are of the kind which readline accepts in its
306 314 # configuration file.
307 315
308 316 # The TAB key can be used to complete names at the command line in one of two
309 317 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
310 318 # completes as much as possible while 'menu-complete' cycles through all
311 319 # possible completions. Leave the one you prefer uncommented.
312 320
313 321 readline_parse_and_bind tab: complete
314 322 #readline_parse_and_bind tab: menu-complete
315 323
316 324 # This binds Control-l to printing the list of all possible completions when
317 325 # there is more than one (what 'complete' does when hitting TAB twice, or at
318 326 # the first TAB if show-all-if-ambiguous is on)
319 327 readline_parse_and_bind "\C-l": possible-completions
320 328
321 329 # This forces readline to automatically print the above list when tab
322 330 # completion is set to 'complete'. You can still get this list manually by
323 331 # using the key bound to 'possible-completions' (Control-l by default) or by
324 332 # hitting TAB twice. Turning this on makes the printing happen at the first
325 333 # TAB.
326 334 readline_parse_and_bind set show-all-if-ambiguous on
327 335
328 336 # If you have TAB set to complete names, you can rebind any key (Control-o by
329 337 # default) to insert a true TAB character.
330 338 readline_parse_and_bind "\C-o": tab-insert
331 339
332 340 # These commands allow you to indent/unindent easily, with the 4-space
333 341 # convention of the Python coding standards. Since IPython's internal
334 342 # auto-indent system also uses 4 spaces, you should not change the number of
335 343 # spaces in the code below.
336 344 readline_parse_and_bind "\M-i": " "
337 345 readline_parse_and_bind "\M-o": "\d\d\d\d"
338 346 readline_parse_and_bind "\M-I": "\d\d\d\d"
339 347
340 348 # Bindings for incremental searches in the history. These searches use the
341 349 # string typed so far on the command line and search anything in the previous
342 350 # input history containing them.
343 351 readline_parse_and_bind "\C-r": reverse-search-history
344 352 readline_parse_and_bind "\C-s": forward-search-history
345 353
346 354 # Bindings for completing the current line in the history of previous
347 355 # commands. This allows you to recall any previous command by typing its first
348 356 # few letters and hitting Control-p, bypassing all intermediate commands which
349 357 # may be in the history (much faster than hitting up-arrow 50 times!)
350 358 readline_parse_and_bind "\C-p": history-search-backward
351 359 readline_parse_and_bind "\C-n": history-search-forward
352 360
353 361 # I also like to have the same functionality on the plain arrow keys. If you'd
354 362 # rather have the arrows use all the history (and not just match what you've
355 363 # typed so far), comment out or delete the next two lines.
356 364 readline_parse_and_bind "\e[A": history-search-backward
357 365 readline_parse_and_bind "\e[B": history-search-forward
358 366
359 367 # These are typically on by default under *nix, but not win32.
360 368 readline_parse_and_bind "\C-k": kill-line
361 369 readline_parse_and_bind "\C-u": unix-line-discard
362 370
363 371 # (ii) readline_remove_delims: a string of characters to be removed from the
364 372 # default word-delimiters list used by readline, so that completions may be
365 373 # performed on strings which contain them.
366 374
367 375 readline_remove_delims -/~
368 376
369 377 # (iii) readline_merge_completions: whether to merge the result of all
370 378 # possible completions or not. If true, IPython will complete filenames,
371 379 # python names and aliases and return all possible completions. If you set it
372 380 # to false, each completer is used at a time, and only if it doesn't return
373 381 # any completions is the next one used.
374 382
375 383 # The default order is: [python_matches, file_matches, alias_matches]
376 384
377 385 readline_merge_completions 1
378 386
379 387 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
380 388 # will complete all attributes of an object, including all the special methods
381 389 # whose names start with single or double underscores (like __getitem__ or
382 390 # __class__).
383 391
384 392 # This variable allows you to control this completion behavior:
385 393
386 394 # readline_omit__names 1 -> completion will omit showing any names starting
387 395 # with two __, but it will still show names starting with one _.
388 396
389 397 # readline_omit__names 2 -> completion will omit all names beginning with one
390 398 # _ (which obviously means filtering out the double __ ones).
391 399
392 400 # Even when this option is set, you can still see those names by explicitly
393 401 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
394 402 # complete attribute names starting with '_'.
395 403
396 404 # This option is off by default so that new users see all attributes of any
397 405 # objects they are dealing with.
398 406
399 407 readline_omit__names 0
400 408
401 409 #---------------------------------------------------------------------------
402 410 # Section: modules to be loaded with 'import ...'
403 411
404 412 # List, separated by spaces, the names of the modules you want to import
405 413
406 414 # Example:
407 415 # import_mod sys os
408 416 # will produce internally the statements
409 417 # import sys
410 418 # import os
411 419
412 420 # Each import is executed in its own try/except block, so if one module
413 421 # fails to load the others will still be ok.
414 422
415 423 import_mod
416 424
417 425 #---------------------------------------------------------------------------
418 426 # Section: modules to import some functions from: 'from ... import ...'
419 427
420 428 # List, one per line, the modules for which you want only to import some
421 429 # functions. Give the module name first and then the name of functions to be
422 430 # imported from that module.
423 431
424 432 # Example:
425 433
426 434 # import_some IPython.genutils timing timings
427 435 # will produce internally the statement
428 436 # from IPython.genutils import timing, timings
429 437
430 438 # timing() and timings() are two IPython utilities for timing the execution of
431 439 # your own functions, which you may find useful. Just commment out the above
432 440 # line if you want to test them.
433 441
434 442 # If you have more than one modules_some line, each gets its own try/except
435 443 # block (like modules, see above).
436 444
437 445 import_some
438 446
439 447 #---------------------------------------------------------------------------
440 448 # Section: modules to import all from : 'from ... import *'
441 449
442 450 # List (same syntax as import_mod above) those modules for which you want to
443 451 # import all functions. Remember, this is a potentially dangerous thing to do,
444 452 # since it is very easy to overwrite names of things you need. Use with
445 453 # caution.
446 454
447 455 # Example:
448 456 # import_all sys os
449 457 # will produce internally the statements
450 458 # from sys import *
451 459 # from os import *
452 460
453 461 # As before, each will be called in a separate try/except block.
454 462
455 463 import_all
456 464
457 465 #---------------------------------------------------------------------------
458 466 # Section: Python code to execute.
459 467
460 468 # Put here code to be explicitly executed (keep it simple!)
461 469 # Put one line of python code per line. All whitespace is removed (this is a
462 470 # feature, not a bug), so don't get fancy building loops here.
463 471 # This is just for quick convenient creation of things you want available.
464 472
465 473 # Example:
466 474 # execute x = 1
467 475 # execute print 'hello world'; y = z = 'a'
468 476 # will produce internally
469 477 # x = 1
470 478 # print 'hello world'; y = z = 'a'
471 479 # and each *line* (not each statement, we don't do python syntax parsing) is
472 480 # executed in its own try/except block.
473 481
474 482 execute
475 483
476 484 # Note for the adventurous: you can use this to define your own names for the
477 485 # magic functions, by playing some namespace tricks:
478 486
479 487 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
480 488
481 489 # defines @pf as a new name for @profile.
482 490
483 491 #---------------------------------------------------------------------------
484 492 # Section: Pyhton files to load and execute.
485 493
486 494 # Put here the full names of files you want executed with execfile(file). If
487 495 # you want complicated initialization, just write whatever you want in a
488 496 # regular python file and load it from here.
489 497
490 498 # Filenames defined here (which *must* include the extension) are searched for
491 499 # through all of sys.path. Since IPython adds your .ipython directory to
492 500 # sys.path, they can also be placed in your .ipython dir and will be
493 501 # found. Otherwise (if you want to execute things not in .ipyton nor in
494 502 # sys.path) give a full path (you can use ~, it gets expanded)
495 503
496 504 # Example:
497 505 # execfile file1.py ~/file2.py
498 506 # will generate
499 507 # execfile('file1.py')
500 508 # execfile('_path_to_your_home/file2.py')
501 509
502 510 # As before, each file gets its own try/except block.
503 511
504 512 execfile
505 513
506 514 # If you are feeling adventurous, you can even add functionality to IPython
507 515 # through here. IPython works through a global variable called __ip which
508 516 # exists at the time when these files are read. If you know what you are doing
509 517 # (read the source) you can add functions to __ip in files loaded here.
510 518
511 519 # The file example-magic.py contains a simple but correct example. Try it:
512 520
513 521 # execfile example-magic.py
514 522
515 523 # Look at the examples in IPython/iplib.py for more details on how these magic
516 524 # functions need to process their arguments.
517 525
518 526 #---------------------------------------------------------------------------
519 527 # Section: aliases for system shell commands
520 528
521 529 # Here you can define your own names for system commands. The syntax is
522 530 # similar to that of the builtin @alias function:
523 531
524 532 # alias alias_name command_string
525 533
526 534 # The resulting aliases are auto-generated magic functions (hence usable as
527 535 # @alias_name)
528 536
529 537 # For example:
530 538
531 539 # alias myls ls -la
532 540
533 541 # will define 'myls' as an alias for executing the system command 'ls -la'.
534 542 # This allows you to customize IPython's environment to have the same aliases
535 543 # you are accustomed to from your own shell.
536 544
537 545 # You can also define aliases with parameters using %s specifiers (one per
538 546 # parameter):
539 547
540 548 # alias parts echo first %s second %s
541 549
542 550 # will give you in IPython:
543 551 # >>> @parts A B
544 552 # first A second B
545 553
546 554 # Use one 'alias' statement per alias you wish to define.
547 555
548 556 # alias
549 557
550 558 #************************* end of file <ipythonrc> ************************
@@ -1,2062 +1,2098 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 921 2005-11-13 06:51:34Z fperez $
9 $Id: iplib.py 923 2005-11-15 08:51:15Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, much of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. The Python License (sec. 2) allows for this, but it's always
23 23 # nice to acknowledge credit where credit is due.
24 24 #*****************************************************************************
25 25
26 26 #****************************************************************************
27 27 # Modules and globals
28 28
29 29 from __future__ import generators # for 2.2 backwards-compatibility
30 30
31 31 from IPython import Release
32 32 __author__ = '%s <%s>\n%s <%s>' % \
33 33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 34 __license__ = Release.license
35 35 __version__ = Release.version
36 36
37 37 # Python standard modules
38 38 import __main__
39 39 import __builtin__
40 40 import exceptions
41 41 import keyword
42 42 import new
43 43 import os, sys, shutil
44 44 import code, glob, types, re
45 45 import string, StringIO
46 46 import inspect, pydoc
47 47 import bdb, pdb
48 48 import UserList # don't subclass list so this works with Python2.1
49 49 from pprint import pprint, pformat
50 50 import cPickle as pickle
51 51 import traceback
52 52 from codeop import CommandCompiler
53 53
54 54 # IPython's own modules
55 55 import IPython
56 56 from IPython import OInspect,PyColorize,ultraTB
57 57 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
58 58 from IPython.Logger import Logger
59 59 from IPython.Magic import Magic,magic2python,shlex_split
60 60 from IPython.usage import cmd_line_usage,interactive_usage
61 61 from IPython.Struct import Struct
62 62 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
63 63 from IPython.FakeModule import FakeModule
64 64 from IPython.background_jobs import BackgroundJobManager
65 65 from IPython.PyColorize import Parser
66 66 from IPython.genutils import *
67 67
68 68 # Global pointer to the running
69 69
70 70 # store the builtin raw_input globally, and use this always, in case user code
71 71 # overwrites it (like wx.py.PyShell does)
72 72 raw_input_original = raw_input
73 73
74 74 #****************************************************************************
75 75 # Some utility function definitions
76 76
77 77 class Bunch: pass
78 78
79 79 def esc_quotes(strng):
80 80 """Return the input string with single and double quotes escaped out"""
81 81
82 82 return strng.replace('"','\\"').replace("'","\\'")
83 83
84 84 def import_fail_info(mod_name,fns=None):
85 85 """Inform load failure for a module."""
86 86
87 87 if fns == None:
88 88 warn("Loading of %s failed.\n" % (mod_name,))
89 89 else:
90 90 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
91 91
92 92 def qw_lol(indata):
93 93 """qw_lol('a b') -> [['a','b']],
94 94 otherwise it's just a call to qw().
95 95
96 96 We need this to make sure the modules_some keys *always* end up as a
97 97 list of lists."""
98 98
99 99 if type(indata) in StringTypes:
100 100 return [qw(indata)]
101 101 else:
102 102 return qw(indata)
103 103
104 104 def ipmagic(arg_s):
105 105 """Call a magic function by name.
106 106
107 107 Input: a string containing the name of the magic function to call and any
108 108 additional arguments to be passed to the magic.
109 109
110 110 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
111 111 prompt:
112 112
113 113 In[1]: %name -opt foo bar
114 114
115 115 To call a magic without arguments, simply use ipmagic('name').
116 116
117 117 This provides a proper Python function to call IPython's magics in any
118 118 valid Python code you can type at the interpreter, including loops and
119 119 compound statements. It is added by IPython to the Python builtin
120 120 namespace upon initialization."""
121 121
122 122 args = arg_s.split(' ',1)
123 123 magic_name = args[0]
124 124 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
125 125 magic_name = magic_name[1:]
126 126 try:
127 127 magic_args = args[1]
128 128 except IndexError:
129 129 magic_args = ''
130 130 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
131 131 if fn is None:
132 132 error("Magic function `%s` not found." % magic_name)
133 133 else:
134 134 magic_args = __IPYTHON__.var_expand(magic_args)
135 135 return fn(magic_args)
136 136
137 137 def ipalias(arg_s):
138 138 """Call an alias by name.
139 139
140 140 Input: a string containing the name of the alias to call and any
141 141 additional arguments to be passed to the magic.
142 142
143 143 ipalias('name -opt foo bar') is equivalent to typing at the ipython
144 144 prompt:
145 145
146 146 In[1]: name -opt foo bar
147 147
148 148 To call an alias without arguments, simply use ipalias('name').
149 149
150 150 This provides a proper Python function to call IPython's aliases in any
151 151 valid Python code you can type at the interpreter, including loops and
152 152 compound statements. It is added by IPython to the Python builtin
153 153 namespace upon initialization."""
154 154
155 155 args = arg_s.split(' ',1)
156 156 alias_name = args[0]
157 157 try:
158 158 alias_args = args[1]
159 159 except IndexError:
160 160 alias_args = ''
161 161 if alias_name in __IPYTHON__.alias_table:
162 162 __IPYTHON__.call_alias(alias_name,alias_args)
163 163 else:
164 164 error("Alias `%s` not found." % alias_name)
165 165
166 166 #-----------------------------------------------------------------------------
167 167 # Local use classes
168 168 try:
169 169 from IPython import FlexCompleter
170 170
171 171 class MagicCompleter(FlexCompleter.Completer):
172 172 """Extension of the completer class to work on %-prefixed lines."""
173 173
174 174 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
175 175 """MagicCompleter() -> completer
176 176
177 177 Return a completer object suitable for use by the readline library
178 178 via readline.set_completer().
179 179
180 180 Inputs:
181 181
182 182 - shell: a pointer to the ipython shell itself. This is needed
183 183 because this completer knows about magic functions, and those can
184 184 only be accessed via the ipython instance.
185 185
186 186 - namespace: an optional dict where completions are performed.
187 187
188 188 - The optional omit__names parameter sets the completer to omit the
189 189 'magic' names (__magicname__) for python objects unless the text
190 190 to be completed explicitly starts with one or more underscores.
191 191
192 192 - If alias_table is supplied, it should be a dictionary of aliases
193 193 to complete. """
194 194
195 195 FlexCompleter.Completer.__init__(self,namespace)
196 196 self.magic_prefix = shell.name+'.magic_'
197 197 self.magic_escape = shell.ESC_MAGIC
198 198 self.readline = FlexCompleter.readline
199 199 delims = self.readline.get_completer_delims()
200 200 delims = delims.replace(self.magic_escape,'')
201 201 self.readline.set_completer_delims(delims)
202 202 self.get_line_buffer = self.readline.get_line_buffer
203 203 self.omit__names = omit__names
204 204 self.merge_completions = shell.rc.readline_merge_completions
205 205
206 206 if alias_table is None:
207 207 alias_table = {}
208 208 self.alias_table = alias_table
209 209 # Regexp to split filenames with spaces in them
210 210 self.space_name_re = re.compile(r'([^\\] )')
211 211 # Hold a local ref. to glob.glob for speed
212 212 self.glob = glob.glob
213 213 # Special handling of backslashes needed in win32 platforms
214 214 if sys.platform == "win32":
215 215 self.clean_glob = self._clean_glob_win32
216 216 else:
217 217 self.clean_glob = self._clean_glob
218 218 self.matchers = [self.python_matches,
219 219 self.file_matches,
220 220 self.alias_matches,
221 221 self.python_func_kw_matches]
222 222
223 223 # Code contributed by Alex Schmolck, for ipython/emacs integration
224 224 def all_completions(self, text):
225 225 """Return all possible completions for the benefit of emacs."""
226 226
227 227 completions = []
228 228 try:
229 229 for i in xrange(sys.maxint):
230 230 res = self.complete(text, i)
231 231
232 232 if not res: break
233 233
234 234 completions.append(res)
235 235 #XXX workaround for ``notDefined.<tab>``
236 236 except NameError:
237 237 pass
238 238 return completions
239 239 # /end Alex Schmolck code.
240 240
241 241 def _clean_glob(self,text):
242 242 return self.glob("%s*" % text)
243 243
244 244 def _clean_glob_win32(self,text):
245 245 return [f.replace("\\","/")
246 246 for f in self.glob("%s*" % text)]
247 247
248 248 def file_matches(self, text):
249 249 """Match filneames, expanding ~USER type strings.
250 250
251 251 Most of the seemingly convoluted logic in this completer is an
252 252 attempt to handle filenames with spaces in them. And yet it's not
253 253 quite perfect, because Python's readline doesn't expose all of the
254 254 GNU readline details needed for this to be done correctly.
255 255
256 256 For a filename with a space in it, the printed completions will be
257 257 only the parts after what's already been typed (instead of the
258 258 full completions, as is normally done). I don't think with the
259 259 current (as of Python 2.3) Python readline it's possible to do
260 260 better."""
261 261
262 262 #print 'Completer->file_matches: <%s>' % text # dbg
263 263
264 264 # chars that require escaping with backslash - i.e. chars
265 265 # that readline treats incorrectly as delimiters, but we
266 266 # don't want to treat as delimiters in filename matching
267 267 # when escaped with backslash
268 268
269 269 protectables = ' ()[]{}'
270 270
271 271 def protect_filename(s):
272 272 return "".join([(ch in protectables and '\\' + ch or ch)
273 273 for ch in s])
274 274
275 275 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
276 276 open_quotes = 0 # track strings with open quotes
277 277 try:
278 278 lsplit = shlex_split(lbuf)[-1]
279 279 except ValueError:
280 280 # typically an unmatched ", or backslash without escaped char.
281 281 if lbuf.count('"')==1:
282 282 open_quotes = 1
283 283 lsplit = lbuf.split('"')[-1]
284 284 elif lbuf.count("'")==1:
285 285 open_quotes = 1
286 286 lsplit = lbuf.split("'")[-1]
287 287 else:
288 288 return None
289 289 except IndexError:
290 290 # tab pressed on empty line
291 291 lsplit = ""
292 292
293 293 if lsplit != protect_filename(lsplit):
294 294 # if protectables are found, do matching on the whole escaped
295 295 # name
296 296 has_protectables = 1
297 297 text0,text = text,lsplit
298 298 else:
299 299 has_protectables = 0
300 300 text = os.path.expanduser(text)
301 301
302 302 if text == "":
303 303 return [protect_filename(f) for f in self.glob("*")]
304 304
305 305 m0 = self.clean_glob(text.replace('\\',''))
306 306 if has_protectables:
307 307 # If we had protectables, we need to revert our changes to the
308 308 # beginning of filename so that we don't double-write the part
309 309 # of the filename we have so far
310 310 len_lsplit = len(lsplit)
311 311 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
312 312 else:
313 313 if open_quotes:
314 314 # if we have a string with an open quote, we don't need to
315 315 # protect the names at all (and we _shouldn't_, as it
316 316 # would cause bugs when the filesystem call is made).
317 317 matches = m0
318 318 else:
319 319 matches = [protect_filename(f) for f in m0]
320 320 if len(matches) == 1 and os.path.isdir(matches[0]):
321 321 # Takes care of links to directories also. Use '/'
322 322 # explicitly, even under Windows, so that name completions
323 323 # don't end up escaped.
324 324 matches[0] += '/'
325 325 return matches
326 326
327 327 def alias_matches(self, text):
328 328 """Match internal system aliases"""
329 329 #print 'Completer->alias_matches:',text # dbg
330 330 text = os.path.expanduser(text)
331 331 aliases = self.alias_table.keys()
332 332 if text == "":
333 333 return aliases
334 334 else:
335 335 return [alias for alias in aliases if alias.startswith(text)]
336 336
337 337 def python_matches(self,text):
338 338 """Match attributes or global python names"""
339 339 #print 'Completer->python_matches' # dbg
340 340 if "." in text:
341 341 try:
342 342 matches = self.attr_matches(text)
343 343 if text.endswith('.') and self.omit__names:
344 344 if self.omit__names == 1:
345 345 # true if txt is _not_ a __ name, false otherwise:
346 346 no__name = (lambda txt:
347 347 re.match(r'.*\.__.*?__',txt) is None)
348 348 else:
349 349 # true if txt is _not_ a _ name, false otherwise:
350 350 no__name = (lambda txt:
351 351 re.match(r'.*\._.*?',txt) is None)
352 352 matches = filter(no__name, matches)
353 353 except NameError:
354 354 # catches <undefined attributes>.<tab>
355 355 matches = []
356 356 else:
357 357 matches = self.global_matches(text)
358 358 # this is so completion finds magics when automagic is on:
359 359 if matches == [] and not text.startswith(os.sep):
360 360 matches = self.attr_matches(self.magic_prefix+text)
361 361 return matches
362 362
363 363 def _default_arguments(self, obj):
364 364 """Return the list of default arguments of obj if it is callable,
365 365 or empty list otherwise."""
366 366
367 367 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
368 368 # for classes, check for __init__,__new__
369 369 if inspect.isclass(obj):
370 370 obj = (getattr(obj,'__init__',None) or
371 371 getattr(obj,'__new__',None))
372 372 # for all others, check if they are __call__able
373 373 elif hasattr(obj, '__call__'):
374 374 obj = obj.__call__
375 375 # XXX: is there a way to handle the builtins ?
376 376 try:
377 377 args,_,_1,defaults = inspect.getargspec(obj)
378 378 if defaults:
379 379 return args[-len(defaults):]
380 380 except TypeError: pass
381 381 return []
382 382
383 383 def python_func_kw_matches(self,text):
384 384 """Match named parameters (kwargs) of the last open function"""
385 385
386 386 if "." in text: # a parameter cannot be dotted
387 387 return []
388 388 try: regexp = self.__funcParamsRegex
389 389 except AttributeError:
390 390 regexp = self.__funcParamsRegex = re.compile(r'''
391 391 '.*?' | # single quoted strings or
392 392 ".*?" | # double quoted strings or
393 393 \w+ | # identifier
394 394 \S # other characters
395 395 ''', re.VERBOSE | re.DOTALL)
396 396 # 1. find the nearest identifier that comes before an unclosed
397 397 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
398 398 tokens = regexp.findall(self.get_line_buffer())
399 399 tokens.reverse()
400 400 iterTokens = iter(tokens); openPar = 0
401 401 for token in iterTokens:
402 402 if token == ')':
403 403 openPar -= 1
404 404 elif token == '(':
405 405 openPar += 1
406 406 if openPar > 0:
407 407 # found the last unclosed parenthesis
408 408 break
409 409 else:
410 410 return []
411 411 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
412 412 ids = []
413 413 isId = re.compile(r'\w+$').match
414 414 while True:
415 415 try:
416 416 ids.append(iterTokens.next())
417 417 if not isId(ids[-1]):
418 418 ids.pop(); break
419 419 if not iterTokens.next() == '.':
420 420 break
421 421 except StopIteration:
422 422 break
423 423 # lookup the candidate callable matches either using global_matches
424 424 # or attr_matches for dotted names
425 425 if len(ids) == 1:
426 426 callableMatches = self.global_matches(ids[0])
427 427 else:
428 428 callableMatches = self.attr_matches('.'.join(ids[::-1]))
429 429 argMatches = []
430 430 for callableMatch in callableMatches:
431 431 try: namedArgs = self._default_arguments(eval(callableMatch,
432 432 self.namespace))
433 433 except: continue
434 434 for namedArg in namedArgs:
435 435 if namedArg.startswith(text):
436 436 argMatches.append("%s=" %namedArg)
437 437 return argMatches
438 438
439 439 def complete(self, text, state):
440 440 """Return the next possible completion for 'text'.
441 441
442 442 This is called successively with state == 0, 1, 2, ... until it
443 443 returns None. The completion should begin with 'text'. """
444 444
445 445 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
446 446 magic_escape = self.magic_escape
447 447 magic_prefix = self.magic_prefix
448 448
449 449 try:
450 450 if text.startswith(magic_escape):
451 451 text = text.replace(magic_escape,magic_prefix)
452 452 elif text.startswith('~'):
453 453 text = os.path.expanduser(text)
454 454 if state == 0:
455 455 # Extend the list of completions with the results of each
456 456 # matcher, so we return results to the user from all
457 457 # namespaces.
458 458 if self.merge_completions:
459 459 self.matches = []
460 460 for matcher in self.matchers:
461 461 self.matches.extend(matcher(text))
462 462 else:
463 463 for matcher in self.matchers:
464 464 self.matches = matcher(text)
465 465 if self.matches:
466 466 break
467 467
468 468 try:
469 469 return self.matches[state].replace(magic_prefix,magic_escape)
470 470 except IndexError:
471 471 return None
472 472 except:
473 473 # If completion fails, don't annoy the user.
474 474 pass
475 475
476 476 except ImportError:
477 477 pass # no readline support
478 478
479 479 except KeyError:
480 480 pass # Windows doesn't set TERM, it doesn't matter
481 481
482 482
483 483 class InputList(UserList.UserList):
484 484 """Class to store user input.
485 485
486 486 It's basically a list, but slices return a string instead of a list, thus
487 487 allowing things like (assuming 'In' is an instance):
488 488
489 489 exec In[4:7]
490 490
491 491 or
492 492
493 493 exec In[5:9] + In[14] + In[21:25]"""
494 494
495 495 def __getslice__(self,i,j):
496 496 return ''.join(UserList.UserList.__getslice__(self,i,j))
497 497
498 498 #****************************************************************************
499 499 # Local use exceptions
500 500 class SpaceInInput(exceptions.Exception):
501 501 pass
502 502
503 503 #****************************************************************************
504 504 # Main IPython class
505 505
506 506 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
507 507 """An enhanced console for Python."""
508 508
509 509 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
510 510 user_ns = None,user_global_ns=None,banner2='',
511 custom_exceptions=((),None)):
511 custom_exceptions=((),None),embedded=False):
512 512
513 513 # Put a reference to self in builtins so that any form of embedded or
514 514 # imported code can test for being inside IPython.
515 515 __builtin__.__IPYTHON__ = self
516 516
517 517 # And load into builtins ipmagic/ipalias as well
518 518 __builtin__.ipmagic = ipmagic
519 519 __builtin__.ipalias = ipalias
520 520
521 521 # Add to __builtin__ other parts of IPython's public API
522 522 __builtin__.ip_set_hook = self.set_hook
523 523
524 524 # Keep in the builtins a flag for when IPython is active. We set it
525 525 # with setdefault so that multiple nested IPythons don't clobber one
526 526 # another. Each will increase its value by one upon being activated,
527 527 # which also gives us a way to determine the nesting level.
528 528 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
529 529
530 530 # Inform the user of ipython's fast exit magics.
531 531 _exit = ' Use %Exit or %Quit to exit without confirmation.'
532 532 __builtin__.exit += _exit
533 533 __builtin__.quit += _exit
534 534
535 # We need to know whether the instance is meant for embedding, since
536 # global/local namespaces need to be handled differently in that case
537 self.embedded = embedded
538
535 539 # compiler command
536 540 self.compile = CommandCompiler()
537 541
538 542 # User input buffer
539 543 self.buffer = []
540 544
541 545 # Default name given in compilation of code
542 546 self.filename = '<ipython console>'
543 547
544 548 # Create the namespace where the user will operate. user_ns is
545 549 # normally the only one used, and it is passed to the exec calls as
546 550 # the locals argument. But we do carry a user_global_ns namespace
547 551 # given as the exec 'globals' argument, This is useful in embedding
548 552 # situations where the ipython shell opens in a context where the
549 553 # distinction between locals and globals is meaningful.
550 554
551 555 # FIXME. For some strange reason, __builtins__ is showing up at user
552 556 # level as a dict instead of a module. This is a manual fix, but I
553 557 # should really track down where the problem is coming from. Alex
554 558 # Schmolck reported this problem first.
555 559
556 560 # A useful post by Alex Martelli on this topic:
557 561 # Re: inconsistent value from __builtins__
558 562 # Von: Alex Martelli <aleaxit@yahoo.com>
559 563 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
560 564 # Gruppen: comp.lang.python
561 565 # Referenzen: 1
562 566
563 567 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
564 568 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
565 569 # > <type 'dict'>
566 570 # > >>> print type(__builtins__)
567 571 # > <type 'module'>
568 572 # > Is this difference in return value intentional?
569 573
570 574 # Well, it's documented that '__builtins__' can be either a dictionary
571 575 # or a module, and it's been that way for a long time. Whether it's
572 576 # intentional (or sensible), I don't know. In any case, the idea is that
573 577 # if you need to access the built-in namespace directly, you should start
574 578 # with "import __builtin__" (note, no 's') which will definitely give you
575 579 # a module. Yeah, it's somewhat confusing:-(.
576 580
577 581 if user_ns is None:
578 582 # Set __name__ to __main__ to better match the behavior of the
579 583 # normal interpreter.
580 584 user_ns = {'__name__' :'__main__',
581 585 '__builtins__' : __builtin__,
582 586 }
583 587
584 588 if user_global_ns is None:
585 589 user_global_ns = {}
586 590
587 # assign namespaces
591 # Assign namespaces
592 # This is the namespace where all normal user variables live
588 593 self.user_ns = user_ns
594 # Embedded instances require a separate namespace for globals.
595 # Normally this one is unused by non-embedded instances.
589 596 self.user_global_ns = user_global_ns
597 # A namespace to keep track of internal data structures to prevent
598 # them from cluttering user-visible stuff. Will be updated later
599 self.internal_ns = {}
600
601 # Namespace of system aliases. Each entry in the alias
602 # table must be a 2-tuple of the form (N,name), where N is the number
603 # of positional arguments of the alias.
604 self.alias_table = {}
605
606 # A table holding all the namespaces IPython deals with, so that
607 # introspection facilities can search easily.
608 self.ns_table = {'user':user_ns,
609 'user_global':user_global_ns,
610 'alias':self.alias_table,
611 'internal':self.internal_ns,
612 'builtin':__builtin__.__dict__
613 }
590 614
591 615 # The user namespace MUST have a pointer to the shell itself.
592 616 self.user_ns[name] = self
593 617
594 618 # We need to insert into sys.modules something that looks like a
595 619 # module but which accesses the IPython namespace, for shelve and
596 620 # pickle to work interactively. Normally they rely on getting
597 621 # everything out of __main__, but for embedding purposes each IPython
598 622 # instance has its own private namespace, so we can't go shoving
599 623 # everything into __main__.
600 624
601 625 try:
602 626 main_name = self.user_ns['__name__']
603 627 except KeyError:
604 628 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
605 629 else:
606 630 #print "pickle hack in place" # dbg
607 631 sys.modules[main_name] = FakeModule(self.user_ns)
608 632
609 633 # List of input with multi-line handling.
610 634 # Fill its zero entry, user counter starts at 1
611 635 self.input_hist = InputList(['\n'])
612 636
613 637 # list of visited directories
614 638 try:
615 639 self.dir_hist = [os.getcwd()]
616 640 except IOError, e:
617 641 self.dir_hist = []
618 642
619 643 # dict of output history
620 644 self.output_hist = {}
621 645
622 # dict of names to be treated as system aliases. Each entry in the
623 # alias table must be a 2-tuple of the form (N,name), where N is the
624 # number of positional arguments of the alias.
625 self.alias_table = {}
626
627 646 # dict of things NOT to alias (keywords, builtins and some special magics)
628 647 no_alias = {}
629 648 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
630 649 for key in keyword.kwlist + no_alias_magics:
631 650 no_alias[key] = 1
632 651 no_alias.update(__builtin__.__dict__)
633 652 self.no_alias = no_alias
634 653
635 654 # make global variables for user access to these
636 655 self.user_ns['_ih'] = self.input_hist
637 656 self.user_ns['_oh'] = self.output_hist
638 657 self.user_ns['_dh'] = self.dir_hist
639 658
640 659 # user aliases to input and output histories
641 660 self.user_ns['In'] = self.input_hist
642 661 self.user_ns['Out'] = self.output_hist
643 662
644 663 # Store the actual shell's name
645 664 self.name = name
646 665
647 666 # Object variable to store code object waiting execution. This is
648 667 # used mainly by the multithreaded shells, but it can come in handy in
649 668 # other situations. No need to use a Queue here, since it's a single
650 669 # item which gets cleared once run.
651 670 self.code_to_run = None
652 671
653 672 # Job manager (for jobs run as background threads)
654 673 self.jobs = BackgroundJobManager()
655 674 # Put the job manager into builtins so it's always there.
656 675 __builtin__.jobs = self.jobs
657 676
658 677 # escapes for automatic behavior on the command line
659 678 self.ESC_SHELL = '!'
660 679 self.ESC_HELP = '?'
661 680 self.ESC_MAGIC = '%'
662 681 self.ESC_QUOTE = ','
663 682 self.ESC_QUOTE2 = ';'
664 683 self.ESC_PAREN = '/'
665 684
666 685 # And their associated handlers
667 686 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
668 687 self.ESC_QUOTE:self.handle_auto,
669 688 self.ESC_QUOTE2:self.handle_auto,
670 689 self.ESC_MAGIC:self.handle_magic,
671 690 self.ESC_HELP:self.handle_help,
672 691 self.ESC_SHELL:self.handle_shell_escape,
673 692 }
674 693
675 694 # class initializations
676 695 Logger.__init__(self,log_ns = self.user_ns)
677 696 Magic.__init__(self,self)
678 697
679 698 # an ugly hack to get a pointer to the shell, so I can start writing
680 699 # magic code via this pointer instead of the current mixin salad.
681 700 Magic.set_shell(self,self)
682 701
683 702 # Python source parser/formatter for syntax highlighting
684 703 pyformat = Parser().format
685 704 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
686 705
687 706 # hooks holds pointers used for user-side customizations
688 707 self.hooks = Struct()
689 708
690 709 # Set all default hooks, defined in the IPython.hooks module.
691 710 hooks = IPython.hooks
692 711 for hook_name in hooks.__all__:
693 712 self.set_hook(hook_name,getattr(hooks,hook_name))
694 713
695 714 # Flag to mark unconditional exit
696 715 self.exit_now = False
697 716
698 717 self.usage_min = """\
699 718 An enhanced console for Python.
700 719 Some of its features are:
701 720 - Readline support if the readline library is present.
702 721 - Tab completion in the local namespace.
703 722 - Logging of input, see command-line options.
704 723 - System shell escape via ! , eg !ls.
705 724 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
706 725 - Keeps track of locally defined variables via %who, %whos.
707 726 - Show object information with a ? eg ?x or x? (use ?? for more info).
708 727 """
709 728 if usage: self.usage = usage
710 729 else: self.usage = self.usage_min
711 730
712 731 # Storage
713 732 self.rc = rc # This will hold all configuration information
714 733 self.inputcache = []
715 734 self._boundcache = []
716 735 self.pager = 'less'
717 736 # temporary files used for various purposes. Deleted at exit.
718 737 self.tempfiles = []
719 738
720 739 # Keep track of readline usage (later set by init_readline)
721 740 self.has_readline = 0
722 741
723 742 # for pushd/popd management
724 743 try:
725 744 self.home_dir = get_home_dir()
726 745 except HomeDirError,msg:
727 746 fatal(msg)
728 747
729 748 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
730 749
731 750 # Functions to call the underlying shell.
732 751
733 752 # utility to expand user variables via Itpl
734 753 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
735 754 self.user_ns))
736 755 # The first is similar to os.system, but it doesn't return a value,
737 756 # and it allows interpolation of variables in the user's namespace.
738 757 self.system = lambda cmd: shell(self.var_expand(cmd),
739 758 header='IPython system call: ',
740 759 verbose=self.rc.system_verbose)
741 760 # These are for getoutput and getoutputerror:
742 761 self.getoutput = lambda cmd: \
743 762 getoutput(self.var_expand(cmd),
744 763 header='IPython system call: ',
745 764 verbose=self.rc.system_verbose)
746 765 self.getoutputerror = lambda cmd: \
747 766 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
748 767 self.user_ns)),
749 768 header='IPython system call: ',
750 769 verbose=self.rc.system_verbose)
751 770
752 771 # RegExp for splitting line contents into pre-char//first
753 772 # word-method//rest. For clarity, each group in on one line.
754 773
755 774 # WARNING: update the regexp if the above escapes are changed, as they
756 775 # are hardwired in.
757 776
758 777 # Don't get carried away with trying to make the autocalling catch too
759 778 # much: it's better to be conservative rather than to trigger hidden
760 779 # evals() somewhere and end up causing side effects.
761 780
762 781 self.line_split = re.compile(r'^([\s*,;/])'
763 782 r'([\?\w\.]+\w*\s*)'
764 783 r'(\(?.*$)')
765 784
766 785 # Original re, keep around for a while in case changes break something
767 786 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
768 787 # r'(\s*[\?\w\.]+\w*\s*)'
769 788 # r'(\(?.*$)')
770 789
771 790 # RegExp to identify potential function names
772 791 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
773 792 # RegExp to exclude strings with this start from autocalling
774 793 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
775 794 # try to catch also methods for stuff in lists/tuples/dicts: off
776 795 # (experimental). For this to work, the line_split regexp would need
777 796 # to be modified so it wouldn't break things at '['. That line is
778 797 # nasty enough that I shouldn't change it until I can test it _well_.
779 798 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
780 799
781 800 # keep track of where we started running (mainly for crash post-mortem)
782 801 self.starting_dir = os.getcwd()
783 802
784 803 # Attributes for Logger mixin class, make defaults here
785 804 self._dolog = 0
786 805 self.LOG = ''
787 806 self.LOGDEF = '.InteractiveShell.log'
788 807 self.LOGMODE = 'over'
789 808 self.LOGHEAD = Itpl(
790 809 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
791 810 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
792 811 #log# opts = $self.rc.opts
793 812 #log# args = $self.rc.args
794 813 #log# It is safe to make manual edits below here.
795 814 #log#-----------------------------------------------------------------------
796 815 """)
797 816 # Various switches which can be set
798 817 self.CACHELENGTH = 5000 # this is cheap, it's just text
799 818 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
800 819 self.banner2 = banner2
801 820
802 821 # TraceBack handlers:
803 822 # Need two, one for syntax errors and one for other exceptions.
804 823 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
805 824 # This one is initialized with an offset, meaning we always want to
806 825 # remove the topmost item in the traceback, which is our own internal
807 826 # code. Valid modes: ['Plain','Context','Verbose']
808 827 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
809 828 color_scheme='NoColor',
810 829 tb_offset = 1)
811 830 # and add any custom exception handlers the user may have specified
812 831 self.set_custom_exc(*custom_exceptions)
813 832
814 833 # Object inspector
815 834 ins_colors = OInspect.InspectColors
816 835 code_colors = PyColorize.ANSICodeColors
817 836 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
818 837 self.autoindent = 0
819 838
820 839 # Make some aliases automatically
821 840 # Prepare list of shell aliases to auto-define
822 841 if os.name == 'posix':
823 842 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
824 843 'mv mv -i','rm rm -i','cp cp -i',
825 844 'cat cat','less less','clear clear',
826 845 # a better ls
827 846 'ls ls -F',
828 847 # long ls
829 848 'll ls -lF',
830 849 # color ls
831 850 'lc ls -F -o --color',
832 851 # ls normal files only
833 852 'lf ls -F -o --color %l | grep ^-',
834 853 # ls symbolic links
835 854 'lk ls -F -o --color %l | grep ^l',
836 855 # directories or links to directories,
837 856 'ldir ls -F -o --color %l | grep /$',
838 857 # things which are executable
839 858 'lx ls -F -o --color %l | grep ^-..x',
840 859 )
841 860 elif os.name in ['nt','dos']:
842 861 auto_alias = ('dir dir /on', 'ls dir /on',
843 862 'ddir dir /ad /on', 'ldir dir /ad /on',
844 863 'mkdir mkdir','rmdir rmdir','echo echo',
845 864 'ren ren','cls cls','copy copy')
846 865 else:
847 866 auto_alias = ()
848 867 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
849 868 # Call the actual (public) initializer
850 869 self.init_auto_alias()
851 870 # end __init__
852 871
853 872 def set_hook(self,name,hook):
854 873 """set_hook(name,hook) -> sets an internal IPython hook.
855 874
856 875 IPython exposes some of its internal API as user-modifiable hooks. By
857 876 resetting one of these hooks, you can modify IPython's behavior to
858 877 call at runtime your own routines."""
859 878
860 879 # At some point in the future, this should validate the hook before it
861 880 # accepts it. Probably at least check that the hook takes the number
862 881 # of args it's supposed to.
863 882 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
864 883
865 884 def set_custom_exc(self,exc_tuple,handler):
866 885 """set_custom_exc(exc_tuple,handler)
867 886
868 887 Set a custom exception handler, which will be called if any of the
869 888 exceptions in exc_tuple occur in the mainloop (specifically, in the
870 889 runcode() method.
871 890
872 891 Inputs:
873 892
874 893 - exc_tuple: a *tuple* of valid exceptions to call the defined
875 894 handler for. It is very important that you use a tuple, and NOT A
876 895 LIST here, because of the way Python's except statement works. If
877 896 you only want to trap a single exception, use a singleton tuple:
878 897
879 898 exc_tuple == (MyCustomException,)
880 899
881 900 - handler: this must be defined as a function with the following
882 901 basic interface: def my_handler(self,etype,value,tb).
883 902
884 903 This will be made into an instance method (via new.instancemethod)
885 904 of IPython itself, and it will be called if any of the exceptions
886 905 listed in the exc_tuple are caught. If the handler is None, an
887 906 internal basic one is used, which just prints basic info.
888 907
889 908 WARNING: by putting in your own exception handler into IPython's main
890 909 execution loop, you run a very good chance of nasty crashes. This
891 910 facility should only be used if you really know what you are doing."""
892 911
893 912 assert type(exc_tuple)==type(()) , \
894 913 "The custom exceptions must be given AS A TUPLE."
895 914
896 915 def dummy_handler(self,etype,value,tb):
897 916 print '*** Simple custom exception handler ***'
898 917 print 'Exception type :',etype
899 918 print 'Exception value:',value
900 919 print 'Traceback :',tb
901 920 print 'Source code :','\n'.join(self.buffer)
902 921
903 922 if handler is None: handler = dummy_handler
904 923
905 924 self.CustomTB = new.instancemethod(handler,self,self.__class__)
906 925 self.custom_exceptions = exc_tuple
907 926
908 927 def set_custom_completer(self,completer,pos=0):
909 928 """set_custom_completer(completer,pos=0)
910 929
911 930 Adds a new custom completer function.
912 931
913 932 The position argument (defaults to 0) is the index in the completers
914 933 list where you want the completer to be inserted."""
915 934
916 935 newcomp = new.instancemethod(completer,self.Completer,
917 936 self.Completer.__class__)
918 937 self.Completer.matchers.insert(pos,newcomp)
919 938
920 939 def complete(self,text):
921 940 """Return a sorted list of all possible completions on text.
922 941
923 942 Inputs:
924 943
925 944 - text: a string of text to be completed on.
926 945
927 946 This is a wrapper around the completion mechanism, similar to what
928 947 readline does at the command line when the TAB key is hit. By
929 948 exposing it as a method, it can be used by other non-readline
930 949 environments (such as GUIs) for text completion.
931 950
932 951 Simple usage example:
933 952
934 953 In [1]: x = 'hello'
935 954
936 955 In [2]: __IP.complete('x.l')
937 956 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
938 957
939 958 complete = self.Completer.complete
940 959 state = 0
941 960 # use a dict so we get unique keys, since ipyhton's multiple
942 961 # completers can return duplicates.
943 962 comps = {}
944 963 while True:
945 964 newcomp = complete(text,state)
946 965 if newcomp is None:
947 966 break
948 967 comps[newcomp] = 1
949 968 state += 1
950 969 outcomps = comps.keys()
951 970 outcomps.sort()
952 971 return outcomps
953 972
954 973 def post_config_initialization(self):
955 974 """Post configuration init method
956 975
957 976 This is called after the configuration files have been processed to
958 977 'finalize' the initialization."""
959
978
979 # Load readline proper
980 if self.rc.readline:
981 self.init_readline()
982
983 # Set user colors (don't do it in the constructor above so that it doesn't
984 # crash if colors option is invalid)
985 self.magic_colors(self.rc.colors)
986
960 987 # dynamic data that survives through sessions
961 988 # XXX make the filename a config option?
962 989 persist_base = 'persist'
963 990 if self.rc.profile:
964 991 persist_base += '_%s' % self.rc.profile
965 992 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
966 993
967 994 try:
968 995 self.persist = pickle.load(file(self.persist_fname))
969 996 except:
970 997 self.persist = {}
971 998
972 999 def init_auto_alias(self):
973 1000 """Define some aliases automatically.
974 1001
975 1002 These are ALL parameter-less aliases"""
976 1003 for alias,cmd in self.auto_alias:
977 1004 self.alias_table[alias] = (0,cmd)
978 1005
979 1006 def alias_table_validate(self,verbose=0):
980 1007 """Update information about the alias table.
981 1008
982 1009 In particular, make sure no Python keywords/builtins are in it."""
983 1010
984 1011 no_alias = self.no_alias
985 1012 for k in self.alias_table.keys():
986 1013 if k in no_alias:
987 1014 del self.alias_table[k]
988 1015 if verbose:
989 1016 print ("Deleting alias <%s>, it's a Python "
990 1017 "keyword or builtin." % k)
991 1018
992 1019 def set_autoindent(self,value=None):
993 1020 """Set the autoindent flag, checking for readline support.
994 1021
995 1022 If called with no arguments, it acts as a toggle."""
996 1023
997 1024 if not self.has_readline:
998 1025 if os.name == 'posix':
999 1026 warn("The auto-indent feature requires the readline library")
1000 1027 self.autoindent = 0
1001 1028 return
1002 1029 if value is None:
1003 1030 self.autoindent = not self.autoindent
1004 1031 else:
1005 1032 self.autoindent = value
1006 1033
1007 1034 def rc_set_toggle(self,rc_field,value=None):
1008 1035 """Set or toggle a field in IPython's rc config. structure.
1009 1036
1010 1037 If called with no arguments, it acts as a toggle.
1011 1038
1012 1039 If called with a non-existent field, the resulting AttributeError
1013 1040 exception will propagate out."""
1014 1041
1015 1042 rc_val = getattr(self.rc,rc_field)
1016 1043 if value is None:
1017 1044 value = not rc_val
1018 1045 setattr(self.rc,rc_field,value)
1019 1046
1020 1047 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1021 1048 """Install the user configuration directory.
1022 1049
1023 1050 Can be called when running for the first time or to upgrade the user's
1024 1051 .ipython/ directory with the mode parameter. Valid modes are 'install'
1025 1052 and 'upgrade'."""
1026 1053
1027 1054 def wait():
1028 1055 try:
1029 1056 raw_input("Please press <RETURN> to start IPython.")
1030 1057 except EOFError:
1031 1058 print >> Term.cout
1032 1059 print '*'*70
1033 1060
1034 1061 cwd = os.getcwd() # remember where we started
1035 1062 glb = glob.glob
1036 1063 print '*'*70
1037 1064 if mode == 'install':
1038 1065 print \
1039 1066 """Welcome to IPython. I will try to create a personal configuration directory
1040 1067 where you can customize many aspects of IPython's functionality in:\n"""
1041 1068 else:
1042 1069 print 'I am going to upgrade your configuration in:'
1043 1070
1044 1071 print ipythondir
1045 1072
1046 1073 rcdirend = os.path.join('IPython','UserConfig')
1047 1074 cfg = lambda d: os.path.join(d,rcdirend)
1048 1075 try:
1049 1076 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1050 1077 except IOError:
1051 1078 warning = """
1052 1079 Installation error. IPython's directory was not found.
1053 1080
1054 1081 Check the following:
1055 1082
1056 1083 The ipython/IPython directory should be in a directory belonging to your
1057 1084 PYTHONPATH environment variable (that is, it should be in a directory
1058 1085 belonging to sys.path). You can copy it explicitly there or just link to it.
1059 1086
1060 1087 IPython will proceed with builtin defaults.
1061 1088 """
1062 1089 warn(warning)
1063 1090 wait()
1064 1091 return
1065 1092
1066 1093 if mode == 'install':
1067 1094 try:
1068 1095 shutil.copytree(rcdir,ipythondir)
1069 1096 os.chdir(ipythondir)
1070 1097 rc_files = glb("ipythonrc*")
1071 1098 for rc_file in rc_files:
1072 1099 os.rename(rc_file,rc_file+rc_suffix)
1073 1100 except:
1074 1101 warning = """
1075 1102
1076 1103 There was a problem with the installation:
1077 1104 %s
1078 1105 Try to correct it or contact the developers if you think it's a bug.
1079 1106 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1080 1107 warn(warning)
1081 1108 wait()
1082 1109 return
1083 1110
1084 1111 elif mode == 'upgrade':
1085 1112 try:
1086 1113 os.chdir(ipythondir)
1087 1114 except:
1088 1115 print """
1089 1116 Can not upgrade: changing to directory %s failed. Details:
1090 1117 %s
1091 1118 """ % (ipythondir,sys.exc_info()[1])
1092 1119 wait()
1093 1120 return
1094 1121 else:
1095 1122 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1096 1123 for new_full_path in sources:
1097 1124 new_filename = os.path.basename(new_full_path)
1098 1125 if new_filename.startswith('ipythonrc'):
1099 1126 new_filename = new_filename + rc_suffix
1100 1127 # The config directory should only contain files, skip any
1101 1128 # directories which may be there (like CVS)
1102 1129 if os.path.isdir(new_full_path):
1103 1130 continue
1104 1131 if os.path.exists(new_filename):
1105 1132 old_file = new_filename+'.old'
1106 1133 if os.path.exists(old_file):
1107 1134 os.remove(old_file)
1108 1135 os.rename(new_filename,old_file)
1109 1136 shutil.copy(new_full_path,new_filename)
1110 1137 else:
1111 1138 raise ValueError,'unrecognized mode for install:',`mode`
1112 1139
1113 1140 # Fix line-endings to those native to each platform in the config
1114 1141 # directory.
1115 1142 try:
1116 1143 os.chdir(ipythondir)
1117 1144 except:
1118 1145 print """
1119 1146 Problem: changing to directory %s failed.
1120 1147 Details:
1121 1148 %s
1122 1149
1123 1150 Some configuration files may have incorrect line endings. This should not
1124 1151 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1125 1152 wait()
1126 1153 else:
1127 1154 for fname in glb('ipythonrc*'):
1128 1155 try:
1129 1156 native_line_ends(fname,backup=0)
1130 1157 except IOError:
1131 1158 pass
1132 1159
1133 1160 if mode == 'install':
1134 1161 print """
1135 1162 Successful installation!
1136 1163
1137 1164 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1138 1165 IPython manual (there are both HTML and PDF versions supplied with the
1139 1166 distribution) to make sure that your system environment is properly configured
1140 1167 to take advantage of IPython's features."""
1141 1168 else:
1142 1169 print """
1143 1170 Successful upgrade!
1144 1171
1145 1172 All files in your directory:
1146 1173 %(ipythondir)s
1147 1174 which would have been overwritten by the upgrade were backed up with a .old
1148 1175 extension. If you had made particular customizations in those files you may
1149 1176 want to merge them back into the new files.""" % locals()
1150 1177 wait()
1151 1178 os.chdir(cwd)
1152 1179 # end user_setup()
1153 1180
1154 1181 def atexit_operations(self):
1155 1182 """This will be executed at the time of exit.
1156 1183
1157 1184 Saving of persistent data should be performed here. """
1158 1185
1159 1186 # input history
1160 1187 self.savehist()
1161 1188
1162 1189 # Cleanup all tempfiles left around
1163 1190 for tfile in self.tempfiles:
1164 1191 try:
1165 1192 os.unlink(tfile)
1166 1193 except OSError:
1167 1194 pass
1168 1195
1169 1196 # save the "persistent data" catch-all dictionary
1170 1197 try:
1171 1198 pickle.dump(self.persist, open(self.persist_fname,"w"))
1172 1199 except:
1173 1200 print "*** ERROR *** persistent data saving failed."
1174 1201
1175 1202 def savehist(self):
1176 1203 """Save input history to a file (via readline library)."""
1177 1204 try:
1178 1205 self.readline.write_history_file(self.histfile)
1179 1206 except:
1180 1207 print 'Unable to save IPython command history to file: ' + \
1181 1208 `self.histfile`
1182 1209
1183 1210 def pre_readline(self):
1184 1211 """readline hook to be used at the start of each line.
1185 1212
1186 1213 Currently it handles auto-indent only."""
1187 1214
1188 1215 self.readline.insert_text(' '* self.readline_indent)
1189 1216
1190 1217 def init_readline(self):
1191 1218 """Command history completion/saving/reloading."""
1192 1219 try:
1193 1220 import readline
1194 1221 self.Completer = MagicCompleter(self,
1195 1222 self.user_ns,
1196 1223 self.rc.readline_omit__names,
1197 1224 self.alias_table)
1198 1225 except ImportError,NameError:
1199 1226 # If FlexCompleter failed to import, MagicCompleter won't be
1200 1227 # defined. This can happen because of a problem with readline
1201 1228 self.has_readline = 0
1202 1229 # no point in bugging windows users with this every time:
1203 1230 if os.name == 'posix':
1204 1231 warn('Readline services not available on this platform.')
1205 1232 else:
1206 1233 import atexit
1207 1234
1208 1235 # Platform-specific configuration
1209 1236 if os.name == 'nt':
1210 1237 # readline under Windows modifies the default exit behavior
1211 1238 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1212 1239 __builtin__.exit = __builtin__.quit = \
1213 1240 ('Use Ctrl-D (i.e. EOF) to exit. '
1214 1241 'Use %Exit or %Quit to exit without confirmation.')
1215 1242 self.readline_startup_hook = readline.set_pre_input_hook
1216 1243 else:
1217 1244 self.readline_startup_hook = readline.set_startup_hook
1218 1245
1219 1246 # Load user's initrc file (readline config)
1220 1247 inputrc_name = os.environ.get('INPUTRC')
1221 1248 if inputrc_name is None:
1222 1249 home_dir = get_home_dir()
1223 1250 if home_dir is not None:
1224 1251 inputrc_name = os.path.join(home_dir,'.inputrc')
1225 1252 if os.path.isfile(inputrc_name):
1226 1253 try:
1227 1254 readline.read_init_file(inputrc_name)
1228 1255 except:
1229 1256 warn('Problems reading readline initialization file <%s>'
1230 1257 % inputrc_name)
1231 1258
1232 1259 self.has_readline = 1
1233 1260 self.readline = readline
1234 1261 self.readline_indent = 0 # for auto-indenting via readline
1235 1262 # save this in sys so embedded copies can restore it properly
1236 1263 sys.ipcompleter = self.Completer.complete
1237 1264 readline.set_completer(self.Completer.complete)
1238 1265
1239 1266 # Configure readline according to user's prefs
1240 1267 for rlcommand in self.rc.readline_parse_and_bind:
1241 1268 readline.parse_and_bind(rlcommand)
1242 1269
1243 1270 # remove some chars from the delimiters list
1244 1271 delims = readline.get_completer_delims()
1245 1272 delims = delims.translate(string._idmap,
1246 1273 self.rc.readline_remove_delims)
1247 1274 readline.set_completer_delims(delims)
1248 1275 # otherwise we end up with a monster history after a while:
1249 1276 readline.set_history_length(1000)
1250 1277 try:
1251 1278 #print '*** Reading readline history' # dbg
1252 1279 readline.read_history_file(self.histfile)
1253 1280 except IOError:
1254 1281 pass # It doesn't exist yet.
1255 1282
1256 1283 atexit.register(self.atexit_operations)
1257 1284 del atexit
1258 1285
1259 1286 # Configure auto-indent for all platforms
1260 1287 self.set_autoindent(self.rc.autoindent)
1261 1288
1262 1289 def showsyntaxerror(self, filename=None):
1263 1290 """Display the syntax error that just occurred.
1264 1291
1265 1292 This doesn't display a stack trace because there isn't one.
1266 1293
1267 1294 If a filename is given, it is stuffed in the exception instead
1268 1295 of what was there before (because Python's parser always uses
1269 1296 "<string>" when reading from a string).
1270 1297 """
1271 1298 type, value, sys.last_traceback = sys.exc_info()
1272 1299 sys.last_type = type
1273 1300 sys.last_value = value
1274 1301 if filename and type is SyntaxError:
1275 1302 # Work hard to stuff the correct filename in the exception
1276 1303 try:
1277 1304 msg, (dummy_filename, lineno, offset, line) = value
1278 1305 except:
1279 1306 # Not the format we expect; leave it alone
1280 1307 pass
1281 1308 else:
1282 1309 # Stuff in the right filename
1283 1310 try:
1284 1311 # Assume SyntaxError is a class exception
1285 1312 value = SyntaxError(msg, (filename, lineno, offset, line))
1286 1313 except:
1287 1314 # If that failed, assume SyntaxError is a string
1288 1315 value = msg, (filename, lineno, offset, line)
1289 1316 self.SyntaxTB(type,value,[])
1290 1317
1291 1318 def debugger(self):
1292 1319 """Call the pdb debugger."""
1293 1320
1294 1321 if not self.rc.pdb:
1295 1322 return
1296 1323 pdb.pm()
1297 1324
1298 1325 def showtraceback(self,exc_tuple = None,filename=None):
1299 1326 """Display the exception that just occurred."""
1300 1327
1301 1328 # Though this won't be called by syntax errors in the input line,
1302 1329 # there may be SyntaxError cases whith imported code.
1303 1330 if exc_tuple is None:
1304 1331 type, value, tb = sys.exc_info()
1305 1332 else:
1306 1333 type, value, tb = exc_tuple
1307 1334 if type is SyntaxError:
1308 1335 self.showsyntaxerror(filename)
1309 1336 else:
1310 1337 sys.last_type = type
1311 1338 sys.last_value = value
1312 1339 sys.last_traceback = tb
1313 1340 self.InteractiveTB()
1314 1341 if self.InteractiveTB.call_pdb and self.has_readline:
1315 1342 # pdb mucks up readline, fix it back
1316 1343 self.readline.set_completer(self.Completer.complete)
1317 1344
1318 1345 def update_cache(self, line):
1319 1346 """puts line into cache"""
1320 1347 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1321 1348 if len(self.inputcache) >= self.CACHELENGTH:
1322 1349 self.inputcache.pop() # This not :-)
1323 1350
1324 1351 def mainloop(self,banner=None):
1325 1352 """Creates the local namespace and starts the mainloop.
1326 1353
1327 1354 If an optional banner argument is given, it will override the
1328 1355 internally created default banner."""
1329 1356
1330 1357 if self.rc.c: # Emulate Python's -c option
1331 1358 self.exec_init_cmd()
1332 1359 if banner is None:
1333 1360 if self.rc.banner:
1334 1361 banner = self.BANNER+self.banner2
1335 1362 else:
1336 1363 banner = ''
1337 1364 self.interact(banner)
1338 1365
1339 1366 def exec_init_cmd(self):
1340 1367 """Execute a command given at the command line.
1341 1368
1342 1369 This emulates Python's -c option."""
1343 1370
1344 1371 sys.argv = ['-c']
1345 1372 self.push(self.rc.c)
1346 1373
1347 1374 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1348 1375 """Embeds IPython into a running python program.
1349 1376
1350 1377 Input:
1351 1378
1352 1379 - header: An optional header message can be specified.
1353 1380
1354 1381 - local_ns, global_ns: working namespaces. If given as None, the
1355 1382 IPython-initialized one is updated with __main__.__dict__, so that
1356 1383 program variables become visible but user-specific configuration
1357 1384 remains possible.
1358 1385
1359 1386 - stack_depth: specifies how many levels in the stack to go to
1360 1387 looking for namespaces (when local_ns and global_ns are None). This
1361 1388 allows an intermediate caller to make sure that this function gets
1362 1389 the namespace from the intended level in the stack. By default (0)
1363 1390 it will get its locals and globals from the immediate caller.
1364 1391
1365 1392 Warning: it's possible to use this in a program which is being run by
1366 1393 IPython itself (via %run), but some funny things will happen (a few
1367 1394 globals get overwritten). In the future this will be cleaned up, as
1368 1395 there is no fundamental reason why it can't work perfectly."""
1369 1396
1370 1397 # Get locals and globals from caller
1371 1398 if local_ns is None or global_ns is None:
1372 1399 call_frame = sys._getframe(stack_depth).f_back
1373 1400
1374 1401 if local_ns is None:
1375 1402 local_ns = call_frame.f_locals
1376 1403 if global_ns is None:
1377 1404 global_ns = call_frame.f_globals
1378 1405
1379 1406 # Update namespaces and fire up interpreter
1380 1407 self.user_ns = local_ns
1381 1408 self.user_global_ns = global_ns
1382 1409
1383 1410 # Patch for global embedding to make sure that things don't overwrite
1384 1411 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1385 1412 # FIXME. Test this a bit more carefully (the if.. is new)
1386 1413 if local_ns is None and global_ns is None:
1387 1414 self.user_global_ns.update(__main__.__dict__)
1388 1415
1389 1416 self.interact(header)
1390 1417
1391 1418 def interact(self, banner=None):
1392 1419 """Closely emulate the interactive Python console.
1393 1420
1394 1421 The optional banner argument specify the banner to print
1395 1422 before the first interaction; by default it prints a banner
1396 1423 similar to the one printed by the real Python interpreter,
1397 1424 followed by the current class name in parentheses (so as not
1398 1425 to confuse this with the real interpreter -- since it's so
1399 1426 close!).
1400 1427
1401 1428 """
1402 1429 cprt = 'Type "copyright", "credits" or "license" for more information.'
1403 1430 if banner is None:
1404 1431 self.write("Python %s on %s\n%s\n(%s)\n" %
1405 1432 (sys.version, sys.platform, cprt,
1406 1433 self.__class__.__name__))
1407 1434 else:
1408 1435 self.write(banner)
1409 1436
1410 1437 more = 0
1411 1438
1412 1439 # Mark activity in the builtins
1413 1440 __builtin__.__dict__['__IPYTHON__active'] += 1
1414 1441
1415 1442 # exit_now is set by a call to %Exit or %Quit
1416 1443 while not self.exit_now:
1417 1444 try:
1418 1445 if more:
1419 1446 prompt = self.outputcache.prompt2
1420 1447 if self.autoindent:
1421 1448 self.readline_startup_hook(self.pre_readline)
1422 1449 else:
1423 1450 prompt = self.outputcache.prompt1
1424 1451 try:
1425 1452 line = self.raw_input(prompt)
1426 1453 if self.autoindent:
1427 1454 self.readline_startup_hook(None)
1428 1455 except EOFError:
1429 1456 if self.autoindent:
1430 1457 self.readline_startup_hook(None)
1431 1458 self.write("\n")
1432 1459 if self.rc.confirm_exit:
1433 1460 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1434 1461 break
1435 1462 else:
1436 1463 break
1437 1464 else:
1438 1465 more = self.push(line)
1439 1466 # Auto-indent management
1440 1467 if self.autoindent:
1441 1468 if line:
1442 1469 ini_spaces = re.match('^(\s+)',line)
1443 1470 if ini_spaces:
1444 1471 nspaces = ini_spaces.end()
1445 1472 else:
1446 1473 nspaces = 0
1447 1474 self.readline_indent = nspaces
1448 1475
1449 1476 if line[-1] == ':':
1450 1477 self.readline_indent += 4
1451 1478 elif re.match(r'^\s+raise|^\s+return',line):
1452 1479 self.readline_indent -= 4
1453 1480 else:
1454 1481 self.readline_indent = 0
1455 1482
1456 1483 except KeyboardInterrupt:
1457 1484 self.write("\nKeyboardInterrupt\n")
1458 1485 self.resetbuffer()
1459 1486 more = 0
1460 1487 # keep cache in sync with the prompt counter:
1461 1488 self.outputcache.prompt_count -= 1
1462 1489
1463 1490 if self.autoindent:
1464 1491 self.readline_indent = 0
1465 1492
1466 1493 except bdb.BdbQuit:
1467 1494 warn("The Python debugger has exited with a BdbQuit exception.\n"
1468 1495 "Because of how pdb handles the stack, it is impossible\n"
1469 1496 "for IPython to properly format this particular exception.\n"
1470 1497 "IPython will resume normal operation.")
1471 1498
1472 1499 # We are off again...
1473 1500 __builtin__.__dict__['__IPYTHON__active'] -= 1
1474 1501
1475 1502 def excepthook(self, type, value, tb):
1476 1503 """One more defense for GUI apps that call sys.excepthook.
1477 1504
1478 1505 GUI frameworks like wxPython trap exceptions and call
1479 1506 sys.excepthook themselves. I guess this is a feature that
1480 1507 enables them to keep running after exceptions that would
1481 1508 otherwise kill their mainloop. This is a bother for IPython
1482 1509 which excepts to catch all of the program exceptions with a try:
1483 1510 except: statement.
1484 1511
1485 1512 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1486 1513 any app directly invokes sys.excepthook, it will look to the user like
1487 1514 IPython crashed. In order to work around this, we can disable the
1488 1515 CrashHandler and replace it with this excepthook instead, which prints a
1489 1516 regular traceback using our InteractiveTB. In this fashion, apps which
1490 1517 call sys.excepthook will generate a regular-looking exception from
1491 1518 IPython, and the CrashHandler will only be triggered by real IPython
1492 1519 crashes.
1493 1520
1494 1521 This hook should be used sparingly, only in places which are not likely
1495 1522 to be true IPython errors.
1496 1523 """
1497 1524
1498 1525 self.InteractiveTB(type, value, tb, tb_offset=0)
1499 1526 if self.InteractiveTB.call_pdb and self.has_readline:
1500 1527 self.readline.set_completer(self.Completer.complete)
1501 1528
1502 1529 def call_alias(self,alias,rest=''):
1503 1530 """Call an alias given its name and the rest of the line.
1504 1531
1505 1532 This function MUST be given a proper alias, because it doesn't make
1506 1533 any checks when looking up into the alias table. The caller is
1507 1534 responsible for invoking it only with a valid alias."""
1508 1535
1509 1536 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1510 1537 nargs,cmd = self.alias_table[alias]
1511 1538 # Expand the %l special to be the user's input line
1512 1539 if cmd.find('%l') >= 0:
1513 1540 cmd = cmd.replace('%l',rest)
1514 1541 rest = ''
1515 1542 if nargs==0:
1516 1543 # Simple, argument-less aliases
1517 1544 cmd = '%s %s' % (cmd,rest)
1518 1545 else:
1519 1546 # Handle aliases with positional arguments
1520 1547 args = rest.split(None,nargs)
1521 1548 if len(args)< nargs:
1522 1549 error('Alias <%s> requires %s arguments, %s given.' %
1523 1550 (alias,nargs,len(args)))
1524 1551 return
1525 1552 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1526 1553 # Now call the macro, evaluating in the user's namespace
1527 1554 try:
1528 1555 self.system(cmd)
1529 1556 except:
1530 1557 self.showtraceback()
1531 1558
1532 1559 def runlines(self,lines):
1533 1560 """Run a string of one or more lines of source.
1534 1561
1535 1562 This method is capable of running a string containing multiple source
1536 1563 lines, as if they had been entered at the IPython prompt. Since it
1537 1564 exposes IPython's processing machinery, the given strings can contain
1538 1565 magic calls (%magic), special shell access (!cmd), etc."""
1539 1566
1540 1567 # We must start with a clean buffer, in case this is run from an
1541 1568 # interactive IPython session (via a magic, for example).
1542 1569 self.resetbuffer()
1543 1570 lines = lines.split('\n')
1544 1571 more = 0
1545 1572 for line in lines:
1546 1573 # skip blank lines so we don't mess up the prompt counter, but do
1547 1574 # NOT skip even a blank line if we are in a code block (more is
1548 1575 # true)
1549 1576 if line or more:
1550 1577 more = self.push((self.prefilter(line,more)))
1551 1578 # IPython's runsource returns None if there was an error
1552 1579 # compiling the code. This allows us to stop processing right
1553 1580 # away, so the user gets the error message at the right place.
1554 1581 if more is None:
1555 1582 break
1556 1583 # final newline in case the input didn't have it, so that the code
1557 1584 # actually does get executed
1558 1585 if more:
1559 1586 self.push('\n')
1560 1587
1561 1588 def runsource(self, source, filename="<input>", symbol="single"):
1562 1589 """Compile and run some source in the interpreter.
1563 1590
1564 1591 Arguments are as for compile_command().
1565 1592
1566 1593 One several things can happen:
1567 1594
1568 1595 1) The input is incorrect; compile_command() raised an
1569 1596 exception (SyntaxError or OverflowError). A syntax traceback
1570 1597 will be printed by calling the showsyntaxerror() method.
1571 1598
1572 1599 2) The input is incomplete, and more input is required;
1573 1600 compile_command() returned None. Nothing happens.
1574 1601
1575 1602 3) The input is complete; compile_command() returned a code
1576 1603 object. The code is executed by calling self.runcode() (which
1577 1604 also handles run-time exceptions, except for SystemExit).
1578 1605
1579 1606 The return value is:
1580 1607
1581 1608 - True in case 2
1582 1609
1583 1610 - False in the other cases, unless an exception is raised, where
1584 1611 None is returned instead. This can be used by external callers to
1585 1612 know whether to continue feeding input or not.
1586 1613
1587 1614 The return value can be used to decide whether to use sys.ps1 or
1588 1615 sys.ps2 to prompt the next line."""
1589 1616
1590 1617 try:
1591 1618 code = self.compile(source, filename, symbol)
1592 1619 except (OverflowError, SyntaxError, ValueError):
1593 1620 # Case 1
1594 1621 self.showsyntaxerror(filename)
1595 1622 return None
1596 1623
1597 1624 if code is None:
1598 1625 # Case 2
1599 1626 return True
1600 1627
1601 1628 # Case 3
1602 1629 # We store the code object so that threaded shells and
1603 1630 # custom exception handlers can access all this info if needed.
1604 1631 # The source corresponding to this can be obtained from the
1605 1632 # buffer attribute as '\n'.join(self.buffer).
1606 1633 self.code_to_run = code
1607 1634 # now actually execute the code object
1608 1635 if self.runcode(code) == 0:
1609 1636 return False
1610 1637 else:
1611 1638 return None
1612 1639
1613 1640 def runcode(self,code_obj):
1614 1641 """Execute a code object.
1615 1642
1616 1643 When an exception occurs, self.showtraceback() is called to display a
1617 1644 traceback.
1618 1645
1619 1646 Return value: a flag indicating whether the code to be run completed
1620 1647 successfully:
1621 1648
1622 1649 - 0: successful execution.
1623 1650 - 1: an error occurred.
1624 1651 """
1625 1652
1626 1653 # Set our own excepthook in case the user code tries to call it
1627 1654 # directly, so that the IPython crash handler doesn't get triggered
1628 1655 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1629 1656 outflag = 1 # happens in more places, so it's easier as default
1630 1657 try:
1631 1658 try:
1632 exec code_obj in self.user_global_ns, self.user_ns
1659 # Embedded instances require separate global/local namespaces
1660 # so they can see both the surrounding (local) namespace and
1661 # the module-level globals when called inside another function.
1662 if self.embedded:
1663 exec code_obj in self.user_global_ns, self.user_ns
1664 # Normal (non-embedded) instances should only have a single
1665 # namespace for user code execution, otherwise functions won't
1666 # see interactive top-level globals.
1667 else:
1668 exec code_obj in self.user_ns
1633 1669 finally:
1634 1670 # Reset our crash handler in place
1635 1671 sys.excepthook = old_excepthook
1636 1672 except SystemExit:
1637 1673 self.resetbuffer()
1638 1674 self.showtraceback()
1639 1675 warn( __builtin__.exit,level=1)
1640 1676 except self.custom_exceptions:
1641 1677 etype,value,tb = sys.exc_info()
1642 1678 self.CustomTB(etype,value,tb)
1643 1679 except:
1644 1680 self.showtraceback()
1645 1681 else:
1646 1682 outflag = 0
1647 1683 if code.softspace(sys.stdout, 0):
1648 1684 print
1649 1685 # Flush out code object which has been run (and source)
1650 1686 self.code_to_run = None
1651 1687 return outflag
1652 1688
1653 1689 def raw_input(self, prompt=""):
1654 1690 """Write a prompt and read a line.
1655 1691
1656 1692 The returned line does not include the trailing newline.
1657 1693 When the user enters the EOF key sequence, EOFError is raised.
1658 1694
1659 1695 The base implementation uses the built-in function
1660 1696 raw_input(); a subclass may replace this with a different
1661 1697 implementation.
1662 1698 """
1663 1699 return self.prefilter(raw_input_original(prompt),
1664 1700 prompt==self.outputcache.prompt2)
1665 1701
1666 1702 def split_user_input(self,line):
1667 1703 """Split user input into pre-char, function part and rest."""
1668 1704
1669 1705 lsplit = self.line_split.match(line)
1670 1706 if lsplit is None: # no regexp match returns None
1671 1707 try:
1672 1708 iFun,theRest = line.split(None,1)
1673 1709 except ValueError:
1674 1710 iFun,theRest = line,''
1675 1711 pre = re.match('^(\s*)(.*)',line).groups()[0]
1676 1712 else:
1677 1713 pre,iFun,theRest = lsplit.groups()
1678 1714
1679 1715 #print 'line:<%s>' % line # dbg
1680 1716 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1681 1717 return pre,iFun.strip(),theRest
1682 1718
1683 1719 def _prefilter(self, line, continue_prompt):
1684 1720 """Calls different preprocessors, depending on the form of line."""
1685 1721
1686 1722 # All handlers *must* return a value, even if it's blank ('').
1687 1723
1688 1724 # Lines are NOT logged here. Handlers should process the line as
1689 1725 # needed, update the cache AND log it (so that the input cache array
1690 1726 # stays synced).
1691 1727
1692 1728 # This function is _very_ delicate, and since it's also the one which
1693 1729 # determines IPython's response to user input, it must be as efficient
1694 1730 # as possible. For this reason it has _many_ returns in it, trying
1695 1731 # always to exit as quickly as it can figure out what it needs to do.
1696 1732
1697 1733 # This function is the main responsible for maintaining IPython's
1698 1734 # behavior respectful of Python's semantics. So be _very_ careful if
1699 1735 # making changes to anything here.
1700 1736
1701 1737 #.....................................................................
1702 1738 # Code begins
1703 1739
1704 1740 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1705 1741
1706 1742 # save the line away in case we crash, so the post-mortem handler can
1707 1743 # record it
1708 1744 self._last_input_line = line
1709 1745
1710 1746 #print '***line: <%s>' % line # dbg
1711 1747
1712 1748 # the input history needs to track even empty lines
1713 1749 if not line.strip():
1714 1750 if not continue_prompt:
1715 1751 self.outputcache.prompt_count -= 1
1716 1752 return self.handle_normal('',continue_prompt)
1717 1753
1718 1754 # print '***cont',continue_prompt # dbg
1719 1755 # special handlers are only allowed for single line statements
1720 1756 if continue_prompt and not self.rc.multi_line_specials:
1721 1757 return self.handle_normal(line,continue_prompt)
1722 1758
1723 1759 # For the rest, we need the structure of the input
1724 1760 pre,iFun,theRest = self.split_user_input(line)
1725 1761 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1726 1762
1727 1763 # First check for explicit escapes in the last/first character
1728 1764 handler = None
1729 1765 if line[-1] == self.ESC_HELP:
1730 1766 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1731 1767 if handler is None:
1732 1768 # look at the first character of iFun, NOT of line, so we skip
1733 1769 # leading whitespace in multiline input
1734 1770 handler = self.esc_handlers.get(iFun[0:1])
1735 1771 if handler is not None:
1736 1772 return handler(line,continue_prompt,pre,iFun,theRest)
1737 1773 # Emacs ipython-mode tags certain input lines
1738 1774 if line.endswith('# PYTHON-MODE'):
1739 1775 return self.handle_emacs(line,continue_prompt)
1740 1776
1741 1777 # Next, check if we can automatically execute this thing
1742 1778
1743 1779 # Allow ! in multi-line statements if multi_line_specials is on:
1744 1780 if continue_prompt and self.rc.multi_line_specials and \
1745 1781 iFun.startswith(self.ESC_SHELL):
1746 1782 return self.handle_shell_escape(line,continue_prompt,
1747 1783 pre=pre,iFun=iFun,
1748 1784 theRest=theRest)
1749 1785
1750 1786 # Let's try to find if the input line is a magic fn
1751 1787 oinfo = None
1752 1788 if hasattr(self,'magic_'+iFun):
1753 1789 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1754 1790 if oinfo['ismagic']:
1755 1791 # Be careful not to call magics when a variable assignment is
1756 1792 # being made (ls='hi', for example)
1757 1793 if self.rc.automagic and \
1758 1794 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1759 1795 (self.rc.multi_line_specials or not continue_prompt):
1760 1796 return self.handle_magic(line,continue_prompt,
1761 1797 pre,iFun,theRest)
1762 1798 else:
1763 1799 return self.handle_normal(line,continue_prompt)
1764 1800
1765 1801 # If the rest of the line begins with an (in)equality, assginment or
1766 1802 # function call, we should not call _ofind but simply execute it.
1767 1803 # This avoids spurious geattr() accesses on objects upon assignment.
1768 1804 #
1769 1805 # It also allows users to assign to either alias or magic names true
1770 1806 # python variables (the magic/alias systems always take second seat to
1771 1807 # true python code).
1772 1808 if theRest and theRest[0] in '!=()':
1773 1809 return self.handle_normal(line,continue_prompt)
1774 1810
1775 1811 if oinfo is None:
1776 1812 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1777 1813
1778 1814 if not oinfo['found']:
1779 1815 return self.handle_normal(line,continue_prompt)
1780 1816 else:
1781 1817 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1782 1818 if oinfo['isalias']:
1783 1819 return self.handle_alias(line,continue_prompt,
1784 1820 pre,iFun,theRest)
1785 1821
1786 1822 if self.rc.autocall and \
1787 1823 not self.re_exclude_auto.match(theRest) and \
1788 1824 self.re_fun_name.match(iFun) and \
1789 1825 callable(oinfo['obj']) :
1790 1826 #print 'going auto' # dbg
1791 1827 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1792 1828 else:
1793 1829 #print 'was callable?', callable(oinfo['obj']) # dbg
1794 1830 return self.handle_normal(line,continue_prompt)
1795 1831
1796 1832 # If we get here, we have a normal Python line. Log and return.
1797 1833 return self.handle_normal(line,continue_prompt)
1798 1834
1799 1835 def _prefilter_dumb(self, line, continue_prompt):
1800 1836 """simple prefilter function, for debugging"""
1801 1837 return self.handle_normal(line,continue_prompt)
1802 1838
1803 1839 # Set the default prefilter() function (this can be user-overridden)
1804 1840 prefilter = _prefilter
1805 1841
1806 1842 def handle_normal(self,line,continue_prompt=None,
1807 1843 pre=None,iFun=None,theRest=None):
1808 1844 """Handle normal input lines. Use as a template for handlers."""
1809 1845
1810 1846 self.log(line,continue_prompt)
1811 1847 self.update_cache(line)
1812 1848 return line
1813 1849
1814 1850 def handle_alias(self,line,continue_prompt=None,
1815 1851 pre=None,iFun=None,theRest=None):
1816 1852 """Handle alias input lines. """
1817 1853
1818 1854 theRest = esc_quotes(theRest)
1819 1855 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1820 1856 self.log(line_out,continue_prompt)
1821 1857 self.update_cache(line_out)
1822 1858 return line_out
1823 1859
1824 1860 def handle_shell_escape(self, line, continue_prompt=None,
1825 1861 pre=None,iFun=None,theRest=None):
1826 1862 """Execute the line in a shell, empty return value"""
1827 1863
1828 1864 #print 'line in :', `line` # dbg
1829 1865 # Example of a special handler. Others follow a similar pattern.
1830 1866 if continue_prompt: # multi-line statements
1831 1867 if iFun.startswith('!!'):
1832 1868 print 'SyntaxError: !! is not allowed in multiline statements'
1833 1869 return pre
1834 1870 else:
1835 1871 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1836 1872 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1837 1873 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1838 1874 else: # single-line input
1839 1875 if line.startswith('!!'):
1840 1876 # rewrite iFun/theRest to properly hold the call to %sx and
1841 1877 # the actual command to be executed, so handle_magic can work
1842 1878 # correctly
1843 1879 theRest = '%s %s' % (iFun[2:],theRest)
1844 1880 iFun = 'sx'
1845 1881 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1846 1882 continue_prompt,pre,iFun,theRest)
1847 1883 else:
1848 1884 cmd = esc_quotes(line[1:])
1849 1885 line_out = '%s.system("%s")' % (self.name,cmd)
1850 1886 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1851 1887 # update cache/log and return
1852 1888 self.log(line_out,continue_prompt)
1853 1889 self.update_cache(line_out) # readline cache gets normal line
1854 1890 #print 'line out r:', `line_out` # dbg
1855 1891 #print 'line out s:', line_out # dbg
1856 1892 return line_out
1857 1893
1858 1894 def handle_magic(self, line, continue_prompt=None,
1859 1895 pre=None,iFun=None,theRest=None):
1860 1896 """Execute magic functions.
1861 1897
1862 1898 Also log them with a prepended # so the log is clean Python."""
1863 1899
1864 1900 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1865 1901 self.log(cmd,continue_prompt)
1866 1902 self.update_cache(line)
1867 1903 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1868 1904 return cmd
1869 1905
1870 1906 def handle_auto(self, line, continue_prompt=None,
1871 1907 pre=None,iFun=None,theRest=None):
1872 1908 """Hande lines which can be auto-executed, quoting if requested."""
1873 1909
1874 1910 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1875 1911
1876 1912 # This should only be active for single-line input!
1877 1913 if continue_prompt:
1878 1914 return line
1879 1915
1880 1916 if pre == self.ESC_QUOTE:
1881 1917 # Auto-quote splitting on whitespace
1882 1918 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1883 1919 elif pre == self.ESC_QUOTE2:
1884 1920 # Auto-quote whole string
1885 1921 newcmd = '%s("%s")' % (iFun,theRest)
1886 1922 else:
1887 1923 # Auto-paren
1888 1924 if theRest[0:1] in ('=','['):
1889 1925 # Don't autocall in these cases. They can be either
1890 1926 # rebindings of an existing callable's name, or item access
1891 1927 # for an object which is BOTH callable and implements
1892 1928 # __getitem__.
1893 1929 return '%s %s' % (iFun,theRest)
1894 1930 if theRest.endswith(';'):
1895 1931 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1896 1932 else:
1897 1933 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1898 1934
1899 1935 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1900 1936 # log what is now valid Python, not the actual user input (without the
1901 1937 # final newline)
1902 1938 self.log(newcmd,continue_prompt)
1903 1939 return newcmd
1904 1940
1905 1941 def handle_help(self, line, continue_prompt=None,
1906 1942 pre=None,iFun=None,theRest=None):
1907 1943 """Try to get some help for the object.
1908 1944
1909 1945 obj? or ?obj -> basic information.
1910 1946 obj?? or ??obj -> more details.
1911 1947 """
1912 1948
1913 1949 # We need to make sure that we don't process lines which would be
1914 1950 # otherwise valid python, such as "x=1 # what?"
1915 1951 try:
1916 1952 code.compile_command(line)
1917 1953 except SyntaxError:
1918 1954 # We should only handle as help stuff which is NOT valid syntax
1919 1955 if line[0]==self.ESC_HELP:
1920 1956 line = line[1:]
1921 1957 elif line[-1]==self.ESC_HELP:
1922 1958 line = line[:-1]
1923 1959 self.log('#?'+line)
1924 1960 self.update_cache(line)
1925 1961 if line:
1926 1962 self.magic_pinfo(line)
1927 1963 else:
1928 1964 page(self.usage,screen_lines=self.rc.screen_length)
1929 1965 return '' # Empty string is needed here!
1930 1966 except:
1931 1967 # Pass any other exceptions through to the normal handler
1932 1968 return self.handle_normal(line,continue_prompt)
1933 1969 else:
1934 1970 # If the code compiles ok, we should handle it normally
1935 1971 return self.handle_normal(line,continue_prompt)
1936 1972
1937 1973 def handle_emacs(self,line,continue_prompt=None,
1938 1974 pre=None,iFun=None,theRest=None):
1939 1975 """Handle input lines marked by python-mode."""
1940 1976
1941 1977 # Currently, nothing is done. Later more functionality can be added
1942 1978 # here if needed.
1943 1979
1944 1980 # The input cache shouldn't be updated
1945 1981
1946 1982 return line
1947 1983
1948 1984 def write(self,data):
1949 1985 """Write a string to the default output"""
1950 1986 Term.cout.write(data)
1951 1987
1952 1988 def write_err(self,data):
1953 1989 """Write a string to the default error output"""
1954 1990 Term.cerr.write(data)
1955 1991
1956 1992 def safe_execfile(self,fname,*where,**kw):
1957 1993 fname = os.path.expanduser(fname)
1958 1994
1959 1995 # find things also in current directory
1960 1996 dname = os.path.dirname(fname)
1961 1997 if not sys.path.count(dname):
1962 1998 sys.path.append(dname)
1963 1999
1964 2000 try:
1965 2001 xfile = open(fname)
1966 2002 except:
1967 2003 print >> Term.cerr, \
1968 2004 'Could not open file <%s> for safe execution.' % fname
1969 2005 return None
1970 2006
1971 2007 kw.setdefault('islog',0)
1972 2008 kw.setdefault('quiet',1)
1973 2009 kw.setdefault('exit_ignore',0)
1974 2010 first = xfile.readline()
1975 2011 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1976 2012 xfile.close()
1977 2013 # line by line execution
1978 2014 if first.startswith(_LOGHEAD) or kw['islog']:
1979 2015 print 'Loading log file <%s> one line at a time...' % fname
1980 2016 if kw['quiet']:
1981 2017 stdout_save = sys.stdout
1982 2018 sys.stdout = StringIO.StringIO()
1983 2019 try:
1984 2020 globs,locs = where[0:2]
1985 2021 except:
1986 2022 try:
1987 2023 globs = locs = where[0]
1988 2024 except:
1989 2025 globs = locs = globals()
1990 2026 badblocks = []
1991 2027
1992 2028 # we also need to identify indented blocks of code when replaying
1993 2029 # logs and put them together before passing them to an exec
1994 2030 # statement. This takes a bit of regexp and look-ahead work in the
1995 2031 # file. It's easiest if we swallow the whole thing in memory
1996 2032 # first, and manually walk through the lines list moving the
1997 2033 # counter ourselves.
1998 2034 indent_re = re.compile('\s+\S')
1999 2035 xfile = open(fname)
2000 2036 filelines = xfile.readlines()
2001 2037 xfile.close()
2002 2038 nlines = len(filelines)
2003 2039 lnum = 0
2004 2040 while lnum < nlines:
2005 2041 line = filelines[lnum]
2006 2042 lnum += 1
2007 2043 # don't re-insert logger status info into cache
2008 2044 if line.startswith('#log#'):
2009 2045 continue
2010 2046 elif line.startswith('#%s'% self.ESC_MAGIC):
2011 2047 self.update_cache(line[1:])
2012 2048 line = magic2python(line)
2013 2049 elif line.startswith('#!'):
2014 2050 self.update_cache(line[1:])
2015 2051 else:
2016 2052 # build a block of code (maybe a single line) for execution
2017 2053 block = line
2018 2054 try:
2019 2055 next = filelines[lnum] # lnum has already incremented
2020 2056 except:
2021 2057 next = None
2022 2058 while next and indent_re.match(next):
2023 2059 block += next
2024 2060 lnum += 1
2025 2061 try:
2026 2062 next = filelines[lnum]
2027 2063 except:
2028 2064 next = None
2029 2065 # now execute the block of one or more lines
2030 2066 try:
2031 2067 exec block in globs,locs
2032 2068 self.update_cache(block.rstrip())
2033 2069 except SystemExit:
2034 2070 pass
2035 2071 except:
2036 2072 badblocks.append(block.rstrip())
2037 2073 if kw['quiet']: # restore stdout
2038 2074 sys.stdout.close()
2039 2075 sys.stdout = stdout_save
2040 2076 print 'Finished replaying log file <%s>' % fname
2041 2077 if badblocks:
2042 2078 print >> sys.stderr, \
2043 2079 '\nThe following lines/blocks in file <%s> reported errors:' \
2044 2080 % fname
2045 2081 for badline in badblocks:
2046 2082 print >> sys.stderr, badline
2047 2083 else: # regular file execution
2048 2084 try:
2049 2085 execfile(fname,*where)
2050 2086 except SyntaxError:
2051 2087 etype, evalue = sys.exc_info()[0:2]
2052 2088 self.SyntaxTB(etype,evalue,[])
2053 2089 warn('Failure executing file: <%s>' % fname)
2054 2090 except SystemExit,status:
2055 2091 if not kw['exit_ignore']:
2056 2092 self.InteractiveTB()
2057 2093 warn('Failure executing file: <%s>' % fname)
2058 2094 except:
2059 2095 self.InteractiveTB()
2060 2096 warn('Failure executing file: <%s>' % fname)
2061 2097
2062 2098 #************************* end of file <iplib.py> *****************************
@@ -1,727 +1,734 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or better.
6 6
7 7 This file contains the main make_IPython() starter function.
8 8
9 $Id: ipmaker.py 911 2005-10-08 07:59:40Z fperez $"""
9 $Id: ipmaker.py 923 2005-11-15 08:51:15Z fperez $"""
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001-2004 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
18 18 from IPython import Release
19 19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 20 __license__ = Release.license
21 21 __version__ = Release.version
22 22
23 23 credits._Printer__data = """
24 24 Python: %s
25 25
26 26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 27 See http://ipython.scipy.org for more information.""" \
28 28 % credits._Printer__data
29 29
30 30 copyright._Printer__data += """
31 31
32 32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 33 All Rights Reserved."""
34 34
35 35 #****************************************************************************
36 36 # Required modules
37 37
38 38 # From the standard library
39 39 import __main__, __builtin__
40 40 import os,sys,types,re
41 41 from pprint import pprint,pformat
42 42
43 43 # Our own
44 44 from IPython import DPyGetOpt
45 45 from IPython.Struct import Struct
46 46 from IPython.OutputTrap import OutputTrap
47 47 from IPython.ConfigLoader import ConfigLoader
48 48 from IPython.iplib import InteractiveShell,qw_lol,import_fail_info
49 49 from IPython.usage import cmd_line_usage,interactive_usage
50 50 from IPython.Prompts import CachedOutput
51 51 from IPython.genutils import *
52 52
53 53 #-----------------------------------------------------------------------------
54 54 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
55 55 shell_class=InteractiveShell,embedded=False,**kw):
56 56 """This is a dump of IPython into a single function.
57 57
58 58 Later it will have to be broken up in a sensible manner.
59 59
60 60 Arguments:
61 61
62 62 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
63 63 script name, b/c DPyGetOpt strips the first argument only for the real
64 64 sys.argv.
65 65
66 66 - user_ns: a dict to be used as the user's namespace."""
67 67
68 68 #----------------------------------------------------------------------
69 69 # Defaults and initialization
70 70
71 71 # For developer debugging, deactivates crash handler and uses pdb.
72 72 DEVDEBUG = False
73 73
74 74 if argv is None:
75 75 argv = sys.argv
76 76
77 77 # __IP is the main global that lives throughout and represents the whole
78 78 # application. If the user redefines it, all bets are off as to what
79 79 # happens.
80 80
81 81 # __IP is the name of he global which the caller will have accessible as
82 82 # __IP.name. We set its name via the first parameter passed to
83 83 # InteractiveShell:
84 84
85 IP = shell_class('__IP',user_ns=user_ns,**kw)
85 IP = shell_class('__IP',user_ns=user_ns,embedded=embedded,**kw)
86 86
87 87 # Put 'help' in the user namespace
88 88 from site import _Helper
89 89 IP.user_ns['help'] = _Helper()
90 90
91 91 if DEVDEBUG:
92 92 # For developer debugging only (global flag)
93 93 from IPython import ultraTB
94 94 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
95 95 else:
96 96 # IPython itself shouldn't crash. This will produce a detailed
97 97 # post-mortem if it does
98 98 from IPython import CrashHandler
99 99 sys.excepthook = CrashHandler.CrashHandler(IP)
100 100
101 101 IP.BANNER_PARTS = ['Python %s\n'
102 102 'Type "copyright", "credits" or "license" '
103 103 'for more information.\n'
104 104 % (sys.version.split('\n')[0],),
105 105 "IPython %s -- An enhanced Interactive Python."
106 106 % (__version__,),
107 107 """? -> Introduction to IPython's features.
108 108 %magic -> Information about IPython's 'magic' % functions.
109 109 help -> Python's own help system.
110 110 object? -> Details about 'object'. ?object also works, ?? prints more.
111 111 """ ]
112 112
113 113 IP.usage = interactive_usage
114 114
115 115 # Platform-dependent suffix and directory names. We use _ipython instead
116 116 # of .ipython under win32 b/c there's software that breaks with .named
117 117 # directories on that platform.
118 118 if os.name == 'posix':
119 119 rc_suffix = ''
120 120 ipdir_def = '.ipython'
121 121 else:
122 122 rc_suffix = '.ini'
123 123 ipdir_def = '_ipython'
124 124
125 125 # default directory for configuration
126 126 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
127 127 os.path.join(IP.home_dir,ipdir_def)))
128 128
129 129 # we need the directory where IPython itself is installed
130 130 import IPython
131 131 IPython_dir = os.path.dirname(IPython.__file__)
132 132 del IPython
133 133
134 134 #-------------------------------------------------------------------------
135 135 # Command line handling
136 136
137 137 # Valid command line options (uses DPyGetOpt syntax, like Perl's
138 138 # GetOpt::Long)
139 139
140 140 # Any key not listed here gets deleted even if in the file (like session
141 141 # or profile). That's deliberate, to maintain the rc namespace clean.
142 142
143 143 # Each set of options appears twice: under _conv only the names are
144 144 # listed, indicating which type they must be converted to when reading the
145 145 # ipythonrc file. And under DPyGetOpt they are listed with the regular
146 146 # DPyGetOpt syntax (=s,=i,:f,etc).
147 147
148 148 # Make sure there's a space before each end of line (they get auto-joined!)
149 149 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
150 150 'c=s classic|cl color_info! colors=s confirm_exit! '
151 151 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
152 152 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
153 153 'quick screen_length|sl=i prompts_pad_left=i '
154 154 'logfile|lf=s logplay|lp=s profile|p=s '
155 155 'readline! readline_merge_completions! '
156 156 'readline_omit__names! '
157 157 'rcfile=s separate_in|si=s separate_out|so=s '
158 'separate_out2|so2=s xmode=s '
158 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
159 159 'magic_docstrings system_verbose! '
160 160 'multi_line_specials!')
161 161
162 162 # Options that can *only* appear at the cmd line (not in rcfiles).
163 163
164 164 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
165 165 # the 'C-c !' command in emacs automatically appends a -i option at the end.
166 166 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
167 167 'gthread! qthread! wthread! pylab! tk!')
168 168
169 169 # Build the actual name list to be used by DPyGetOpt
170 170 opts_names = qw(cmdline_opts) + qw(cmdline_only)
171 171
172 172 # Set sensible command line defaults.
173 173 # This should have everything from cmdline_opts and cmdline_only
174 174 opts_def = Struct(autocall = 1,
175 175 autoindent=0,
176 176 automagic = 1,
177 177 banner = 1,
178 178 cache_size = 1000,
179 179 c = '',
180 180 classic = 0,
181 181 colors = 'NoColor',
182 182 color_info = 0,
183 183 confirm_exit = 1,
184 184 debug = 0,
185 185 deep_reload = 0,
186 186 editor = '0',
187 187 help = 0,
188 188 ignore = 0,
189 189 ipythondir = ipythondir,
190 190 log = 0,
191 191 logfile = '',
192 192 logplay = '',
193 193 multi_line_specials = 1,
194 194 messages = 1,
195 195 nosep = 0,
196 196 pdb = 0,
197 197 pprint = 0,
198 198 profile = '',
199 199 prompt_in1 = 'In [\\#]: ',
200 200 prompt_in2 = ' .\\D.: ',
201 201 prompt_out = 'Out[\\#]: ',
202 202 prompts_pad_left = 1,
203 203 quick = 0,
204 204 readline = 1,
205 205 readline_merge_completions = 1,
206 206 readline_omit__names = 0,
207 207 rcfile = 'ipythonrc' + rc_suffix,
208 208 screen_length = 0,
209 209 separate_in = '\n',
210 210 separate_out = '\n',
211 211 separate_out2 = '',
212 212 system_verbose = 0,
213 213 gthread = 0,
214 214 qthread = 0,
215 215 wthread = 0,
216 216 pylab = 0,
217 217 tk = 0,
218 218 upgrade = 0,
219 219 Version = 0,
220 220 xmode = 'Verbose',
221 wildcards_case_sensitive = 1,
221 222 magic_docstrings = 0, # undocumented, for doc generation
222 223 )
223 224
224 225 # Things that will *only* appear in rcfiles (not at the command line).
225 226 # Make sure there's a space before each end of line (they get auto-joined!)
226 227 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
227 228 qw_lol: 'import_some ',
228 229 # for things with embedded whitespace:
229 230 list_strings:'execute alias readline_parse_and_bind ',
230 231 # Regular strings need no conversion:
231 232 None:'readline_remove_delims ',
232 233 }
233 234 # Default values for these
234 235 rc_def = Struct(include = [],
235 236 import_mod = [],
236 237 import_all = [],
237 238 import_some = [[]],
238 239 execute = [],
239 240 execfile = [],
240 241 alias = [],
241 242 readline_parse_and_bind = [],
242 243 readline_remove_delims = '',
243 244 )
244 245
245 246 # Build the type conversion dictionary from the above tables:
246 247 typeconv = rcfile_opts.copy()
247 248 typeconv.update(optstr2types(cmdline_opts))
248 249
249 250 # FIXME: the None key appears in both, put that back together by hand. Ugly!
250 251 typeconv[None] += ' ' + rcfile_opts[None]
251 252
252 253 # Remove quotes at ends of all strings (used to protect spaces)
253 254 typeconv[unquote_ends] = typeconv[None]
254 255 del typeconv[None]
255 256
256 257 # Build the list we'll use to make all config decisions with defaults:
257 258 opts_all = opts_def.copy()
258 259 opts_all.update(rc_def)
259 260
260 261 # Build conflict resolver for recursive loading of config files:
261 262 # - preserve means the outermost file maintains the value, it is not
262 263 # overwritten if an included file has the same key.
263 264 # - add_flip applies + to the two values, so it better make sense to add
264 265 # those types of keys. But it flips them first so that things loaded
265 266 # deeper in the inclusion chain have lower precedence.
266 267 conflict = {'preserve': ' '.join([ typeconv[int],
267 268 typeconv[unquote_ends] ]),
268 269 'add_flip': ' '.join([ typeconv[qwflat],
269 270 typeconv[qw_lol],
270 271 typeconv[list_strings] ])
271 272 }
272 273
273 274 # Now actually process the command line
274 275 getopt = DPyGetOpt.DPyGetOpt()
275 276 getopt.setIgnoreCase(0)
276 277
277 278 getopt.parseConfiguration(opts_names)
278 279
279 280 try:
280 281 getopt.processArguments(argv)
281 282 except:
282 283 print cmd_line_usage
283 284 warn('\nError in Arguments: ' + `sys.exc_value`)
284 sys.exit()
285 sys.exit(1)
285 286
286 287 # convert the options dict to a struct for much lighter syntax later
287 288 opts = Struct(getopt.optionValues)
288 289 args = getopt.freeValues
289 290
290 291 # this is the struct (which has default values at this point) with which
291 292 # we make all decisions:
292 293 opts_all.update(opts)
293 294
294 295 # Options that force an immediate exit
295 296 if opts_all.help:
296 297 page(cmd_line_usage)
297 298 sys.exit()
298 299
299 300 if opts_all.Version:
300 301 print __version__
301 302 sys.exit()
302 303
303 304 if opts_all.magic_docstrings:
304 305 IP.magic_magic('-latex')
305 306 sys.exit()
306 307
307 308 # Create user config directory if it doesn't exist. This must be done
308 309 # *after* getting the cmd line options.
309 310 if not os.path.isdir(opts_all.ipythondir):
310 311 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
311 312
312 313 # upgrade user config files while preserving a copy of the originals
313 314 if opts_all.upgrade:
314 315 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
315 316
316 317 # check mutually exclusive options in the *original* command line
317 318 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
318 319 qw('classic profile'),qw('classic rcfile')])
319 320
320 321 # default logfilename used when -log is called.
321 322 IP.LOGDEF = 'ipython.log'
322 323
323 324 #---------------------------------------------------------------------------
324 325 # Log replay
325 326
326 327 # if -logplay, we need to 'become' the other session. That basically means
327 328 # replacing the current command line environment with that of the old
328 329 # session and moving on.
329 330
330 331 # this is needed so that later we know we're in session reload mode, as
331 332 # opts_all will get overwritten:
332 333 load_logplay = 0
333 334
334 335 if opts_all.logplay:
335 336 load_logplay = opts_all.logplay
336 337 opts_debug_save = opts_all.debug
337 338 try:
338 339 logplay = open(opts_all.logplay)
339 340 except IOError:
340 341 if opts_all.debug: IP.InteractiveTB()
341 342 warn('Could not open logplay file '+`opts_all.logplay`)
342 343 # restore state as if nothing had happened and move on, but make
343 344 # sure that later we don't try to actually load the session file
344 345 logplay = None
345 346 load_logplay = 0
346 347 del opts_all.logplay
347 348 else:
348 349 try:
349 350 logplay.readline()
350 351 logplay.readline();
351 352 # this reloads that session's command line
352 353 cmd = logplay.readline()[6:]
353 354 exec cmd
354 355 # restore the true debug flag given so that the process of
355 356 # session loading itself can be monitored.
356 357 opts.debug = opts_debug_save
357 358 # save the logplay flag so later we don't overwrite the log
358 359 opts.logplay = load_logplay
359 360 # now we must update our own structure with defaults
360 361 opts_all.update(opts)
361 362 # now load args
362 363 cmd = logplay.readline()[6:]
363 364 exec cmd
364 365 logplay.close()
365 366 except:
366 367 logplay.close()
367 368 if opts_all.debug: IP.InteractiveTB()
368 369 warn("Logplay file lacking full configuration information.\n"
369 370 "I'll try to read it, but some things may not work.")
370 371
371 372 #-------------------------------------------------------------------------
372 373 # set up output traps: catch all output from files, being run, modules
373 374 # loaded, etc. Then give it to the user in a clean form at the end.
374 375
375 376 msg_out = 'Output messages. '
376 377 msg_err = 'Error messages. '
377 378 msg_sep = '\n'
378 379 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
379 380 msg_err,msg_sep,debug,
380 381 quiet_out=1),
381 382 user_exec = OutputTrap('User File Execution',msg_out,
382 383 msg_err,msg_sep,debug),
383 384 logplay = OutputTrap('Log Loader',msg_out,
384 385 msg_err,msg_sep,debug),
385 386 summary = ''
386 387 )
387 388
388 389 #-------------------------------------------------------------------------
389 390 # Process user ipythonrc-type configuration files
390 391
391 392 # turn on output trapping and log to msg.config
392 393 # remember that with debug on, trapping is actually disabled
393 394 msg.config.trap_all()
394 395
395 396 # look for rcfile in current or default directory
396 397 try:
397 398 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
398 399 except IOError:
399 400 if opts_all.debug: IP.InteractiveTB()
400 401 warn('Configuration file %s not found. Ignoring request.'
401 402 % (opts_all.rcfile) )
402 403
403 404 # 'profiles' are a shorthand notation for config filenames
404 405 if opts_all.profile:
405 406 try:
406 407 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
407 408 + rc_suffix,
408 409 opts_all.ipythondir)
409 410 except IOError:
410 411 if opts_all.debug: IP.InteractiveTB()
411 412 opts.profile = '' # remove profile from options if invalid
412 413 warn('Profile configuration file %s not found. Ignoring request.'
413 414 % (opts_all.profile) )
414 415
415 416 # load the config file
416 417 rcfiledata = None
417 418 if opts_all.quick:
418 419 print 'Launching IPython in quick mode. No config file read.'
419 420 elif opts_all.classic:
420 421 print 'Launching IPython in classic mode. No config file read.'
421 422 elif opts_all.rcfile:
422 423 try:
423 424 cfg_loader = ConfigLoader(conflict)
424 425 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
425 426 'include',opts_all.ipythondir,
426 427 purge = 1,
427 428 unique = conflict['preserve'])
428 429 except:
429 430 IP.InteractiveTB()
430 431 warn('Problems loading configuration file '+
431 432 `opts_all.rcfile`+
432 433 '\nStarting with default -bare bones- configuration.')
433 434 else:
434 435 warn('No valid configuration file found in either currrent directory\n'+
435 436 'or in the IPython config. directory: '+`opts_all.ipythondir`+
436 437 '\nProceeding with internal defaults.')
437 438
438 439 #------------------------------------------------------------------------
439 440 # Set exception handlers in mode requested by user.
440 441 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
441 442 IP.magic_xmode(opts_all.xmode)
442 443 otrap.release_out()
443 444
444 445 #------------------------------------------------------------------------
445 446 # Execute user config
446 447
447 448 # first, create a valid config structure with the right precedence order:
448 # defaults < rcfile < command line
449 IP.rc = rc_def.copy()
450 IP.rc.update(opts_def)
449 # defaults < rcfile < command line. We make it as a local (IP_rc) to
450 # avoid a zillion attribute accesses. Right before returning, this will
451 # be set as IP.rc.
452 IP_rc = rc_def.copy()
453 IP_rc.update(opts_def)
451 454 if rcfiledata:
452 455 # now we can update
453 IP.rc.update(rcfiledata)
454 IP.rc.update(opts)
455 IP.rc.update(rc_override)
456 IP_rc.update(rcfiledata)
457 IP_rc.update(opts)
458 IP_rc.update(rc_override)
456 459
457 460 # Store the original cmd line for reference:
458 IP.rc.opts = opts
459 IP.rc.args = args
461 IP_rc.opts = opts
462 IP_rc.args = args
460 463
461 464 # create a *runtime* Struct like rc for holding parameters which may be
462 465 # created and/or modified by runtime user extensions.
463 466 IP.runtime_rc = Struct()
464 467
465 # from this point on, all config should be handled through IP.rc,
468 # from this point on, all config should be handled through IP_rc,
466 469 # opts* shouldn't be used anymore.
467 470
468 471 # add personal .ipython dir to sys.path so that users can put things in
469 472 # there for customization
470 sys.path.append(IP.rc.ipythondir)
473 sys.path.append(IP_rc.ipythondir)
471 474 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
472 475
473 # update IP.rc with some special things that need manual
476 # update IP_rc with some special things that need manual
474 477 # tweaks. Basically options which affect other options. I guess this
475 478 # should just be written so that options are fully orthogonal and we
476 479 # wouldn't worry about this stuff!
477 480
478 if IP.rc.classic:
479 IP.rc.quick = 1
480 IP.rc.cache_size = 0
481 IP.rc.pprint = 0
482 IP.rc.prompt_in1 = '>>> '
483 IP.rc.prompt_in2 = '... '
484 IP.rc.prompt_out = ''
485 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
486 IP.rc.colors = 'NoColor'
487 IP.rc.xmode = 'Plain'
481 if IP_rc.classic:
482 IP_rc.quick = 1
483 IP_rc.cache_size = 0
484 IP_rc.pprint = 0
485 IP_rc.prompt_in1 = '>>> '
486 IP_rc.prompt_in2 = '... '
487 IP_rc.prompt_out = ''
488 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
489 IP_rc.colors = 'NoColor'
490 IP_rc.xmode = 'Plain'
488 491
489 492 # configure readline
490 493 # Define the history file for saving commands in between sessions
491 if IP.rc.profile:
492 histfname = 'history-%s' % IP.rc.profile
494 if IP_rc.profile:
495 histfname = 'history-%s' % IP_rc.profile
493 496 else:
494 497 histfname = 'history'
495 498 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
496 # Load readline proper
497 if IP.rc.readline:
498 IP.init_readline()
499 499
500 500 # update exception handlers with rc file status
501 501 otrap.trap_out() # I don't want these messages ever.
502 IP.magic_xmode(IP.rc.xmode)
502 IP.magic_xmode(IP_rc.xmode)
503 503 otrap.release_out()
504 504
505 505 # activate logging if requested and not reloading a log
506 if IP.rc.logplay:
507 IP.magic_logstart(IP.rc.logplay + ' append')
508 elif IP.rc.logfile:
509 IP.magic_logstart(IP.rc.logfile)
510 elif IP.rc.log:
506 if IP_rc.logplay:
507 IP.magic_logstart(IP_rc.logplay + ' append')
508 elif IP_rc.logfile:
509 IP.magic_logstart(IP_rc.logfile)
510 elif IP_rc.log:
511 511 IP.magic_logstart()
512 512
513 513 # find user editor so that it we don't have to look it up constantly
514 if IP.rc.editor.strip()=='0':
514 if IP_rc.editor.strip()=='0':
515 515 try:
516 516 ed = os.environ['EDITOR']
517 517 except KeyError:
518 518 if os.name == 'posix':
519 519 ed = 'vi' # the only one guaranteed to be there!
520 520 else:
521 521 ed = 'notepad' # same in Windows!
522 IP.rc.editor = ed
522 IP_rc.editor = ed
523
524 # Keep track of whether this is an embedded instance or not (useful for
525 # post-mortems).
526 IP_rc.embedded = IP.embedded
523 527
524 528 # Recursive reload
525 529 try:
526 530 from IPython import deep_reload
527 if IP.rc.deep_reload:
531 if IP_rc.deep_reload:
528 532 __builtin__.reload = deep_reload.reload
529 533 else:
530 534 __builtin__.dreload = deep_reload.reload
531 535 del deep_reload
532 536 except ImportError:
533 537 pass
534 538
535 539 # Save the current state of our namespace so that the interactive shell
536 540 # can later know which variables have been created by us from config files
537 541 # and loading. This way, loading a file (in any way) is treated just like
538 542 # defining things on the command line, and %who works as expected.
539 543
540 544 # DON'T do anything that affects the namespace beyond this point!
541 IP.internal_ns = __main__.__dict__.copy()
545 IP.internal_ns.update(__main__.__dict__)
542 546
543 547 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
544 548
545 549 # Now run through the different sections of the users's config
546 if IP.rc.debug:
550 if IP_rc.debug:
547 551 print 'Trying to execute the following configuration structure:'
548 552 print '(Things listed first are deeper in the inclusion tree and get'
549 553 print 'loaded first).\n'
550 pprint(IP.rc.__dict__)
554 pprint(IP_rc.__dict__)
551 555
552 for mod in IP.rc.import_mod:
556 for mod in IP_rc.import_mod:
553 557 try:
554 558 exec 'import '+mod in IP.user_ns
555 559 except :
556 560 IP.InteractiveTB()
557 561 import_fail_info(mod)
558 562
559 for mod_fn in IP.rc.import_some:
563 for mod_fn in IP_rc.import_some:
560 564 if mod_fn == []: break
561 565 mod,fn = mod_fn[0],','.join(mod_fn[1:])
562 566 try:
563 567 exec 'from '+mod+' import '+fn in IP.user_ns
564 568 except :
565 569 IP.InteractiveTB()
566 570 import_fail_info(mod,fn)
567 571
568 for mod in IP.rc.import_all:
572 for mod in IP_rc.import_all:
569 573 try:
570 574 exec 'from '+mod+' import *' in IP.user_ns
571 575 except :
572 576 IP.InteractiveTB()
573 577 import_fail_info(mod)
574 578
575 for code in IP.rc.execute:
579 for code in IP_rc.execute:
576 580 try:
577 581 exec code in IP.user_ns
578 582 except:
579 583 IP.InteractiveTB()
580 584 warn('Failure executing code: ' + `code`)
581 585
582 586 # Execute the files the user wants in ipythonrc
583 for file in IP.rc.execfile:
587 for file in IP_rc.execfile:
584 588 try:
585 589 file = filefind(file,sys.path+[IPython_dir])
586 590 except IOError:
587 591 warn(itpl('File $file not found. Skipping it.'))
588 592 else:
589 593 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
590 594
591 595 # Load user aliases
592 for alias in IP.rc.alias:
596 for alias in IP_rc.alias:
593 597 IP.magic_alias(alias)
594 598
595 599 # release stdout and stderr and save config log into a global summary
596 600 msg.config.release_all()
597 if IP.rc.messages:
601 if IP_rc.messages:
598 602 msg.summary += msg.config.summary_all()
599 603
600 604 #------------------------------------------------------------------------
601 605 # Setup interactive session
602 606
603 607 # Now we should be fully configured. We can then execute files or load
604 608 # things only needed for interactive use. Then we'll open the shell.
605 609
606 610 # Take a snapshot of the user namespace before opening the shell. That way
607 611 # we'll be able to identify which things were interactively defined and
608 612 # which were defined through config files.
609 613 IP.user_config_ns = IP.user_ns.copy()
610 614
611 615 # Force reading a file as if it were a session log. Slower but safer.
612 616 if load_logplay:
613 617 print 'Replaying log...'
614 618 try:
615 if IP.rc.debug:
619 if IP_rc.debug:
616 620 logplay_quiet = 0
617 621 else:
618 622 logplay_quiet = 1
619 623
620 624 msg.logplay.trap_all()
621 625 IP.safe_execfile(load_logplay,IP.user_ns,
622 626 islog = 1, quiet = logplay_quiet)
623 627 msg.logplay.release_all()
624 if IP.rc.messages:
628 if IP_rc.messages:
625 629 msg.summary += msg.logplay.summary_all()
626 630 except:
627 631 warn('Problems replaying logfile %s.' % load_logplay)
628 632 IP.InteractiveTB()
629 633
630 634 # Load remaining files in command line
631 635 msg.user_exec.trap_all()
632 636
633 637 # Do NOT execute files named in the command line as scripts to be loaded
634 638 # by embedded instances. Doing so has the potential for an infinite
635 639 # recursion if there are exceptions thrown in the process.
636 640
637 641 # XXX FIXME: the execution of user files should be moved out to after
638 642 # ipython is fully initialized, just as if they were run via %run at the
639 643 # ipython prompt. This would also give them the benefit of ipython's
640 644 # nice tracebacks.
641 645
642 if not embedded and IP.rc.args:
646 if not embedded and IP_rc.args:
643 647 name_save = IP.user_ns['__name__']
644 648 IP.user_ns['__name__'] = '__main__'
645 649 try:
646 650 # Set our own excepthook in case the user code tries to call it
647 651 # directly. This prevents triggering the IPython crash handler.
648 652 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
649 653 for run in args:
650 654 IP.safe_execfile(run,IP.user_ns)
651 655 finally:
652 656 # Reset our crash handler in place
653 657 sys.excepthook = old_excepthook
654 658
655 659 IP.user_ns['__name__'] = name_save
656 660
657 661 msg.user_exec.release_all()
658 if IP.rc.messages:
662 if IP_rc.messages:
659 663 msg.summary += msg.user_exec.summary_all()
660 664
661 665 # since we can't specify a null string on the cmd line, 0 is the equivalent:
662 if IP.rc.nosep:
663 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
664 if IP.rc.separate_in == '0': IP.rc.separate_in = ''
665 if IP.rc.separate_out == '0': IP.rc.separate_out = ''
666 if IP.rc.separate_out2 == '0': IP.rc.separate_out2 = ''
667 IP.rc.separate_in = IP.rc.separate_in.replace('\\n','\n')
668 IP.rc.separate_out = IP.rc.separate_out.replace('\\n','\n')
669 IP.rc.separate_out2 = IP.rc.separate_out2.replace('\\n','\n')
666 if IP_rc.nosep:
667 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
668 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
669 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
670 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
671 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
672 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
673 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
670 674
671 675 # Determine how many lines at the bottom of the screen are needed for
672 676 # showing prompts, so we can know wheter long strings are to be printed or
673 677 # paged:
674 num_lines_bot = IP.rc.separate_in.count('\n')+1
675 IP.rc.screen_length = IP.rc.screen_length - num_lines_bot
678 num_lines_bot = IP_rc.separate_in.count('\n')+1
679 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
676 680 # Initialize cache, set in/out prompts and printing system
677 IP.outputcache = CachedOutput(IP.rc.cache_size,
678 IP.rc.pprint,
679 input_sep = IP.rc.separate_in,
680 output_sep = IP.rc.separate_out,
681 output_sep2 = IP.rc.separate_out2,
682 ps1 = IP.rc.prompt_in1,
683 ps2 = IP.rc.prompt_in2,
684 ps_out = IP.rc.prompt_out,
681 IP.outputcache = CachedOutput(IP_rc.cache_size,
682 IP_rc.pprint,
683 input_sep = IP_rc.separate_in,
684 output_sep = IP_rc.separate_out,
685 output_sep2 = IP_rc.separate_out2,
686 ps1 = IP_rc.prompt_in1,
687 ps2 = IP_rc.prompt_in2,
688 ps_out = IP_rc.prompt_out,
685 689 user_ns = IP.user_ns,
686 690 input_hist = IP.input_hist,
687 pad_left = IP.rc.prompts_pad_left)
688
689 # Set user colors (don't do it in the constructor above so that it doesn't
690 # crash if colors option is invalid)
691 IP.magic_colors(IP.rc.colors)
691 pad_left = IP_rc.prompts_pad_left)
692 692
693 693 # user may have over-ridden the default print hook:
694 694 try:
695 695 IP.outputcache.__class__.display = IP.hooks.display
696 696 except AttributeError:
697 697 pass
698 698
699 699 # Set calling of pdb on exceptions
700 IP.InteractiveTB.call_pdb = IP.rc.pdb
700 IP.InteractiveTB.call_pdb = IP_rc.pdb
701 701
702 702 # I don't like assigning globally to sys, because it means when embedding
703 703 # instances, each embedded instance overrides the previous choice. But
704 704 # sys.displayhook seems to be called internally by exec, so I don't see a
705 705 # way around it.
706 706 sys.displayhook = IP.outputcache
707 707
708 708 # we need to know globally if we're caching i/o or not
709 709 IP.do_full_cache = IP.outputcache.do_full_cache
710 710
711 711 # configure startup banner
712 if IP.rc.c: # regular python doesn't print the banner with -c
713 IP.rc.banner = 0
714 if IP.rc.banner:
715 IP.BANNER = '\n'.join(IP.BANNER_PARTS)
712 if IP_rc.c: # regular python doesn't print the banner with -c
713 IP_rc.banner = 0
714 if IP_rc.banner:
715 BANN_P = IP.BANNER_PARTS
716 716 else:
717 IP.BANNER = ''
717 BANN_P = []
718 718
719 if IP.rc.profile: IP.BANNER += '\nIPython profile: '+IP.rc.profile+'\n'
719 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
720 720
721 721 # add message log (possibly empty)
722 IP.BANNER += msg.summary
722 if msg.summary: BANN_P.append(msg.summary)
723 # Final banner is a string
724 IP.BANNER = '\n'.join(BANN_P)
725
726 # Assign the IP_rc object as an attribute of IP
727 IP.rc = IP_rc
723 728
729 # Finalize the IPython instance. This assumes the rc structure is fully
730 # in place.
724 731 IP.post_config_initialization()
725 732
726 733 return IP
727 734 #************************ end of file <ipmaker.py> **************************
@@ -1,156 +1,138 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Support for wildcard pattern matching in object inspection.
3 3
4 4 $Id: OInspect.py 608 2005-07-06 17:52:32Z fperez $
5 5 """
6 6
7 7 #*****************************************************************************
8 8 # Copyright (C) 2005 Jörgen Stenarson <jorgen.stenarson@bostream.nu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 from IPython import Release
15 15 __author__ = "Jörgen Stenarson <jorgen.stenarson@bostream.nu>"
16 16 __license__ = Release.license
17 17
18 18 import __builtin__
19 19 import types
20 20 import re
21 21 import pprint
22 22 import exceptions
23 23 import pdb
24 import IPython.genutils as genutils
25 24
26 25 def create_typestr2type_dicts(dont_include_in_type2type2str=["lambda"]):
27 26 """Return dictionaries mapping lower case typename to type objects, from
28 27 the types package, and vice versa."""
29 28 typenamelist=[]
30 29 for tname in dir(types):
31 30 if tname[-4:]=="Type":
32 31 typenamelist.append(tname)
33 32 typestr2type={}
34 33 type2typestr={}
35 34 for tname in typenamelist:
36 35 name=tname[:-4].lower()
37 36 obj=getattr(types,tname)
38 37 typestr2type[name]=getattr(types,tname)
39 38 if name in dont_include_in_type2type2str:
40 39 type2typestr[obj]=name
41 40 return typestr2type,type2typestr
42 41
43 42 typestr2type,type2typestr=create_typestr2type_dicts()
44 43
45 44 def is_type(obj,typestr_or_type):
46 45 """is_type(obj,typestr_or_type) verifies if obj is of a certain type or
47 46 group of types takes strings as parameters of the for 'tuple'<->TupleType
48 47 'all' matches all types. TODO: Should be extended for choosing more than
49 48 one type
50 49 """
51 50 if typestr_or_type=="all":
52 51 return True
53 52 if type(typestr_or_type)==types.TypeType:
54 53 test_type=typestr_or_type
55 54 else:
56 55 test_type=typestr2type.get(typestr_or_type,False)
57 56 if test_type:
58 57 return isinstance(obj,test_type)
59 58 else:
60 59 return False
61 60
62 def show_hidden(str,showhidden=False):
63 """Return true for strings starting with single _ if showhidden is true."""
64 return showhidden or str.startswith("__") or not str.startswith("_")
61 def show_hidden(str,show_all=False):
62 """Return true for strings starting with single _ if show_all is true."""
63 return show_all or str.startswith("__") or not str.startswith("_")
65 64
66 65
67 66 class NameSpace(object):
68 67 """NameSpace holds the dictionary for a namespace and implements filtering
69 68 on name and types"""
70 def __init__(self,obj,namepattern="*",typepattern="all",ignorecase=True,
71 showhidden=True):
72 self.showhidden = showhidden #Hide names beginning with single _
69 def __init__(self,obj,name_pattern="*",type_pattern="all",ignore_case=True,
70 show_all=True):
71 self.show_all = show_all #Hide names beginning with single _
73 72 self.object = obj
74 self.namepattern = namepattern
75 self.typepattern = typepattern
76 self.ignorecase = ignorecase
73 self.name_pattern = name_pattern
74 self.type_pattern = type_pattern
75 self.ignore_case = ignore_case
77 76
78 77 # We should only match EXACT dicts here, so DON'T use isinstance()
79 78 if type(obj) == types.DictType:
80 79 self._ns = obj
81 80 else:
82 81 self._ns = dict([(key,getattr(obj,key)) for key in dir(obj)
83 82 if isinstance(key, basestring)])
84 83
85 84 def get_ns(self):
86 85 """Return name space dictionary with objects matching type and name patterns."""
87 return self.filter(self.namepattern,self.typepattern)
86 return self.filter(self.name_pattern,self.type_pattern)
88 87 ns=property(get_ns)
89 88
90 89 def get_ns_names(self):
91 90 """Return list of object names in namespace that match the patterns."""
92 91 return self.ns.keys()
93 92 ns_names=property(get_ns_names,doc="List of objects in name space that "
94 93 "match the type and name patterns.")
95 94
96 def filter(self,namepattern,typepattern):
95 def filter(self,name_pattern,type_pattern):
97 96 """Return dictionary of filtered namespace."""
98 def glob_filter(lista,namepattern,hidehidden,ignorecase):
97 def glob_filter(lista,name_pattern,hidehidden,ignore_case):
99 98 """Return list of elements in lista that match pattern."""
100 pattern=namepattern.replace("*",".*")
101 if ignorecase:
99 pattern=name_pattern.replace("*",".*")
100 if ignore_case:
102 101 reg=re.compile(pattern+"$",re.I)
103 102 else:
104 103 reg=re.compile(pattern+"$")
105 104 result=[x for x in lista if reg.match(x) and show_hidden(x,hidehidden)]
106 105 return result
107 106 ns=self._ns
108 #Filter namespace by the namepattern
109 all=[(x,ns[x]) for x in glob_filter(ns.keys(),namepattern,
110 self.showhidden,self.ignorecase)]
111 #Filter namespace by typepattern
112 all=[(key,obj) for key,obj in all if is_type(obj,typepattern)]
107 #Filter namespace by the name_pattern
108 all=[(x,ns[x]) for x in glob_filter(ns.keys(),name_pattern,
109 self.show_all,self.ignore_case)]
110 #Filter namespace by type_pattern
111 all=[(key,obj) for key,obj in all if is_type(obj,type_pattern)]
113 112 all=dict(all)
114 113 return all
115 114
116 115 #TODO: Implement dictionary like access to filtered name space?
117 116
118 def list_namespace(namespace,typepattern,filter,ignorecase=False,showhidden=False):
119 """Return dictionary of all objects in namespace that matches typepattern
117 def list_namespace(namespace,type_pattern,filter,ignore_case=False,show_all=False):
118 """Return dictionary of all objects in namespace that matches type_pattern
120 119 and filter."""
121 patternlist=filter.split(".")
122 if len(patternlist)==1:
123 ns=NameSpace(namespace,namepattern=patternlist[0],typepattern=typepattern,
124 ignorecase=ignorecase,showhidden=showhidden)
120 pattern_list=filter.split(".")
121 if len(pattern_list)==1:
122 ns=NameSpace(namespace,name_pattern=pattern_list[0],type_pattern=type_pattern,
123 ignore_case=ignore_case,show_all=show_all)
125 124 return ns.ns
126 if len(patternlist)>1:
127 #This is where we can change if all objects should be searched or only moduleas
128 #Just change the typepattern to module to search only modules
129 ns=NameSpace(namespace,
130 namepattern=patternlist[0],
131 typepattern="all",ignorecase=ignorecase,showhidden=showhidden)
125 else:
126 # This is where we can change if all objects should be searched or
127 # only modules. Just change the type_pattern to module to search only
128 # modules
129 ns=NameSpace(namespace,name_pattern=pattern_list[0],type_pattern="all",
130 ignore_case=ignore_case,show_all=show_all)
132 131 res={}
133 132 nsdict=ns.ns
134 133 for name,obj in nsdict.iteritems():
135 ns=list_namespace(obj,typepattern,".".join(patternlist[1:]),
136 ignorecase=ignorecase,showhidden=showhidden)
134 ns=list_namespace(obj,type_pattern,".".join(pattern_list[1:]),
135 ignore_case=ignore_case,show_all=show_all)
137 136 for inner_name,inner_obj in ns.iteritems():
138 137 res["%s.%s"%(name,inner_name)]=inner_obj
139 138 return res
140
141 def choose_namespaces(shell,cmds):
142 """Returns a list of namespaces modified by arguments."""
143 nslist=genutils.mkdict(user=shell.user_ns,internal=shell.internal_ns,
144 builtin=__builtin__.__dict__,alias=shell.alias_table)
145 default_list=["user","builtin"] # Should this list be a user option??
146 for cmd in cmds:
147 if cmd[0]=="-": #remove from defaultlist
148 if cmd[1:] in default_list:
149 default_list.remove(cmd[1:])
150 elif cmd[0]=="+":
151 if cmd[1:] not in default_list and cmd[1:]in nslist:
152 default_list.append(cmd[1:])
153 else:
154 if cmd in nslist:
155 default_list.append(cmd[1:])
156 return [nslist[x] for x in default_list]
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now