##// END OF EJS Templates
Fernando Perez -
Show More
@@ -0,0 +1,34 b''
1 """Test code for https://bugs.launchpad.net/ipython/+bug/239054
2
3 WARNING: this script exits IPython! It MUST be run in a subprocess.
4
5 When you run the following script from CPython it prints:
6 __init__ is here
7 __del__ is here
8
9 and creates the __del__.txt file
10
11 When you run it from IPython it prints:
12 __init__ is here
13
14 When you exit() or Exit from IPython neothing is printed and no file is created
15 (the file thing is to make sure __del__ is really never called and not that
16 just the output is eaten).
17
18 Note that if you call %reset in IPython then everything is Ok.
19
20 IPython should do the equivalent of %reset and release all the references it
21 holds before exit. This behavior is important when working with binding objects
22 that rely on __del__. If the current behavior has some use case then I suggest
23 to add a configuration option to IPython to control it.
24 """
25 import sys
26
27 class A(object):
28 def __del__(self):
29 print 'object A deleted'
30
31 a = A()
32
33 # Now, we force an exit, the caller will check that the del printout was given
34 _ip.IP.ask_exit()
@@ -0,0 +1,16 b''
1 """Tests for the key iplib module, where the main ipython class is defined.
2 """
3
4 import nose.tools as nt
5
6 def test_reset():
7 """reset must clear most namespaces."""
8 ip = _ip.IP
9 ip.reset() # first, it should run without error
10 # Then, check that most namespaces end up empty
11 for ns in ip.ns_refs_table:
12 if ns is ip.user_ns:
13 # The user namespace is reset with some data, so we can't check for
14 # it being empty
15 continue
16 nt.assert_equals(len(ns),0)
@@ -1,686 +1,685 b''
1 1 """IPython customization API
2 2
3 3 Your one-stop module for configuring & extending ipython
4 4
5 5 The API will probably break when ipython 1.0 is released, but so
6 6 will the other configuration method (rc files).
7 7
8 8 All names prefixed by underscores are for internal use, not part
9 9 of the public api.
10 10
11 11 Below is an example that you can just put to a module and import from ipython.
12 12
13 13 A good practice is to install the config script below as e.g.
14 14
15 15 ~/.ipython/my_private_conf.py
16 16
17 17 And do
18 18
19 19 import_mod my_private_conf
20 20
21 21 in ~/.ipython/ipythonrc
22 22
23 23 That way the module is imported at startup and you can have all your
24 24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 25 stuff) in there.
26 26
27 27 import IPython.ipapi
28 28 ip = IPython.ipapi.get()
29 29
30 30 def ankka_f(self, arg):
31 31 print 'Ankka',self,'says uppercase:',arg.upper()
32 32
33 33 ip.expose_magic('ankka',ankka_f)
34 34
35 35 ip.magic('alias sayhi echo "Testing, hi ok"')
36 36 ip.magic('alias helloworld echo "Hello world"')
37 37 ip.system('pwd')
38 38
39 39 ip.ex('import re')
40 40 ip.ex('''
41 41 def funcci(a,b):
42 42 print a+b
43 43 print funcci(3,4)
44 44 ''')
45 45 ip.ex('funcci(348,9)')
46 46
47 47 def jed_editor(self,filename, linenum=None):
48 48 print 'Calling my own editor, jed ... via hook!'
49 49 import os
50 50 if linenum is None: linenum = 0
51 51 os.system('jed +%d %s' % (linenum, filename))
52 52 print 'exiting jed'
53 53
54 54 ip.set_hook('editor',jed_editor)
55 55
56 56 o = ip.options
57 57 o.autocall = 2 # FULL autocall mode
58 58
59 59 print 'done!'
60 60 """
61 61
62 62 #-----------------------------------------------------------------------------
63 63 # Modules and globals
64 64
65 65 # stdlib imports
66 66 import __builtin__
67 67 import sys
68 68
69 69 # contains the most recently instantiated IPApi
70 70 _RECENT_IP = None
71 71
72 72 #-----------------------------------------------------------------------------
73 73 # Code begins
74 74
75 75 class TryNext(Exception):
76 76 """Try next hook exception.
77 77
78 78 Raise this in your hook function to indicate that the next hook handler
79 79 should be used to handle the operation. If you pass arguments to the
80 80 constructor those arguments will be used by the next hook instead of the
81 81 original ones.
82 82 """
83 83
84 84 def __init__(self, *args, **kwargs):
85 85 self.args = args
86 86 self.kwargs = kwargs
87 87
88 88
89 89 class UsageError(Exception):
90 90 """ Error in magic function arguments, etc.
91 91
92 92 Something that probably won't warrant a full traceback, but should
93 93 nevertheless interrupt a macro / batch file.
94 94 """
95 95
96 96
97 97 class IPyAutocall:
98 98 """ Instances of this class are always autocalled
99 99
100 100 This happens regardless of 'autocall' variable state. Use this to
101 101 develop macro-like mechanisms.
102 102 """
103 103
104 104 def set_ip(self,ip):
105 105 """ Will be used to set _ip point to current ipython instance b/f call
106 106
107 107 Override this method if you don't want this to happen.
108 108
109 109 """
110 110 self._ip = ip
111 111
112 112
113 113 class IPythonNotRunning:
114 114 """Dummy do-nothing class.
115 115
116 116 Instances of this class return a dummy attribute on all accesses, which
117 117 can be called and warns. This makes it easier to write scripts which use
118 118 the ipapi.get() object for informational purposes to operate both with and
119 119 without ipython. Obviously code which uses the ipython object for
120 120 computations will not work, but this allows a wider range of code to
121 121 transparently work whether ipython is being used or not."""
122 122
123 123 def __init__(self,warn=True):
124 124 if warn:
125 125 self.dummy = self._dummy_warn
126 126 else:
127 127 self.dummy = self._dummy_silent
128 128
129 129 def __str__(self):
130 130 return "<IPythonNotRunning>"
131 131
132 132 __repr__ = __str__
133 133
134 134 def __getattr__(self,name):
135 135 return self.dummy
136 136
137 137 def _dummy_warn(self,*args,**kw):
138 138 """Dummy function, which doesn't do anything but warn."""
139 139
140 140 print ("IPython is not running, this is a dummy no-op function")
141 141
142 142 def _dummy_silent(self,*args,**kw):
143 143 """Dummy function, which doesn't do anything and emits no warnings."""
144 144 pass
145 145
146 146
147 147 def get(allow_dummy=False,dummy_warn=True):
148 148 """Get an IPApi object.
149 149
150 150 If allow_dummy is true, returns an instance of IPythonNotRunning
151 151 instead of None if not running under IPython.
152 152
153 153 If dummy_warn is false, the dummy instance will be completely silent.
154 154
155 155 Running this should be the first thing you do when writing extensions that
156 156 can be imported as normal modules. You can then direct all the
157 157 configuration operations against the returned object.
158 158 """
159 159 global _RECENT_IP
160 160 if allow_dummy and not _RECENT_IP:
161 161 _RECENT_IP = IPythonNotRunning(dummy_warn)
162 162 return _RECENT_IP
163 163
164 164
165 165 class IPApi(object):
166 166 """ The actual API class for configuring IPython
167 167
168 168 You should do all of the IPython configuration by getting an IPApi object
169 169 with IPython.ipapi.get() and using the attributes and methods of the
170 170 returned object."""
171 171
172 172 def __init__(self,ip):
173 173
174 174 global _RECENT_IP
175 175
176 176 # All attributes exposed here are considered to be the public API of
177 177 # IPython. As needs dictate, some of these may be wrapped as
178 178 # properties.
179 179
180 180 self.magic = ip.ipmagic
181 181
182 182 self.system = ip.system
183 183
184 184 self.set_hook = ip.set_hook
185 185
186 186 self.set_custom_exc = ip.set_custom_exc
187 187
188 188 self.user_ns = ip.user_ns
189 self.user_ns['_ip'] = self
190 189
191 190 self.set_crash_handler = ip.set_crash_handler
192 191
193 192 # Session-specific data store, which can be used to store
194 193 # data that should persist through the ipython session.
195 194 self.meta = ip.meta
196 195
197 196 # The ipython instance provided
198 197 self.IP = ip
199 198
200 199 self.extensions = {}
201 200
202 201 self.dbg = DebugTools(self)
203 202
204 203 _RECENT_IP = self
205 204
206 205 # Use a property for some things which are added to the instance very
207 206 # late. I don't have time right now to disentangle the initialization
208 207 # order issues, so a property lets us delay item extraction while
209 208 # providing a normal attribute API.
210 209 def get_db(self):
211 210 """A handle to persistent dict-like database (a PickleShareDB object)"""
212 211 return self.IP.db
213 212
214 213 db = property(get_db,None,None,get_db.__doc__)
215 214
216 215 def get_options(self):
217 216 """All configurable variables."""
218 217
219 218 # catch typos by disabling new attribute creation. If new attr creation
220 219 # is in fact wanted (e.g. when exposing new options), do
221 220 # allow_new_attr(True) for the received rc struct.
222 221
223 222 self.IP.rc.allow_new_attr(False)
224 223 return self.IP.rc
225 224
226 225 options = property(get_options,None,None,get_options.__doc__)
227 226
228 227 def expose_magic(self,magicname, func):
229 228 """Expose own function as magic function for ipython
230 229
231 230 def foo_impl(self,parameter_s=''):
232 231 'My very own magic!. (Use docstrings, IPython reads them).'
233 232 print 'Magic function. Passed parameter is between < >:'
234 233 print '<%s>' % parameter_s
235 234 print 'The self object is:',self
236 235
237 236 ipapi.expose_magic('foo',foo_impl)
238 237 """
239 238
240 239 import new
241 240 im = new.instancemethod(func,self.IP, self.IP.__class__)
242 241 old = getattr(self.IP, "magic_" + magicname, None)
243 242 if old:
244 243 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
245 244 (magicname,old) )
246 245
247 246 setattr(self.IP, "magic_" + magicname, im)
248 247
249 248 def ex(self,cmd):
250 249 """ Execute a normal python statement in user namespace """
251 250 exec cmd in self.user_ns
252 251
253 252 def ev(self,expr):
254 253 """ Evaluate python expression expr in user namespace
255 254
256 255 Returns the result of evaluation"""
257 256 return eval(expr,self.user_ns)
258 257
259 258 def runlines(self,lines):
260 259 """ Run the specified lines in interpreter, honoring ipython directives.
261 260
262 261 This allows %magic and !shell escape notations.
263 262
264 263 Takes either all lines in one string or list of lines.
265 264 """
266 265
267 266 def cleanup_ipy_script(script):
268 267 """ Make a script safe for _ip.runlines()
269 268
270 269 - Removes empty lines Suffixes all indented blocks that end with
271 270 - unindented lines with empty lines
272 271 """
273 272
274 273 res = []
275 274 lines = script.splitlines()
276 275
277 276 level = 0
278 277 for l in lines:
279 278 lstripped = l.lstrip()
280 279 stripped = l.strip()
281 280 if not stripped:
282 281 continue
283 282 newlevel = len(l) - len(lstripped)
284 283 def is_secondary_block_start(s):
285 284 if not s.endswith(':'):
286 285 return False
287 286 if (s.startswith('elif') or
288 287 s.startswith('else') or
289 288 s.startswith('except') or
290 289 s.startswith('finally')):
291 290 return True
292 291
293 292 if level > 0 and newlevel == 0 and \
294 293 not is_secondary_block_start(stripped):
295 294 # add empty line
296 295 res.append('')
297 296
298 297 res.append(l)
299 298 level = newlevel
300 299 return '\n'.join(res) + '\n'
301 300
302 301 if isinstance(lines,basestring):
303 302 script = lines
304 303 else:
305 304 script = '\n'.join(lines)
306 305 clean=cleanup_ipy_script(script)
307 306 # print "_ip.runlines() script:\n",clean # dbg
308 307 self.IP.runlines(clean)
309 308
310 309 def to_user_ns(self,vars, interactive = True):
311 310 """Inject a group of variables into the IPython user namespace.
312 311
313 312 Inputs:
314 313
315 314 - vars: string with variable names separated by whitespace, or a
316 315 dict with name/value pairs.
317 316
318 317 - interactive: if True (default), the var will be listed with
319 318 %whos et. al.
320 319
321 320 This utility routine is meant to ease interactive debugging work,
322 321 where you want to easily propagate some internal variable in your code
323 322 up to the interactive namespace for further exploration.
324 323
325 324 When you run code via %run, globals in your script become visible at
326 325 the interactive prompt, but this doesn't happen for locals inside your
327 326 own functions and methods. Yet when debugging, it is common to want
328 327 to explore some internal variables further at the interactive propmt.
329 328
330 329 Examples:
331 330
332 331 To use this, you first must obtain a handle on the ipython object as
333 332 indicated above, via:
334 333
335 334 import IPython.ipapi
336 335 ip = IPython.ipapi.get()
337 336
338 337 Once this is done, inside a routine foo() where you want to expose
339 338 variables x and y, you do the following:
340 339
341 340 def foo():
342 341 ...
343 342 x = your_computation()
344 343 y = something_else()
345 344
346 345 # This pushes x and y to the interactive prompt immediately, even
347 346 # if this routine crashes on the next line after:
348 347 ip.to_user_ns('x y')
349 348 ...
350 349
351 350 # To expose *ALL* the local variables from the function, use:
352 351 ip.to_user_ns(locals())
353 352
354 353 ...
355 354 # return
356 355
357 356
358 357 If you need to rename variables, the dict input makes it easy. For
359 358 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
360 359 in IPython user namespace:
361 360
362 361 ip.to_user_ns(dict(x=foo,y=bar))
363 362 """
364 363
365 364 # print 'vars given:',vars # dbg
366 365
367 366 # We need a dict of name/value pairs to do namespace updates.
368 367 if isinstance(vars,dict):
369 368 # If a dict was given, no need to change anything.
370 369 vdict = vars
371 370 elif isinstance(vars,basestring):
372 371 # If a string with names was given, get the caller's frame to
373 372 # evaluate the given names in
374 373 cf = sys._getframe(1)
375 374 vdict = {}
376 375 for name in vars.split():
377 376 try:
378 377 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
379 378 except:
380 379 print ('could not get var. %s from %s' %
381 380 (name,cf.f_code.co_name))
382 381 else:
383 382 raise ValueError('vars must be a string or a dict')
384 383
385 384 # Propagate variables to user namespace
386 385 self.user_ns.update(vdict)
387 386
388 387 # And configure interactive visibility
389 388 config_ns = self.IP.user_config_ns
390 389 if interactive:
391 390 for name,val in vdict.iteritems():
392 391 config_ns.pop(name,None)
393 392 else:
394 393 for name,val in vdict.iteritems():
395 394 config_ns[name] = val
396 395
397 396 def expand_alias(self,line):
398 397 """ Expand an alias in the command line
399 398
400 399 Returns the provided command line, possibly with the first word
401 400 (command) translated according to alias expansion rules.
402 401
403 402 [ipython]|16> _ip.expand_aliases("np myfile.txt")
404 403 <16> 'q:/opt/np/notepad++.exe myfile.txt'
405 404 """
406 405
407 406 pre,fn,rest = self.IP.split_user_input(line)
408 407 res = pre + self.IP.expand_aliases(fn,rest)
409 408 return res
410 409
411 410 def itpl(self, s, depth = 1):
412 411 """ Expand Itpl format string s.
413 412
414 413 Only callable from command line (i.e. prefilter results);
415 414 If you use in your scripts, you need to use a bigger depth!
416 415 """
417 416 return self.IP.var_expand(s, depth)
418 417
419 418 def defalias(self, name, cmd):
420 419 """ Define a new alias
421 420
422 421 _ip.defalias('bb','bldmake bldfiles')
423 422
424 423 Creates a new alias named 'bb' in ipython user namespace
425 424 """
426 425
427 426 self.dbg.check_hotname(name)
428 427
429 428 if name in self.IP.alias_table:
430 429 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
431 430 % (name, cmd, self.IP.alias_table[name]))
432 431
433 432 if callable(cmd):
434 433 self.IP.alias_table[name] = cmd
435 434 import IPython.shadowns
436 435 setattr(IPython.shadowns, name,cmd)
437 436 return
438 437
439 438 if isinstance(cmd,basestring):
440 439 nargs = cmd.count('%s')
441 440 if nargs>0 and cmd.find('%l')>=0:
442 441 raise Exception('The %s and %l specifiers are mutually '
443 442 'exclusive in alias definitions.')
444 443
445 444 self.IP.alias_table[name] = (nargs,cmd)
446 445 return
447 446
448 447 # just put it in - it's probably (0,'foo')
449 448 self.IP.alias_table[name] = cmd
450 449
451 450 def defmacro(self, *args):
452 451 """ Define a new macro
453 452
454 453 2 forms of calling:
455 454
456 455 mac = _ip.defmacro('print "hello"\nprint "world"')
457 456
458 457 (doesn't put the created macro on user namespace)
459 458
460 459 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
461 460
462 461 (creates a macro named 'build' in user namespace)
463 462 """
464 463
465 464 import IPython.macro
466 465
467 466 if len(args) == 1:
468 467 return IPython.macro.Macro(args[0])
469 468 elif len(args) == 2:
470 469 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
471 470 else:
472 471 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
473 472
474 473 def set_next_input(self, s):
475 474 """ Sets the 'default' input string for the next command line.
476 475
477 476 Requires readline.
478 477
479 478 Example:
480 479
481 480 [D:\ipython]|1> _ip.set_next_input("Hello Word")
482 481 [D:\ipython]|2> Hello Word_ # cursor is here
483 482 """
484 483
485 484 self.IP.rl_next_input = s
486 485
487 486 def load(self, mod):
488 487 """ Load an extension.
489 488
490 489 Some modules should (or must) be 'load()':ed, rather than just imported.
491 490
492 491 Loading will do:
493 492
494 493 - run init_ipython(ip)
495 494 - run ipython_firstrun(ip)
496 495 """
497 496
498 497 if mod in self.extensions:
499 498 # just to make sure we don't init it twice
500 499 # note that if you 'load' a module that has already been
501 500 # imported, init_ipython gets run anyway
502 501
503 502 return self.extensions[mod]
504 503 __import__(mod)
505 504 m = sys.modules[mod]
506 505 if hasattr(m,'init_ipython'):
507 506 m.init_ipython(self)
508 507
509 508 if hasattr(m,'ipython_firstrun'):
510 509 already_loaded = self.db.get('firstrun_done', set())
511 510 if mod not in already_loaded:
512 511 m.ipython_firstrun(self)
513 512 already_loaded.add(mod)
514 513 self.db['firstrun_done'] = already_loaded
515 514
516 515 self.extensions[mod] = m
517 516 return m
518 517
519 518
520 519 class DebugTools:
521 520 """ Used for debugging mishaps in api usage
522 521
523 522 So far, tracing redefinitions is supported.
524 523 """
525 524
526 525 def __init__(self, ip):
527 526 self.ip = ip
528 527 self.debugmode = False
529 528 self.hotnames = set()
530 529
531 530 def hotname(self, name_to_catch):
532 531 self.hotnames.add(name_to_catch)
533 532
534 533 def debug_stack(self, msg = None):
535 534 if not self.debugmode:
536 535 return
537 536
538 537 import traceback
539 538 if msg is not None:
540 539 print '====== %s ========' % msg
541 540 traceback.print_stack()
542 541
543 542 def check_hotname(self,name):
544 543 if name in self.hotnames:
545 544 self.debug_stack( "HotName '%s' caught" % name)
546 545
547 546
548 547 def launch_new_instance(user_ns = None,shellclass = None):
549 548 """ Make and start a new ipython instance.
550 549
551 550 This can be called even without having an already initialized
552 551 ipython session running.
553 552
554 553 This is also used as the egg entry point for the 'ipython' script.
555 554
556 555 """
557 556 ses = make_session(user_ns,shellclass)
558 557 ses.mainloop()
559 558
560 559
561 560 def make_user_ns(user_ns = None):
562 561 """Return a valid user interactive namespace.
563 562
564 563 This builds a dict with the minimal information needed to operate as a
565 564 valid IPython user namespace, which you can pass to the various embedding
566 565 classes in ipython.
567 566
568 567 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
569 568 to make both the local and global namespace objects simultaneously.
570 569
571 570 :Parameters:
572 571 user_ns : dict-like, optional
573 572 The current user namespace. The items in this namespace should be
574 573 included in the output. If None, an appropriate blank namespace
575 574 should be created.
576 575
577 576 :Returns:
578 577 A dictionary-like object to be used as the local namespace of the
579 578 interpreter.
580 579 """
581 580
582 581 raise NotImplementedError
583 582
584 583
585 584 def make_user_global_ns(ns = None):
586 585 """Return a valid user global namespace.
587 586
588 587 Similar to make_user_ns(), but global namespaces are really only needed in
589 588 embedded applications, where there is a distinction between the user's
590 589 interactive namespace and the global one where ipython is running.
591 590
592 591 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
593 592 to make both the local and global namespace objects simultaneously.
594 593
595 594 :Parameters:
596 595 ns : dict, optional
597 596 The current user global namespace. The items in this namespace
598 597 should be included in the output. If None, an appropriate blank
599 598 namespace should be created.
600 599
601 600 :Returns:
602 601 A true dict to be used as the global namespace of the interpreter.
603 602 """
604 603
605 604 raise NotImplementedError
606 605
607 606 # Record the true objects in order to be able to test if the user has overridden
608 607 # these API functions.
609 608 _make_user_ns = make_user_ns
610 609 _make_user_global_ns = make_user_global_ns
611 610
612 611
613 612 def make_user_namespaces(user_ns = None,user_global_ns = None):
614 613 """Return a valid local and global user interactive namespaces.
615 614
616 615 This builds a dict with the minimal information needed to operate as a
617 616 valid IPython user namespace, which you can pass to the various embedding
618 617 classes in ipython. The default implementation returns the same dict for
619 618 both the locals and the globals to allow functions to refer to variables in
620 619 the namespace. Customized implementations can return different dicts. The
621 620 locals dictionary can actually be anything following the basic mapping
622 621 protocol of a dict, but the globals dict must be a true dict, not even
623 622 a subclass. It is recommended that any custom object for the locals
624 623 namespace synchronize with the globals dict somehow.
625 624
626 625 Raises TypeError if the provided globals namespace is not a true dict.
627 626
628 627 :Parameters:
629 628 user_ns : dict-like, optional
630 629 The current user namespace. The items in this namespace should be
631 630 included in the output. If None, an appropriate blank namespace
632 631 should be created.
633 632 user_global_ns : dict, optional
634 633 The current user global namespace. The items in this namespace
635 634 should be included in the output. If None, an appropriate blank
636 635 namespace should be created.
637 636
638 637 :Returns:
639 638 A tuple pair of dictionary-like object to be used as the local namespace
640 639 of the interpreter and a dict to be used as the global namespace.
641 640 """
642 641
643 642 if user_ns is None:
644 643 if make_user_ns is not _make_user_ns:
645 644 # Old API overridden.
646 645 # FIXME: Issue DeprecationWarning, or just let the old API live on?
647 646 user_ns = make_user_ns(user_ns)
648 647 else:
649 648 # Set __name__ to __main__ to better match the behavior of the
650 649 # normal interpreter.
651 650 user_ns = {'__name__' :'__main__',
652 651 '__builtins__' : __builtin__,
653 652 }
654 653 else:
655 654 user_ns.setdefault('__name__','__main__')
656 655 user_ns.setdefault('__builtins__',__builtin__)
657 656
658 657 if user_global_ns is None:
659 658 if make_user_global_ns is not _make_user_global_ns:
660 659 # Old API overridden.
661 660 user_global_ns = make_user_global_ns(user_global_ns)
662 661 else:
663 662 user_global_ns = user_ns
664 663 if type(user_global_ns) is not dict:
665 664 raise TypeError("user_global_ns must be a true dict; got %r"
666 665 % type(user_global_ns))
667 666
668 667 return user_ns, user_global_ns
669 668
670 669
671 670 def make_session(user_ns = None, shellclass = None):
672 671 """Makes, but does not launch an IPython session.
673 672
674 673 Later on you can call obj.mainloop() on the returned object.
675 674
676 675 Inputs:
677 676
678 677 - user_ns(None): a dict to be used as the user's namespace with initial
679 678 data.
680 679
681 680 WARNING: This should *not* be run when a session exists already."""
682 681
683 682 import IPython.Shell
684 683 if shellclass is None:
685 684 return IPython.Shell.start(user_ns)
686 685 return shellclass(user_ns = user_ns)
@@ -1,2729 +1,2783 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.4 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8 """
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #
17 17 # Note: this code originally subclassed code.InteractiveConsole from the
18 18 # Python standard library. Over time, all of that class has been copied
19 19 # verbatim here for modifications which could not be accomplished by
20 20 # subclassing. At this point, there are no dependencies at all on the code
21 21 # module anymore (it is not even imported). The Python License (sec. 2)
22 22 # allows for this, but it's always nice to acknowledge credit where credit is
23 23 # due.
24 24 #*****************************************************************************
25 25
26 26 #****************************************************************************
27 27 # Modules and globals
28 28
29 29 # Python standard modules
30 30 import __main__
31 31 import __builtin__
32 32 import StringIO
33 33 import bdb
34 34 import cPickle as pickle
35 35 import codeop
36 36 import exceptions
37 37 import glob
38 38 import inspect
39 39 import keyword
40 40 import new
41 41 import os
42 42 import pydoc
43 43 import re
44 44 import shutil
45 45 import string
46 46 import sys
47 47 import tempfile
48 48 import traceback
49 49 import types
50 50 import warnings
51 51 warnings.filterwarnings('ignore', r'.*sets module*')
52 52 from sets import Set
53 53 from pprint import pprint, pformat
54 54
55 55 # IPython's own modules
56 56 #import IPython
57 57 from IPython import Debugger,OInspect,PyColorize,ultraTB
58 58 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
59 59 from IPython.Extensions import pickleshare
60 60 from IPython.FakeModule import FakeModule
61 61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 62 from IPython.Logger import Logger
63 63 from IPython.Magic import Magic
64 64 from IPython.Prompts import CachedOutput
65 65 from IPython.ipstruct import Struct
66 66 from IPython.background_jobs import BackgroundJobManager
67 67 from IPython.usage import cmd_line_usage,interactive_usage
68 68 from IPython.genutils import *
69 69 from IPython.strdispatch import StrDispatch
70 70 import IPython.ipapi
71 71 import IPython.history
72 72 import IPython.prefilter as prefilter
73 73 import IPython.shadowns
74 74 # Globals
75 75
76 76 # store the builtin raw_input globally, and use this always, in case user code
77 77 # overwrites it (like wx.py.PyShell does)
78 78 raw_input_original = raw_input
79 79
80 80 # compiled regexps for autoindent management
81 81 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
82 82
83 83
84 84 #****************************************************************************
85 85 # Some utility function definitions
86 86
87 87 ini_spaces_re = re.compile(r'^(\s+)')
88 88
89 89 def num_ini_spaces(strng):
90 90 """Return the number of initial spaces in a string"""
91 91
92 92 ini_spaces = ini_spaces_re.match(strng)
93 93 if ini_spaces:
94 94 return ini_spaces.end()
95 95 else:
96 96 return 0
97 97
98 98 def softspace(file, newvalue):
99 99 """Copied from code.py, to remove the dependency"""
100 100
101 101 oldvalue = 0
102 102 try:
103 103 oldvalue = file.softspace
104 104 except AttributeError:
105 105 pass
106 106 try:
107 107 file.softspace = newvalue
108 108 except (AttributeError, TypeError):
109 109 # "attribute-less object" or "read-only attributes"
110 110 pass
111 111 return oldvalue
112 112
113 113
114 114 #****************************************************************************
115 115 # Local use exceptions
116 116 class SpaceInInput(exceptions.Exception): pass
117 117
118 118
119 119 #****************************************************************************
120 120 # Local use classes
121 121 class Bunch: pass
122 122
123 123 class Undefined: pass
124 124
125 125 class Quitter(object):
126 126 """Simple class to handle exit, similar to Python 2.5's.
127 127
128 128 It handles exiting in an ipython-safe manner, which the one in Python 2.5
129 129 doesn't do (obviously, since it doesn't know about ipython)."""
130 130
131 131 def __init__(self,shell,name):
132 132 self.shell = shell
133 133 self.name = name
134 134
135 135 def __repr__(self):
136 136 return 'Type %s() to exit.' % self.name
137 137 __str__ = __repr__
138 138
139 139 def __call__(self):
140 140 self.shell.exit()
141 141
142 142 class InputList(list):
143 143 """Class to store user input.
144 144
145 145 It's basically a list, but slices return a string instead of a list, thus
146 146 allowing things like (assuming 'In' is an instance):
147 147
148 148 exec In[4:7]
149 149
150 150 or
151 151
152 152 exec In[5:9] + In[14] + In[21:25]"""
153 153
154 154 def __getslice__(self,i,j):
155 155 return ''.join(list.__getslice__(self,i,j))
156 156
157 157 class SyntaxTB(ultraTB.ListTB):
158 158 """Extension which holds some state: the last exception value"""
159 159
160 160 def __init__(self,color_scheme = 'NoColor'):
161 161 ultraTB.ListTB.__init__(self,color_scheme)
162 162 self.last_syntax_error = None
163 163
164 164 def __call__(self, etype, value, elist):
165 165 self.last_syntax_error = value
166 166 ultraTB.ListTB.__call__(self,etype,value,elist)
167 167
168 168 def clear_err_state(self):
169 169 """Return the current error state and clear it"""
170 170 e = self.last_syntax_error
171 171 self.last_syntax_error = None
172 172 return e
173 173
174 174 #****************************************************************************
175 175 # Main IPython class
176 176
177 177 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
178 178 # until a full rewrite is made. I've cleaned all cross-class uses of
179 179 # attributes and methods, but too much user code out there relies on the
180 180 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
181 181 #
182 182 # But at least now, all the pieces have been separated and we could, in
183 183 # principle, stop using the mixin. This will ease the transition to the
184 184 # chainsaw branch.
185 185
186 186 # For reference, the following is the list of 'self.foo' uses in the Magic
187 187 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
188 188 # class, to prevent clashes.
189 189
190 190 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
191 191 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
192 192 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
193 193 # 'self.value']
194 194
195 195 class InteractiveShell(object,Magic):
196 196 """An enhanced console for Python."""
197 197
198 198 # class attribute to indicate whether the class supports threads or not.
199 199 # Subclasses with thread support should override this as needed.
200 200 isthreaded = False
201 201
202 202 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
203 203 user_ns=None,user_global_ns=None,banner2='',
204 204 custom_exceptions=((),None),embedded=False):
205 205
206 206 # log system
207 207 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
208 208
209 209 # Job manager (for jobs run as background threads)
210 210 self.jobs = BackgroundJobManager()
211 211
212 212 # Store the actual shell's name
213 213 self.name = name
214 214 self.more = False
215 215
216 216 # We need to know whether the instance is meant for embedding, since
217 217 # global/local namespaces need to be handled differently in that case
218 218 self.embedded = embedded
219 219 if embedded:
220 220 # Control variable so users can, from within the embedded instance,
221 221 # permanently deactivate it.
222 222 self.embedded_active = True
223 223
224 224 # command compiler
225 225 self.compile = codeop.CommandCompiler()
226 226
227 227 # User input buffer
228 228 self.buffer = []
229 229
230 230 # Default name given in compilation of code
231 231 self.filename = '<ipython console>'
232 232
233 233 # Install our own quitter instead of the builtins. For python2.3-2.4,
234 234 # this brings in behavior like 2.5, and for 2.5 it's identical.
235 235 __builtin__.exit = Quitter(self,'exit')
236 236 __builtin__.quit = Quitter(self,'quit')
237 237
238 238 # Make an empty namespace, which extension writers can rely on both
239 239 # existing and NEVER being used by ipython itself. This gives them a
240 240 # convenient location for storing additional information and state
241 241 # their extensions may require, without fear of collisions with other
242 242 # ipython names that may develop later.
243 243 self.meta = Struct()
244 244
245 245 # Create the namespace where the user will operate. user_ns is
246 246 # normally the only one used, and it is passed to the exec calls as
247 247 # the locals argument. But we do carry a user_global_ns namespace
248 248 # given as the exec 'globals' argument, This is useful in embedding
249 249 # situations where the ipython shell opens in a context where the
250 250 # distinction between locals and globals is meaningful. For
251 251 # non-embedded contexts, it is just the same object as the user_ns dict.
252 252
253 253 # FIXME. For some strange reason, __builtins__ is showing up at user
254 254 # level as a dict instead of a module. This is a manual fix, but I
255 255 # should really track down where the problem is coming from. Alex
256 256 # Schmolck reported this problem first.
257 257
258 258 # A useful post by Alex Martelli on this topic:
259 259 # Re: inconsistent value from __builtins__
260 260 # Von: Alex Martelli <aleaxit@yahoo.com>
261 261 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
262 262 # Gruppen: comp.lang.python
263 263
264 264 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
265 265 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
266 266 # > <type 'dict'>
267 267 # > >>> print type(__builtins__)
268 268 # > <type 'module'>
269 269 # > Is this difference in return value intentional?
270 270
271 271 # Well, it's documented that '__builtins__' can be either a dictionary
272 272 # or a module, and it's been that way for a long time. Whether it's
273 273 # intentional (or sensible), I don't know. In any case, the idea is
274 274 # that if you need to access the built-in namespace directly, you
275 275 # should start with "import __builtin__" (note, no 's') which will
276 276 # definitely give you a module. Yeah, it's somewhat confusing:-(.
277 277
278 278 # These routines return properly built dicts as needed by the rest of
279 279 # the code, and can also be used by extension writers to generate
280 280 # properly initialized namespaces.
281 281 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
282 282 user_global_ns)
283 283
284 284 # Assign namespaces
285 285 # This is the namespace where all normal user variables live
286 286 self.user_ns = user_ns
287 287 self.user_global_ns = user_global_ns
288
289 # An auxiliary namespace that checks what parts of the user_ns were
290 # loaded at startup, so we can list later only variables defined in
291 # actual interactive use. Since it is always a subset of user_ns, it
292 # doesn't need to be seaparately tracked in the ns_table
293 self.user_config_ns = {}
294
288 295 # A namespace to keep track of internal data structures to prevent
289 296 # them from cluttering user-visible stuff. Will be updated later
290 297 self.internal_ns = {}
291 298
292 299 # Namespace of system aliases. Each entry in the alias
293 300 # table must be a 2-tuple of the form (N,name), where N is the number
294 301 # of positional arguments of the alias.
295 302 self.alias_table = {}
296 303
304 # Now that FakeModule produces a real module, we've run into a nasty
305 # problem: after script execution (via %run), the module where the user
306 # code ran is deleted. Now that this object is a true module (needed
307 # so docetst and other tools work correctly), the Python module
308 # teardown mechanism runs over it, and sets to None every variable
309 # present in that module. Top-level references to objects from the
310 # script survive, because the user_ns is updated with them. However,
311 # calling functions defined in the script that use other things from
312 # the script will fail, because the function's closure had references
313 # to the original objects, which are now all None. So we must protect
314 # these modules from deletion by keeping a cache. To avoid keeping
315 # stale modules around (we only need the one from the last run), we use
316 # a dict keyed with the full path to the script, so only the last
317 # version of the module is held in the cache. The %reset command will
318 # flush this cache. See the cache_main_mod() and clear_main_mod_cache()
319 # methods for details on use.
320 self._user_main_modules = {}
321
297 322 # A table holding all the namespaces IPython deals with, so that
298 323 # introspection facilities can search easily.
299 324 self.ns_table = {'user':user_ns,
300 325 'user_global':user_global_ns,
301 326 'alias':self.alias_table,
302 327 'internal':self.internal_ns,
303 328 'builtin':__builtin__.__dict__
304 329 }
305 # The user namespace MUST have a pointer to the shell itself.
306 self.user_ns[name] = self
307 330
331 # Similarly, track all namespaces where references can be held and that
332 # we can safely clear (so it can NOT include builtin). This one can be
333 # a simple list.
334 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
335 self.alias_table, self.internal_ns,
336 self._user_main_modules ]
337
308 338 # We need to insert into sys.modules something that looks like a
309 339 # module but which accesses the IPython namespace, for shelve and
310 340 # pickle to work interactively. Normally they rely on getting
311 341 # everything out of __main__, but for embedding purposes each IPython
312 342 # instance has its own private namespace, so we can't go shoving
313 343 # everything into __main__.
314 344
315 345 # note, however, that we should only do this for non-embedded
316 346 # ipythons, which really mimic the __main__.__dict__ with their own
317 347 # namespace. Embedded instances, on the other hand, should not do
318 348 # this because they need to manage the user local/global namespaces
319 349 # only, but they live within a 'normal' __main__ (meaning, they
320 350 # shouldn't overtake the execution environment of the script they're
321 351 # embedded in).
322 352
323 353 if not embedded:
324 354 try:
325 355 main_name = self.user_ns['__name__']
326 356 except KeyError:
327 357 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
328 358 else:
329 359 #print "pickle hack in place" # dbg
330 360 #print 'main_name:',main_name # dbg
331 361 sys.modules[main_name] = FakeModule(self.user_ns)
332
333 # Now that FakeModule produces a real module, we've run into a nasty
334 # problem: after script execution (via %run), the module where the user
335 # code ran is deleted. Now that this object is a true module (needed
336 # so docetst and other tools work correctly), the Python module
337 # teardown mechanism runs over it, and sets to None every variable
338 # present in that module. Top-level references to objects from the
339 # script survive, because the user_ns is updated with them. However,
340 # calling functions defined in the script that use other things from
341 # the script will fail, because the function's closure had references
342 # to the original objects, which are now all None. So we must protect
343 # these modules from deletion by keeping a cache. To avoid keeping
344 # stale modules around (we only need the one from the last run), we use
345 # a dict keyed with the full path to the script, so only the last
346 # version of the module is held in the cache. The %reset command will
347 # flush this cache. See the cache_main_mod() and clear_main_mod_cache()
348 # methods for details on use.
349 self._user_main_modules = {}
350 362
351 363 # List of input with multi-line handling.
352 # Fill its zero entry, user counter starts at 1
353 self.input_hist = InputList(['\n'])
364 self.input_hist = InputList()
354 365 # This one will hold the 'raw' input history, without any
355 366 # pre-processing. This will allow users to retrieve the input just as
356 367 # it was exactly typed in by the user, with %hist -r.
357 self.input_hist_raw = InputList(['\n'])
368 self.input_hist_raw = InputList()
358 369
359 370 # list of visited directories
360 371 try:
361 372 self.dir_hist = [os.getcwd()]
362 373 except OSError:
363 374 self.dir_hist = []
364 375
365 376 # dict of output history
366 377 self.output_hist = {}
367 378
368 379 # Get system encoding at startup time. Certain terminals (like Emacs
369 380 # under Win32 have it set to None, and we need to have a known valid
370 381 # encoding to use in the raw_input() method
371 382 try:
372 383 self.stdin_encoding = sys.stdin.encoding or 'ascii'
373 384 except AttributeError:
374 385 self.stdin_encoding = 'ascii'
375 386
376 387 # dict of things NOT to alias (keywords, builtins and some magics)
377 388 no_alias = {}
378 389 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
379 390 for key in keyword.kwlist + no_alias_magics:
380 391 no_alias[key] = 1
381 392 no_alias.update(__builtin__.__dict__)
382 393 self.no_alias = no_alias
383
384 # make global variables for user access to these
385 self.user_ns['_ih'] = self.input_hist
386 self.user_ns['_oh'] = self.output_hist
387 self.user_ns['_dh'] = self.dir_hist
388
389 # user aliases to input and output histories
390 self.user_ns['In'] = self.input_hist
391 self.user_ns['Out'] = self.output_hist
392 394
393 self.user_ns['_sh'] = IPython.shadowns
394 395 # Object variable to store code object waiting execution. This is
395 396 # used mainly by the multithreaded shells, but it can come in handy in
396 397 # other situations. No need to use a Queue here, since it's a single
397 398 # item which gets cleared once run.
398 399 self.code_to_run = None
399 400
400 401 # escapes for automatic behavior on the command line
401 402 self.ESC_SHELL = '!'
402 403 self.ESC_SH_CAP = '!!'
403 404 self.ESC_HELP = '?'
404 405 self.ESC_MAGIC = '%'
405 406 self.ESC_QUOTE = ','
406 407 self.ESC_QUOTE2 = ';'
407 408 self.ESC_PAREN = '/'
408 409
409 410 # And their associated handlers
410 411 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
411 412 self.ESC_QUOTE : self.handle_auto,
412 413 self.ESC_QUOTE2 : self.handle_auto,
413 414 self.ESC_MAGIC : self.handle_magic,
414 415 self.ESC_HELP : self.handle_help,
415 416 self.ESC_SHELL : self.handle_shell_escape,
416 417 self.ESC_SH_CAP : self.handle_shell_escape,
417 418 }
418 419
419 420 # class initializations
420 421 Magic.__init__(self,self)
421 422
422 423 # Python source parser/formatter for syntax highlighting
423 424 pyformat = PyColorize.Parser().format
424 425 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
425 426
426 427 # hooks holds pointers used for user-side customizations
427 428 self.hooks = Struct()
428 429
429 430 self.strdispatchers = {}
430 431
431 432 # Set all default hooks, defined in the IPython.hooks module.
432 433 hooks = IPython.hooks
433 434 for hook_name in hooks.__all__:
434 435 # default hooks have priority 100, i.e. low; user hooks should have
435 436 # 0-100 priority
436 437 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
437 438 #print "bound hook",hook_name
438 439
439 440 # Flag to mark unconditional exit
440 441 self.exit_now = False
441 442
442 443 self.usage_min = """\
443 444 An enhanced console for Python.
444 445 Some of its features are:
445 446 - Readline support if the readline library is present.
446 447 - Tab completion in the local namespace.
447 448 - Logging of input, see command-line options.
448 449 - System shell escape via ! , eg !ls.
449 450 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
450 451 - Keeps track of locally defined variables via %who, %whos.
451 452 - Show object information with a ? eg ?x or x? (use ?? for more info).
452 453 """
453 454 if usage: self.usage = usage
454 455 else: self.usage = self.usage_min
455 456
456 457 # Storage
457 458 self.rc = rc # This will hold all configuration information
458 459 self.pager = 'less'
459 460 # temporary files used for various purposes. Deleted at exit.
460 461 self.tempfiles = []
461 462
462 463 # Keep track of readline usage (later set by init_readline)
463 464 self.has_readline = False
464 465
465 466 # template for logfile headers. It gets resolved at runtime by the
466 467 # logstart method.
467 468 self.loghead_tpl = \
468 469 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
469 470 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
470 471 #log# opts = %s
471 472 #log# args = %s
472 473 #log# It is safe to make manual edits below here.
473 474 #log#-----------------------------------------------------------------------
474 475 """
475 476 # for pushd/popd management
476 477 try:
477 478 self.home_dir = get_home_dir()
478 479 except HomeDirError,msg:
479 480 fatal(msg)
480 481
481 482 self.dir_stack = []
482 483
483 484 # Functions to call the underlying shell.
484 485
485 486 # The first is similar to os.system, but it doesn't return a value,
486 487 # and it allows interpolation of variables in the user's namespace.
487 488 self.system = lambda cmd: \
488 489 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
489 490
490 491 # These are for getoutput and getoutputerror:
491 492 self.getoutput = lambda cmd: \
492 493 getoutput(self.var_expand(cmd,depth=2),
493 494 header=self.rc.system_header,
494 495 verbose=self.rc.system_verbose)
495 496
496 497 self.getoutputerror = lambda cmd: \
497 498 getoutputerror(self.var_expand(cmd,depth=2),
498 499 header=self.rc.system_header,
499 500 verbose=self.rc.system_verbose)
500 501
501 502
502 503 # keep track of where we started running (mainly for crash post-mortem)
503 504 self.starting_dir = os.getcwd()
504 505
505 506 # Various switches which can be set
506 507 self.CACHELENGTH = 5000 # this is cheap, it's just text
507 508 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
508 509 self.banner2 = banner2
509 510
510 511 # TraceBack handlers:
511 512
512 513 # Syntax error handler.
513 514 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
514 515
515 516 # The interactive one is initialized with an offset, meaning we always
516 517 # want to remove the topmost item in the traceback, which is our own
517 518 # internal code. Valid modes: ['Plain','Context','Verbose']
518 519 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
519 520 color_scheme='NoColor',
520 521 tb_offset = 1)
521 522
522 523 # IPython itself shouldn't crash. This will produce a detailed
523 524 # post-mortem if it does. But we only install the crash handler for
524 525 # non-threaded shells, the threaded ones use a normal verbose reporter
525 526 # and lose the crash handler. This is because exceptions in the main
526 527 # thread (such as in GUI code) propagate directly to sys.excepthook,
527 528 # and there's no point in printing crash dumps for every user exception.
528 529 if self.isthreaded:
529 530 ipCrashHandler = ultraTB.FormattedTB()
530 531 else:
531 532 from IPython import CrashHandler
532 533 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
533 534 self.set_crash_handler(ipCrashHandler)
534 535
535 536 # and add any custom exception handlers the user may have specified
536 537 self.set_custom_exc(*custom_exceptions)
537 538
538 539 # indentation management
539 540 self.autoindent = False
540 541 self.indent_current_nsp = 0
541 542
542 543 # Make some aliases automatically
543 544 # Prepare list of shell aliases to auto-define
544 545 if os.name == 'posix':
545 546 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
546 547 'mv mv -i','rm rm -i','cp cp -i',
547 548 'cat cat','less less','clear clear',
548 549 # a better ls
549 550 'ls ls -F',
550 551 # long ls
551 552 'll ls -lF')
552 553 # Extra ls aliases with color, which need special treatment on BSD
553 554 # variants
554 555 ls_extra = ( # color ls
555 556 'lc ls -F -o --color',
556 557 # ls normal files only
557 558 'lf ls -F -o --color %l | grep ^-',
558 559 # ls symbolic links
559 560 'lk ls -F -o --color %l | grep ^l',
560 561 # directories or links to directories,
561 562 'ldir ls -F -o --color %l | grep /$',
562 563 # things which are executable
563 564 'lx ls -F -o --color %l | grep ^-..x',
564 565 )
565 566 # The BSDs don't ship GNU ls, so they don't understand the
566 567 # --color switch out of the box
567 568 if 'bsd' in sys.platform:
568 569 ls_extra = ( # ls normal files only
569 570 'lf ls -lF | grep ^-',
570 571 # ls symbolic links
571 572 'lk ls -lF | grep ^l',
572 573 # directories or links to directories,
573 574 'ldir ls -lF | grep /$',
574 575 # things which are executable
575 576 'lx ls -lF | grep ^-..x',
576 577 )
577 578 auto_alias = auto_alias + ls_extra
578 579 elif os.name in ['nt','dos']:
579 580 auto_alias = ('ls dir /on',
580 581 'ddir dir /ad /on', 'ldir dir /ad /on',
581 582 'mkdir mkdir','rmdir rmdir','echo echo',
582 583 'ren ren','cls cls','copy copy')
583 584 else:
584 585 auto_alias = ()
585 586 self.auto_alias = [s.split(None,1) for s in auto_alias]
586
587 587
588 588 # Produce a public API instance
589 589 self.api = IPython.ipapi.IPApi(self)
590 590
591 # Initialize all user-visible namespaces
592 self.init_namespaces()
593
591 594 # Call the actual (public) initializer
592 595 self.init_auto_alias()
593 596
594 597 # track which builtins we add, so we can clean up later
595 598 self.builtins_added = {}
596 599 # This method will add the necessary builtins for operation, but
597 600 # tracking what it did via the builtins_added dict.
598 601
599 602 #TODO: remove this, redundant
600 603 self.add_builtins()
601 604 # end __init__
602 605
603 606 def var_expand(self,cmd,depth=0):
604 607 """Expand python variables in a string.
605 608
606 609 The depth argument indicates how many frames above the caller should
607 610 be walked to look for the local namespace where to expand variables.
608 611
609 612 The global namespace for expansion is always the user's interactive
610 613 namespace.
611 614 """
612 615
613 616 return str(ItplNS(cmd,
614 617 self.user_ns, # globals
615 618 # Skip our own frame in searching for locals:
616 619 sys._getframe(depth+1).f_locals # locals
617 620 ))
618 621
619 622 def pre_config_initialization(self):
620 623 """Pre-configuration init method
621 624
622 625 This is called before the configuration files are processed to
623 626 prepare the services the config files might need.
624 627
625 628 self.rc already has reasonable default values at this point.
626 629 """
627 630 rc = self.rc
628 631 try:
629 632 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
630 633 except exceptions.UnicodeDecodeError:
631 634 print "Your ipythondir can't be decoded to unicode!"
632 635 print "Please set HOME environment variable to something that"
633 636 print r"only has ASCII characters, e.g. c:\home"
634 637 print "Now it is",rc.ipythondir
635 638 sys.exit()
636 639 self.shadowhist = IPython.history.ShadowHist(self.db)
637 640
638 641 def post_config_initialization(self):
639 642 """Post configuration init method
640 643
641 644 This is called after the configuration files have been processed to
642 645 'finalize' the initialization."""
643 646
644 647 rc = self.rc
645 648
646 649 # Object inspector
647 650 self.inspector = OInspect.Inspector(OInspect.InspectColors,
648 651 PyColorize.ANSICodeColors,
649 652 'NoColor',
650 653 rc.object_info_string_level)
651 654
652 655 self.rl_next_input = None
653 656 self.rl_do_indent = False
654 657 # Load readline proper
655 658 if rc.readline:
656 659 self.init_readline()
657
658 660
659 661 # local shortcut, this is used a LOT
660 662 self.log = self.logger.log
661 663
662 664 # Initialize cache, set in/out prompts and printing system
663 665 self.outputcache = CachedOutput(self,
664 666 rc.cache_size,
665 667 rc.pprint,
666 668 input_sep = rc.separate_in,
667 669 output_sep = rc.separate_out,
668 670 output_sep2 = rc.separate_out2,
669 671 ps1 = rc.prompt_in1,
670 672 ps2 = rc.prompt_in2,
671 673 ps_out = rc.prompt_out,
672 674 pad_left = rc.prompts_pad_left)
673 675
674 676 # user may have over-ridden the default print hook:
675 677 try:
676 678 self.outputcache.__class__.display = self.hooks.display
677 679 except AttributeError:
678 680 pass
679 681
680 682 # I don't like assigning globally to sys, because it means when
681 683 # embedding instances, each embedded instance overrides the previous
682 684 # choice. But sys.displayhook seems to be called internally by exec,
683 685 # so I don't see a way around it. We first save the original and then
684 686 # overwrite it.
685 687 self.sys_displayhook = sys.displayhook
686 688 sys.displayhook = self.outputcache
687 689
688 690 # Do a proper resetting of doctest, including the necessary displayhook
689 691 # monkeypatching
690 692 try:
691 693 doctest_reload()
692 694 except ImportError:
693 695 warn("doctest module does not exist.")
694 696
695 697 # Set user colors (don't do it in the constructor above so that it
696 698 # doesn't crash if colors option is invalid)
697 699 self.magic_colors(rc.colors)
698 700
699 701 # Set calling of pdb on exceptions
700 702 self.call_pdb = rc.pdb
701 703
702 704 # Load user aliases
703 705 for alias in rc.alias:
704 706 self.magic_alias(alias)
705 707
706 708 self.hooks.late_startup_hook()
707 709
708 710 for cmd in self.rc.autoexec:
709 711 #print "autoexec>",cmd #dbg
710 712 self.api.runlines(cmd)
711 713
712 714 batchrun = False
713 715 for batchfile in [path(arg) for arg in self.rc.args
714 716 if arg.lower().endswith('.ipy')]:
715 717 if not batchfile.isfile():
716 718 print "No such batch file:", batchfile
717 719 continue
718 720 self.api.runlines(batchfile.text())
719 721 batchrun = True
720 722 # without -i option, exit after running the batch file
721 723 if batchrun and not self.rc.interact:
722 724 self.ask_exit()
723 725
726 def init_namespaces(self):
727 """Initialize all user-visible namespaces to their minimum defaults.
728
729 Certain history lists are also initialized here, as they effectively
730 act as user namespaces.
731
732 Note
733 ----
734 All data structures here are only filled in, they are NOT reset by this
735 method. If they were not empty before, data will simply be added to
736 therm.
737 """
738 # The user namespace MUST have a pointer to the shell itself.
739 self.user_ns[self.name] = self
740
741 # Store the public api instance
742 self.user_ns['_ip'] = self.api
743
744 # make global variables for user access to the histories
745 self.user_ns['_ih'] = self.input_hist
746 self.user_ns['_oh'] = self.output_hist
747 self.user_ns['_dh'] = self.dir_hist
748
749 # user aliases to input and output histories
750 self.user_ns['In'] = self.input_hist
751 self.user_ns['Out'] = self.output_hist
752
753 self.user_ns['_sh'] = IPython.shadowns
754
755 # Fill the history zero entry, user counter starts at 1
756 self.input_hist.append('\n')
757 self.input_hist_raw.append('\n')
758
724 759 def add_builtins(self):
725 760 """Store ipython references into the builtin namespace.
726 761
727 762 Some parts of ipython operate via builtins injected here, which hold a
728 763 reference to IPython itself."""
729 764
730 765 # TODO: deprecate all of these, they are unsafe
731 766 builtins_new = dict(__IPYTHON__ = self,
732 767 ip_set_hook = self.set_hook,
733 768 jobs = self.jobs,
734 769 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
735 770 ipalias = wrap_deprecated(self.ipalias),
736 771 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
737 772 #_ip = self.api
738 773 )
739 774 for biname,bival in builtins_new.items():
740 775 try:
741 776 # store the orignal value so we can restore it
742 777 self.builtins_added[biname] = __builtin__.__dict__[biname]
743 778 except KeyError:
744 779 # or mark that it wasn't defined, and we'll just delete it at
745 780 # cleanup
746 781 self.builtins_added[biname] = Undefined
747 782 __builtin__.__dict__[biname] = bival
748 783
749 784 # Keep in the builtins a flag for when IPython is active. We set it
750 785 # with setdefault so that multiple nested IPythons don't clobber one
751 786 # another. Each will increase its value by one upon being activated,
752 787 # which also gives us a way to determine the nesting level.
753 788 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
754 789
755 790 def clean_builtins(self):
756 791 """Remove any builtins which might have been added by add_builtins, or
757 792 restore overwritten ones to their previous values."""
758 793 for biname,bival in self.builtins_added.items():
759 794 if bival is Undefined:
760 795 del __builtin__.__dict__[biname]
761 796 else:
762 797 __builtin__.__dict__[biname] = bival
763 798 self.builtins_added.clear()
764 799
765 800 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
766 801 """set_hook(name,hook) -> sets an internal IPython hook.
767 802
768 803 IPython exposes some of its internal API as user-modifiable hooks. By
769 804 adding your function to one of these hooks, you can modify IPython's
770 805 behavior to call at runtime your own routines."""
771 806
772 807 # At some point in the future, this should validate the hook before it
773 808 # accepts it. Probably at least check that the hook takes the number
774 809 # of args it's supposed to.
775 810
776 811 f = new.instancemethod(hook,self,self.__class__)
777 812
778 813 # check if the hook is for strdispatcher first
779 814 if str_key is not None:
780 815 sdp = self.strdispatchers.get(name, StrDispatch())
781 816 sdp.add_s(str_key, f, priority )
782 817 self.strdispatchers[name] = sdp
783 818 return
784 819 if re_key is not None:
785 820 sdp = self.strdispatchers.get(name, StrDispatch())
786 821 sdp.add_re(re.compile(re_key), f, priority )
787 822 self.strdispatchers[name] = sdp
788 823 return
789 824
790 825 dp = getattr(self.hooks, name, None)
791 826 if name not in IPython.hooks.__all__:
792 827 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
793 828 if not dp:
794 829 dp = IPython.hooks.CommandChainDispatcher()
795 830
796 831 try:
797 832 dp.add(f,priority)
798 833 except AttributeError:
799 834 # it was not commandchain, plain old func - replace
800 835 dp = f
801 836
802 837 setattr(self.hooks,name, dp)
803 838
804 839
805 840 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
806 841
807 842 def set_crash_handler(self,crashHandler):
808 843 """Set the IPython crash handler.
809 844
810 845 This must be a callable with a signature suitable for use as
811 846 sys.excepthook."""
812 847
813 848 # Install the given crash handler as the Python exception hook
814 849 sys.excepthook = crashHandler
815 850
816 851 # The instance will store a pointer to this, so that runtime code
817 852 # (such as magics) can access it. This is because during the
818 853 # read-eval loop, it gets temporarily overwritten (to deal with GUI
819 854 # frameworks).
820 855 self.sys_excepthook = sys.excepthook
821 856
822 857
823 858 def set_custom_exc(self,exc_tuple,handler):
824 859 """set_custom_exc(exc_tuple,handler)
825 860
826 861 Set a custom exception handler, which will be called if any of the
827 862 exceptions in exc_tuple occur in the mainloop (specifically, in the
828 863 runcode() method.
829 864
830 865 Inputs:
831 866
832 867 - exc_tuple: a *tuple* of valid exceptions to call the defined
833 868 handler for. It is very important that you use a tuple, and NOT A
834 869 LIST here, because of the way Python's except statement works. If
835 870 you only want to trap a single exception, use a singleton tuple:
836 871
837 872 exc_tuple == (MyCustomException,)
838 873
839 874 - handler: this must be defined as a function with the following
840 875 basic interface: def my_handler(self,etype,value,tb).
841 876
842 877 This will be made into an instance method (via new.instancemethod)
843 878 of IPython itself, and it will be called if any of the exceptions
844 879 listed in the exc_tuple are caught. If the handler is None, an
845 880 internal basic one is used, which just prints basic info.
846 881
847 882 WARNING: by putting in your own exception handler into IPython's main
848 883 execution loop, you run a very good chance of nasty crashes. This
849 884 facility should only be used if you really know what you are doing."""
850 885
851 886 assert type(exc_tuple)==type(()) , \
852 887 "The custom exceptions must be given AS A TUPLE."
853 888
854 889 def dummy_handler(self,etype,value,tb):
855 890 print '*** Simple custom exception handler ***'
856 891 print 'Exception type :',etype
857 892 print 'Exception value:',value
858 893 print 'Traceback :',tb
859 894 print 'Source code :','\n'.join(self.buffer)
860 895
861 896 if handler is None: handler = dummy_handler
862 897
863 898 self.CustomTB = new.instancemethod(handler,self,self.__class__)
864 899 self.custom_exceptions = exc_tuple
865 900
866 901 def set_custom_completer(self,completer,pos=0):
867 902 """set_custom_completer(completer,pos=0)
868 903
869 904 Adds a new custom completer function.
870 905
871 906 The position argument (defaults to 0) is the index in the completers
872 907 list where you want the completer to be inserted."""
873 908
874 909 newcomp = new.instancemethod(completer,self.Completer,
875 910 self.Completer.__class__)
876 911 self.Completer.matchers.insert(pos,newcomp)
877 912
878 913 def set_completer(self):
879 914 """reset readline's completer to be our own."""
880 915 self.readline.set_completer(self.Completer.complete)
881 916
882 917 def _get_call_pdb(self):
883 918 return self._call_pdb
884 919
885 920 def _set_call_pdb(self,val):
886 921
887 922 if val not in (0,1,False,True):
888 923 raise ValueError,'new call_pdb value must be boolean'
889 924
890 925 # store value in instance
891 926 self._call_pdb = val
892 927
893 928 # notify the actual exception handlers
894 929 self.InteractiveTB.call_pdb = val
895 930 if self.isthreaded:
896 931 try:
897 932 self.sys_excepthook.call_pdb = val
898 933 except:
899 934 warn('Failed to activate pdb for threaded exception handler')
900 935
901 936 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
902 937 'Control auto-activation of pdb at exceptions')
903 938
904 939 # These special functions get installed in the builtin namespace, to
905 940 # provide programmatic (pure python) access to magics, aliases and system
906 941 # calls. This is important for logging, user scripting, and more.
907 942
908 943 # We are basically exposing, via normal python functions, the three
909 944 # mechanisms in which ipython offers special call modes (magics for
910 945 # internal control, aliases for direct system access via pre-selected
911 946 # names, and !cmd for calling arbitrary system commands).
912 947
913 948 def ipmagic(self,arg_s):
914 949 """Call a magic function by name.
915 950
916 951 Input: a string containing the name of the magic function to call and any
917 952 additional arguments to be passed to the magic.
918 953
919 954 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
920 955 prompt:
921 956
922 957 In[1]: %name -opt foo bar
923 958
924 959 To call a magic without arguments, simply use ipmagic('name').
925 960
926 961 This provides a proper Python function to call IPython's magics in any
927 962 valid Python code you can type at the interpreter, including loops and
928 963 compound statements. It is added by IPython to the Python builtin
929 964 namespace upon initialization."""
930 965
931 966 args = arg_s.split(' ',1)
932 967 magic_name = args[0]
933 968 magic_name = magic_name.lstrip(self.ESC_MAGIC)
934 969
935 970 try:
936 971 magic_args = args[1]
937 972 except IndexError:
938 973 magic_args = ''
939 974 fn = getattr(self,'magic_'+magic_name,None)
940 975 if fn is None:
941 976 error("Magic function `%s` not found." % magic_name)
942 977 else:
943 978 magic_args = self.var_expand(magic_args,1)
944 979 return fn(magic_args)
945 980
946 981 def ipalias(self,arg_s):
947 982 """Call an alias by name.
948 983
949 984 Input: a string containing the name of the alias to call and any
950 985 additional arguments to be passed to the magic.
951 986
952 987 ipalias('name -opt foo bar') is equivalent to typing at the ipython
953 988 prompt:
954 989
955 990 In[1]: name -opt foo bar
956 991
957 992 To call an alias without arguments, simply use ipalias('name').
958 993
959 994 This provides a proper Python function to call IPython's aliases in any
960 995 valid Python code you can type at the interpreter, including loops and
961 996 compound statements. It is added by IPython to the Python builtin
962 997 namespace upon initialization."""
963 998
964 999 args = arg_s.split(' ',1)
965 1000 alias_name = args[0]
966 1001 try:
967 1002 alias_args = args[1]
968 1003 except IndexError:
969 1004 alias_args = ''
970 1005 if alias_name in self.alias_table:
971 1006 self.call_alias(alias_name,alias_args)
972 1007 else:
973 1008 error("Alias `%s` not found." % alias_name)
974 1009
975 1010 def ipsystem(self,arg_s):
976 1011 """Make a system call, using IPython."""
977 1012
978 1013 self.system(arg_s)
979 1014
980 1015 def complete(self,text):
981 1016 """Return a sorted list of all possible completions on text.
982 1017
983 1018 Inputs:
984 1019
985 1020 - text: a string of text to be completed on.
986 1021
987 1022 This is a wrapper around the completion mechanism, similar to what
988 1023 readline does at the command line when the TAB key is hit. By
989 1024 exposing it as a method, it can be used by other non-readline
990 1025 environments (such as GUIs) for text completion.
991 1026
992 1027 Simple usage example:
993 1028
994 1029 In [7]: x = 'hello'
995 1030
996 1031 In [8]: x
997 1032 Out[8]: 'hello'
998 1033
999 1034 In [9]: print x
1000 1035 hello
1001 1036
1002 1037 In [10]: _ip.IP.complete('x.l')
1003 1038 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1004 1039 """
1005 1040
1006 1041 complete = self.Completer.complete
1007 1042 state = 0
1008 1043 # use a dict so we get unique keys, since ipyhton's multiple
1009 1044 # completers can return duplicates. When we make 2.4 a requirement,
1010 1045 # start using sets instead, which are faster.
1011 1046 comps = {}
1012 1047 while True:
1013 1048 newcomp = complete(text,state,line_buffer=text)
1014 1049 if newcomp is None:
1015 1050 break
1016 1051 comps[newcomp] = 1
1017 1052 state += 1
1018 1053 outcomps = comps.keys()
1019 1054 outcomps.sort()
1020 1055 #print "T:",text,"OC:",outcomps # dbg
1021 1056 #print "vars:",self.user_ns.keys()
1022 1057 return outcomps
1023 1058
1024 1059 def set_completer_frame(self, frame=None):
1025 1060 if frame:
1026 1061 self.Completer.namespace = frame.f_locals
1027 1062 self.Completer.global_namespace = frame.f_globals
1028 1063 else:
1029 1064 self.Completer.namespace = self.user_ns
1030 1065 self.Completer.global_namespace = self.user_global_ns
1031 1066
1032 1067 def init_auto_alias(self):
1033 1068 """Define some aliases automatically.
1034 1069
1035 1070 These are ALL parameter-less aliases"""
1036 1071
1037 1072 for alias,cmd in self.auto_alias:
1038 1073 self.getapi().defalias(alias,cmd)
1039 1074
1040 1075
1041 1076 def alias_table_validate(self,verbose=0):
1042 1077 """Update information about the alias table.
1043 1078
1044 1079 In particular, make sure no Python keywords/builtins are in it."""
1045 1080
1046 1081 no_alias = self.no_alias
1047 1082 for k in self.alias_table.keys():
1048 1083 if k in no_alias:
1049 1084 del self.alias_table[k]
1050 1085 if verbose:
1051 1086 print ("Deleting alias <%s>, it's a Python "
1052 1087 "keyword or builtin." % k)
1053 1088
1054 1089 def set_autoindent(self,value=None):
1055 1090 """Set the autoindent flag, checking for readline support.
1056 1091
1057 1092 If called with no arguments, it acts as a toggle."""
1058 1093
1059 1094 if not self.has_readline:
1060 1095 if os.name == 'posix':
1061 1096 warn("The auto-indent feature requires the readline library")
1062 1097 self.autoindent = 0
1063 1098 return
1064 1099 if value is None:
1065 1100 self.autoindent = not self.autoindent
1066 1101 else:
1067 1102 self.autoindent = value
1068 1103
1069 1104 def rc_set_toggle(self,rc_field,value=None):
1070 1105 """Set or toggle a field in IPython's rc config. structure.
1071 1106
1072 1107 If called with no arguments, it acts as a toggle.
1073 1108
1074 1109 If called with a non-existent field, the resulting AttributeError
1075 1110 exception will propagate out."""
1076 1111
1077 1112 rc_val = getattr(self.rc,rc_field)
1078 1113 if value is None:
1079 1114 value = not rc_val
1080 1115 setattr(self.rc,rc_field,value)
1081 1116
1082 1117 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1083 1118 """Install the user configuration directory.
1084 1119
1085 1120 Can be called when running for the first time or to upgrade the user's
1086 1121 .ipython/ directory with the mode parameter. Valid modes are 'install'
1087 1122 and 'upgrade'."""
1088 1123
1089 1124 def wait():
1090 1125 try:
1091 1126 raw_input("Please press <RETURN> to start IPython.")
1092 1127 except EOFError:
1093 1128 print >> Term.cout
1094 1129 print '*'*70
1095 1130
1096 1131 cwd = os.getcwd() # remember where we started
1097 1132 glb = glob.glob
1098 1133 print '*'*70
1099 1134 if mode == 'install':
1100 1135 print \
1101 1136 """Welcome to IPython. I will try to create a personal configuration directory
1102 1137 where you can customize many aspects of IPython's functionality in:\n"""
1103 1138 else:
1104 1139 print 'I am going to upgrade your configuration in:'
1105 1140
1106 1141 print ipythondir
1107 1142
1108 1143 rcdirend = os.path.join('IPython','UserConfig')
1109 1144 cfg = lambda d: os.path.join(d,rcdirend)
1110 1145 try:
1111 1146 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1112 1147 print "Initializing from configuration",rcdir
1113 1148 except IndexError:
1114 1149 warning = """
1115 1150 Installation error. IPython's directory was not found.
1116 1151
1117 1152 Check the following:
1118 1153
1119 1154 The ipython/IPython directory should be in a directory belonging to your
1120 1155 PYTHONPATH environment variable (that is, it should be in a directory
1121 1156 belonging to sys.path). You can copy it explicitly there or just link to it.
1122 1157
1123 1158 IPython will create a minimal default configuration for you.
1124 1159
1125 1160 """
1126 1161 warn(warning)
1127 1162 wait()
1128 1163
1129 1164 if sys.platform =='win32':
1130 1165 inif = 'ipythonrc.ini'
1131 1166 else:
1132 1167 inif = 'ipythonrc'
1133 1168 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
1134 1169 inif : '# intentionally left blank' }
1135 1170 os.makedirs(ipythondir, mode = 0777)
1136 1171 for f, cont in minimal_setup.items():
1137 1172 open(ipythondir + '/' + f,'w').write(cont)
1138 1173
1139 1174 return
1140 1175
1141 1176 if mode == 'install':
1142 1177 try:
1143 1178 shutil.copytree(rcdir,ipythondir)
1144 1179 os.chdir(ipythondir)
1145 1180 rc_files = glb("ipythonrc*")
1146 1181 for rc_file in rc_files:
1147 1182 os.rename(rc_file,rc_file+rc_suffix)
1148 1183 except:
1149 1184 warning = """
1150 1185
1151 1186 There was a problem with the installation:
1152 1187 %s
1153 1188 Try to correct it or contact the developers if you think it's a bug.
1154 1189 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1155 1190 warn(warning)
1156 1191 wait()
1157 1192 return
1158 1193
1159 1194 elif mode == 'upgrade':
1160 1195 try:
1161 1196 os.chdir(ipythondir)
1162 1197 except:
1163 1198 print """
1164 1199 Can not upgrade: changing to directory %s failed. Details:
1165 1200 %s
1166 1201 """ % (ipythondir,sys.exc_info()[1])
1167 1202 wait()
1168 1203 return
1169 1204 else:
1170 1205 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1171 1206 for new_full_path in sources:
1172 1207 new_filename = os.path.basename(new_full_path)
1173 1208 if new_filename.startswith('ipythonrc'):
1174 1209 new_filename = new_filename + rc_suffix
1175 1210 # The config directory should only contain files, skip any
1176 1211 # directories which may be there (like CVS)
1177 1212 if os.path.isdir(new_full_path):
1178 1213 continue
1179 1214 if os.path.exists(new_filename):
1180 1215 old_file = new_filename+'.old'
1181 1216 if os.path.exists(old_file):
1182 1217 os.remove(old_file)
1183 1218 os.rename(new_filename,old_file)
1184 1219 shutil.copy(new_full_path,new_filename)
1185 1220 else:
1186 1221 raise ValueError,'unrecognized mode for install:',`mode`
1187 1222
1188 1223 # Fix line-endings to those native to each platform in the config
1189 1224 # directory.
1190 1225 try:
1191 1226 os.chdir(ipythondir)
1192 1227 except:
1193 1228 print """
1194 1229 Problem: changing to directory %s failed.
1195 1230 Details:
1196 1231 %s
1197 1232
1198 1233 Some configuration files may have incorrect line endings. This should not
1199 1234 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1200 1235 wait()
1201 1236 else:
1202 1237 for fname in glb('ipythonrc*'):
1203 1238 try:
1204 1239 native_line_ends(fname,backup=0)
1205 1240 except IOError:
1206 1241 pass
1207 1242
1208 1243 if mode == 'install':
1209 1244 print """
1210 1245 Successful installation!
1211 1246
1212 1247 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1213 1248 IPython manual (there are both HTML and PDF versions supplied with the
1214 1249 distribution) to make sure that your system environment is properly configured
1215 1250 to take advantage of IPython's features.
1216 1251
1217 1252 Important note: the configuration system has changed! The old system is
1218 1253 still in place, but its setting may be partly overridden by the settings in
1219 1254 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1220 1255 if some of the new settings bother you.
1221 1256
1222 1257 """
1223 1258 else:
1224 1259 print """
1225 1260 Successful upgrade!
1226 1261
1227 1262 All files in your directory:
1228 1263 %(ipythondir)s
1229 1264 which would have been overwritten by the upgrade were backed up with a .old
1230 1265 extension. If you had made particular customizations in those files you may
1231 1266 want to merge them back into the new files.""" % locals()
1232 1267 wait()
1233 1268 os.chdir(cwd)
1234 1269 # end user_setup()
1235 1270
1236 1271 def atexit_operations(self):
1237 1272 """This will be executed at the time of exit.
1238 1273
1239 1274 Saving of persistent data should be performed here. """
1240 1275
1241 1276 #print '*** IPython exit cleanup ***' # dbg
1242 1277 # input history
1243 1278 self.savehist()
1244 1279
1245 1280 # Cleanup all tempfiles left around
1246 1281 for tfile in self.tempfiles:
1247 1282 try:
1248 1283 os.unlink(tfile)
1249 1284 except OSError:
1250 1285 pass
1251 1286
1287 # Clear all user namespaces to release all references cleanly.
1288 self.reset()
1289
1290 # Run user hooks
1252 1291 self.hooks.shutdown_hook()
1292
1293 def reset(self):
1294 """Clear all internal namespaces.
1295
1296 Note that this is much more aggressive than %reset, since it clears
1297 fully all namespaces, as well as all input/output lists.
1298 """
1299 for ns in self.ns_refs_table:
1300 ns.clear()
1301
1302 # Clear input and output histories
1303 self.input_hist[:] = []
1304 self.input_hist_raw[:] = []
1305 self.output_hist.clear()
1306 # Restore the user namespaces to minimal usability
1307 self.init_namespaces()
1253 1308
1254 1309 def savehist(self):
1255 1310 """Save input history to a file (via readline library)."""
1256 1311
1257 1312 if not self.has_readline:
1258 1313 return
1259 1314
1260 1315 try:
1261 1316 self.readline.write_history_file(self.histfile)
1262 1317 except:
1263 1318 print 'Unable to save IPython command history to file: ' + \
1264 1319 `self.histfile`
1265 1320
1266 1321 def reloadhist(self):
1267 1322 """Reload the input history from disk file."""
1268 1323
1269 1324 if self.has_readline:
1270 1325 try:
1271 1326 self.readline.clear_history()
1272 1327 self.readline.read_history_file(self.shell.histfile)
1273 1328 except AttributeError:
1274 1329 pass
1275 1330
1276 1331
1277 1332 def history_saving_wrapper(self, func):
1278 1333 """ Wrap func for readline history saving
1279 1334
1280 1335 Convert func into callable that saves & restores
1281 1336 history around the call """
1282 1337
1283 1338 if not self.has_readline:
1284 1339 return func
1285 1340
1286 1341 def wrapper():
1287 1342 self.savehist()
1288 1343 try:
1289 1344 func()
1290 1345 finally:
1291 1346 readline.read_history_file(self.histfile)
1292 1347 return wrapper
1293 1348
1294 1349 def pre_readline(self):
1295 1350 """readline hook to be used at the start of each line.
1296 1351
1297 1352 Currently it handles auto-indent only."""
1298 1353
1299 1354 #debugx('self.indent_current_nsp','pre_readline:')
1300 1355
1301 1356 if self.rl_do_indent:
1302 1357 self.readline.insert_text(self.indent_current_str())
1303 1358 if self.rl_next_input is not None:
1304 1359 self.readline.insert_text(self.rl_next_input)
1305 1360 self.rl_next_input = None
1306 1361
1307 1362 def init_readline(self):
1308 1363 """Command history completion/saving/reloading."""
1309 1364
1310 1365
1311 1366 import IPython.rlineimpl as readline
1312 1367
1313 1368 if not readline.have_readline:
1314 1369 self.has_readline = 0
1315 1370 self.readline = None
1316 1371 # no point in bugging windows users with this every time:
1317 1372 warn('Readline services not available on this platform.')
1318 1373 else:
1319 1374 sys.modules['readline'] = readline
1320 1375 import atexit
1321 1376 from IPython.completer import IPCompleter
1322 1377 self.Completer = IPCompleter(self,
1323 1378 self.user_ns,
1324 1379 self.user_global_ns,
1325 1380 self.rc.readline_omit__names,
1326 1381 self.alias_table)
1327 1382 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1328 1383 self.strdispatchers['complete_command'] = sdisp
1329 1384 self.Completer.custom_completers = sdisp
1330 1385 # Platform-specific configuration
1331 1386 if os.name == 'nt':
1332 1387 self.readline_startup_hook = readline.set_pre_input_hook
1333 1388 else:
1334 1389 self.readline_startup_hook = readline.set_startup_hook
1335 1390
1336 1391 # Load user's initrc file (readline config)
1337 1392 # Or if libedit is used, load editrc.
1338 1393 inputrc_name = os.environ.get('INPUTRC')
1339 1394 if inputrc_name is None:
1340 1395 home_dir = get_home_dir()
1341 1396 if home_dir is not None:
1342 1397 inputrc_name = '.inputrc'
1343 1398 if readline.uses_libedit:
1344 1399 inputrc_name = '.editrc'
1345 1400 inputrc_name = os.path.join(home_dir, inputrc_name)
1346 1401 if os.path.isfile(inputrc_name):
1347 1402 try:
1348 1403 readline.read_init_file(inputrc_name)
1349 1404 except:
1350 1405 warn('Problems reading readline initialization file <%s>'
1351 1406 % inputrc_name)
1352 1407
1353 1408 self.has_readline = 1
1354 1409 self.readline = readline
1355 1410 # save this in sys so embedded copies can restore it properly
1356 1411 sys.ipcompleter = self.Completer.complete
1357 1412 self.set_completer()
1358 1413
1359 1414 # Configure readline according to user's prefs
1360 1415 # This is only done if GNU readline is being used. If libedit
1361 1416 # is being used (as on Leopard) the readline config is
1362 1417 # not run as the syntax for libedit is different.
1363 1418 if not readline.uses_libedit:
1364 1419 for rlcommand in self.rc.readline_parse_and_bind:
1365 1420 readline.parse_and_bind(rlcommand)
1366 1421
1367 1422 # remove some chars from the delimiters list
1368 1423 delims = readline.get_completer_delims()
1369 1424 delims = delims.translate(string._idmap,
1370 1425 self.rc.readline_remove_delims)
1371 1426 readline.set_completer_delims(delims)
1372 1427 # otherwise we end up with a monster history after a while:
1373 1428 readline.set_history_length(1000)
1374 1429 try:
1375 1430 #print '*** Reading readline history' # dbg
1376 1431 readline.read_history_file(self.histfile)
1377 1432 except IOError:
1378 1433 pass # It doesn't exist yet.
1379 1434
1380 1435 atexit.register(self.atexit_operations)
1381 1436 del atexit
1382 1437
1383 1438 # Configure auto-indent for all platforms
1384 1439 self.set_autoindent(self.rc.autoindent)
1385 1440
1386 1441 def ask_yes_no(self,prompt,default=True):
1387 1442 if self.rc.quiet:
1388 1443 return True
1389 1444 return ask_yes_no(prompt,default)
1390 1445
1391 1446 def cache_main_mod(self,mod):
1392 1447 """Cache a main module.
1393 1448
1394 1449 When scripts are executed via %run, we must keep a reference to their
1395 1450 __main__ module (a FakeModule instance) around so that Python doesn't
1396 1451 clear it, rendering objects defined therein useless.
1397 1452
1398 1453 This method keeps said reference in a private dict, keyed by the
1399 1454 absolute path of the module object (which corresponds to the script
1400 1455 path). This way, for multiple executions of the same script we only
1401 1456 keep one copy of __main__ (the last one), thus preventing memory leaks
1402 1457 from old references while allowing the objects from the last execution
1403 1458 to be accessible.
1404 1459
1405 1460 Parameters
1406 1461 ----------
1407 1462 mod : a module object
1408 1463
1409 1464 Examples
1410 1465 --------
1411 1466
1412 1467 In [10]: import IPython
1413 1468
1414 1469 In [11]: _ip.IP.cache_main_mod(IPython)
1415 1470
1416 1471 In [12]: IPython.__file__ in _ip.IP._user_main_modules
1417 1472 Out[12]: True
1418 1473 """
1419 1474 self._user_main_modules[os.path.abspath(mod.__file__) ] = mod
1420 1475
1421 1476 def clear_main_mod_cache(self):
1422 1477 """Clear the cache of main modules.
1423 1478
1424 1479 Mainly for use by utilities like %reset.
1425 1480
1426 1481 Examples
1427 1482 --------
1428 1483
1429 1484 In [15]: import IPython
1430 1485
1431 1486 In [16]: _ip.IP.cache_main_mod(IPython)
1432 1487
1433 1488 In [17]: len(_ip.IP._user_main_modules) > 0
1434 1489 Out[17]: True
1435 1490
1436 1491 In [18]: _ip.IP.clear_main_mod_cache()
1437 1492
1438 1493 In [19]: len(_ip.IP._user_main_modules) == 0
1439 1494 Out[19]: True
1440 1495 """
1441 1496 self._user_main_modules.clear()
1442 1497
1443 1498 def _should_recompile(self,e):
1444 1499 """Utility routine for edit_syntax_error"""
1445 1500
1446 1501 if e.filename in ('<ipython console>','<input>','<string>',
1447 1502 '<console>','<BackgroundJob compilation>',
1448 1503 None):
1449 1504
1450 1505 return False
1451 1506 try:
1452 1507 if (self.rc.autoedit_syntax and
1453 1508 not self.ask_yes_no('Return to editor to correct syntax error? '
1454 1509 '[Y/n] ','y')):
1455 1510 return False
1456 1511 except EOFError:
1457 1512 return False
1458 1513
1459 1514 def int0(x):
1460 1515 try:
1461 1516 return int(x)
1462 1517 except TypeError:
1463 1518 return 0
1464 1519 # always pass integer line and offset values to editor hook
1465 1520 self.hooks.fix_error_editor(e.filename,
1466 1521 int0(e.lineno),int0(e.offset),e.msg)
1467 1522 return True
1468 1523
1469 1524 def edit_syntax_error(self):
1470 1525 """The bottom half of the syntax error handler called in the main loop.
1471 1526
1472 1527 Loop until syntax error is fixed or user cancels.
1473 1528 """
1474 1529
1475 1530 while self.SyntaxTB.last_syntax_error:
1476 1531 # copy and clear last_syntax_error
1477 1532 err = self.SyntaxTB.clear_err_state()
1478 1533 if not self._should_recompile(err):
1479 1534 return
1480 1535 try:
1481 1536 # may set last_syntax_error again if a SyntaxError is raised
1482 1537 self.safe_execfile(err.filename,self.user_ns)
1483 1538 except:
1484 1539 self.showtraceback()
1485 1540 else:
1486 1541 try:
1487 1542 f = file(err.filename)
1488 1543 try:
1489 1544 sys.displayhook(f.read())
1490 1545 finally:
1491 1546 f.close()
1492 1547 except:
1493 1548 self.showtraceback()
1494 1549
1495 1550 def showsyntaxerror(self, filename=None):
1496 1551 """Display the syntax error that just occurred.
1497 1552
1498 1553 This doesn't display a stack trace because there isn't one.
1499 1554
1500 1555 If a filename is given, it is stuffed in the exception instead
1501 1556 of what was there before (because Python's parser always uses
1502 1557 "<string>" when reading from a string).
1503 1558 """
1504 1559 etype, value, last_traceback = sys.exc_info()
1505 1560
1506 1561 # See note about these variables in showtraceback() below
1507 1562 sys.last_type = etype
1508 1563 sys.last_value = value
1509 1564 sys.last_traceback = last_traceback
1510 1565
1511 1566 if filename and etype is SyntaxError:
1512 1567 # Work hard to stuff the correct filename in the exception
1513 1568 try:
1514 1569 msg, (dummy_filename, lineno, offset, line) = value
1515 1570 except:
1516 1571 # Not the format we expect; leave it alone
1517 1572 pass
1518 1573 else:
1519 1574 # Stuff in the right filename
1520 1575 try:
1521 1576 # Assume SyntaxError is a class exception
1522 1577 value = SyntaxError(msg, (filename, lineno, offset, line))
1523 1578 except:
1524 1579 # If that failed, assume SyntaxError is a string
1525 1580 value = msg, (filename, lineno, offset, line)
1526 1581 self.SyntaxTB(etype,value,[])
1527 1582
1528 1583 def debugger(self,force=False):
1529 1584 """Call the pydb/pdb debugger.
1530 1585
1531 1586 Keywords:
1532 1587
1533 1588 - force(False): by default, this routine checks the instance call_pdb
1534 1589 flag and does not actually invoke the debugger if the flag is false.
1535 1590 The 'force' option forces the debugger to activate even if the flag
1536 1591 is false.
1537 1592 """
1538 1593
1539 1594 if not (force or self.call_pdb):
1540 1595 return
1541 1596
1542 1597 if not hasattr(sys,'last_traceback'):
1543 1598 error('No traceback has been produced, nothing to debug.')
1544 1599 return
1545 1600
1546 1601 # use pydb if available
1547 1602 if Debugger.has_pydb:
1548 1603 from pydb import pm
1549 1604 else:
1550 1605 # fallback to our internal debugger
1551 1606 pm = lambda : self.InteractiveTB.debugger(force=True)
1552 1607 self.history_saving_wrapper(pm)()
1553 1608
1554 1609 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1555 1610 """Display the exception that just occurred.
1556 1611
1557 1612 If nothing is known about the exception, this is the method which
1558 1613 should be used throughout the code for presenting user tracebacks,
1559 1614 rather than directly invoking the InteractiveTB object.
1560 1615
1561 1616 A specific showsyntaxerror() also exists, but this method can take
1562 1617 care of calling it if needed, so unless you are explicitly catching a
1563 1618 SyntaxError exception, don't try to analyze the stack manually and
1564 1619 simply call this method."""
1565 1620
1566 1621
1567 1622 # Though this won't be called by syntax errors in the input line,
1568 1623 # there may be SyntaxError cases whith imported code.
1569 1624
1570 1625 try:
1571 1626 if exc_tuple is None:
1572 1627 etype, value, tb = sys.exc_info()
1573 1628 else:
1574 1629 etype, value, tb = exc_tuple
1575 1630
1576 1631 if etype is SyntaxError:
1577 1632 self.showsyntaxerror(filename)
1578 1633 elif etype is IPython.ipapi.UsageError:
1579 1634 print "UsageError:", value
1580 1635 else:
1581 1636 # WARNING: these variables are somewhat deprecated and not
1582 1637 # necessarily safe to use in a threaded environment, but tools
1583 1638 # like pdb depend on their existence, so let's set them. If we
1584 1639 # find problems in the field, we'll need to revisit their use.
1585 1640 sys.last_type = etype
1586 1641 sys.last_value = value
1587 1642 sys.last_traceback = tb
1588 1643
1589 1644 if etype in self.custom_exceptions:
1590 1645 self.CustomTB(etype,value,tb)
1591 1646 else:
1592 1647 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1593 1648 if self.InteractiveTB.call_pdb and self.has_readline:
1594 1649 # pdb mucks up readline, fix it back
1595 1650 self.set_completer()
1596 1651 except KeyboardInterrupt:
1597 1652 self.write("\nKeyboardInterrupt\n")
1598 1653
1599 1654 def mainloop(self,banner=None):
1600 1655 """Creates the local namespace and starts the mainloop.
1601 1656
1602 1657 If an optional banner argument is given, it will override the
1603 1658 internally created default banner."""
1604 1659
1605 1660 if self.rc.c: # Emulate Python's -c option
1606 1661 self.exec_init_cmd()
1607 1662 if banner is None:
1608 1663 if not self.rc.banner:
1609 1664 banner = ''
1610 1665 # banner is string? Use it directly!
1611 1666 elif isinstance(self.rc.banner,basestring):
1612 1667 banner = self.rc.banner
1613 1668 else:
1614 1669 banner = self.BANNER+self.banner2
1615 1670
1616 1671 while 1:
1617 1672 try:
1618 1673 self.interact(banner)
1619 1674 #self.interact_with_readline()
1620 1675
1621 1676 # XXX for testing of a readline-decoupled repl loop, call
1622 1677 # interact_with_readline above
1623 1678
1624 1679 break
1625 1680 except KeyboardInterrupt:
1626 1681 # this should not be necessary, but KeyboardInterrupt
1627 1682 # handling seems rather unpredictable...
1628 1683 self.write("\nKeyboardInterrupt in interact()\n")
1629 1684
1630 1685 def exec_init_cmd(self):
1631 1686 """Execute a command given at the command line.
1632 1687
1633 1688 This emulates Python's -c option."""
1634 1689
1635 1690 #sys.argv = ['-c']
1636 1691 self.push(self.prefilter(self.rc.c, False))
1637 1692 if not self.rc.interact:
1638 1693 self.ask_exit()
1639 1694
1640 1695 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1641 1696 """Embeds IPython into a running python program.
1642 1697
1643 1698 Input:
1644 1699
1645 1700 - header: An optional header message can be specified.
1646 1701
1647 1702 - local_ns, global_ns: working namespaces. If given as None, the
1648 1703 IPython-initialized one is updated with __main__.__dict__, so that
1649 1704 program variables become visible but user-specific configuration
1650 1705 remains possible.
1651 1706
1652 1707 - stack_depth: specifies how many levels in the stack to go to
1653 1708 looking for namespaces (when local_ns and global_ns are None). This
1654 1709 allows an intermediate caller to make sure that this function gets
1655 1710 the namespace from the intended level in the stack. By default (0)
1656 1711 it will get its locals and globals from the immediate caller.
1657 1712
1658 1713 Warning: it's possible to use this in a program which is being run by
1659 1714 IPython itself (via %run), but some funny things will happen (a few
1660 1715 globals get overwritten). In the future this will be cleaned up, as
1661 1716 there is no fundamental reason why it can't work perfectly."""
1662 1717
1663 1718 # Get locals and globals from caller
1664 1719 if local_ns is None or global_ns is None:
1665 1720 call_frame = sys._getframe(stack_depth).f_back
1666 1721
1667 1722 if local_ns is None:
1668 1723 local_ns = call_frame.f_locals
1669 1724 if global_ns is None:
1670 1725 global_ns = call_frame.f_globals
1671 1726
1672 1727 # Update namespaces and fire up interpreter
1673 1728
1674 1729 # The global one is easy, we can just throw it in
1675 1730 self.user_global_ns = global_ns
1676 1731
1677 1732 # but the user/local one is tricky: ipython needs it to store internal
1678 1733 # data, but we also need the locals. We'll copy locals in the user
1679 1734 # one, but will track what got copied so we can delete them at exit.
1680 1735 # This is so that a later embedded call doesn't see locals from a
1681 1736 # previous call (which most likely existed in a separate scope).
1682 1737 local_varnames = local_ns.keys()
1683 1738 self.user_ns.update(local_ns)
1684 1739 #self.user_ns['local_ns'] = local_ns # dbg
1685 1740
1686 1741 # Patch for global embedding to make sure that things don't overwrite
1687 1742 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1688 1743 # FIXME. Test this a bit more carefully (the if.. is new)
1689 1744 if local_ns is None and global_ns is None:
1690 1745 self.user_global_ns.update(__main__.__dict__)
1691 1746
1692 1747 # make sure the tab-completer has the correct frame information, so it
1693 1748 # actually completes using the frame's locals/globals
1694 1749 self.set_completer_frame()
1695 1750
1696 1751 # before activating the interactive mode, we need to make sure that
1697 1752 # all names in the builtin namespace needed by ipython point to
1698 1753 # ourselves, and not to other instances.
1699 1754 self.add_builtins()
1700 1755
1701 1756 self.interact(header)
1702 1757
1703 1758 # now, purge out the user namespace from anything we might have added
1704 1759 # from the caller's local namespace
1705 1760 delvar = self.user_ns.pop
1706 1761 for var in local_varnames:
1707 1762 delvar(var,None)
1708 1763 # and clean builtins we may have overridden
1709 1764 self.clean_builtins()
1710 1765
1711 1766 def interact_prompt(self):
1712 1767 """ Print the prompt (in read-eval-print loop)
1713 1768
1714 1769 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1715 1770 used in standard IPython flow.
1716 1771 """
1717 1772 if self.more:
1718 1773 try:
1719 1774 prompt = self.hooks.generate_prompt(True)
1720 1775 except:
1721 1776 self.showtraceback()
1722 1777 if self.autoindent:
1723 1778 self.rl_do_indent = True
1724 1779
1725 1780 else:
1726 1781 try:
1727 1782 prompt = self.hooks.generate_prompt(False)
1728 1783 except:
1729 1784 self.showtraceback()
1730 1785 self.write(prompt)
1731 1786
1732 1787 def interact_handle_input(self,line):
1733 1788 """ Handle the input line (in read-eval-print loop)
1734 1789
1735 1790 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1736 1791 used in standard IPython flow.
1737 1792 """
1738 1793 if line.lstrip() == line:
1739 1794 self.shadowhist.add(line.strip())
1740 1795 lineout = self.prefilter(line,self.more)
1741 1796
1742 1797 if line.strip():
1743 1798 if self.more:
1744 1799 self.input_hist_raw[-1] += '%s\n' % line
1745 1800 else:
1746 1801 self.input_hist_raw.append('%s\n' % line)
1747 1802
1748 1803
1749 1804 self.more = self.push(lineout)
1750 1805 if (self.SyntaxTB.last_syntax_error and
1751 1806 self.rc.autoedit_syntax):
1752 1807 self.edit_syntax_error()
1753 1808
1754 1809 def interact_with_readline(self):
1755 1810 """ Demo of using interact_handle_input, interact_prompt
1756 1811
1757 1812 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1758 1813 it should work like this.
1759 1814 """
1760 1815 self.readline_startup_hook(self.pre_readline)
1761 1816 while not self.exit_now:
1762 1817 self.interact_prompt()
1763 1818 if self.more:
1764 1819 self.rl_do_indent = True
1765 1820 else:
1766 1821 self.rl_do_indent = False
1767 1822 line = raw_input_original().decode(self.stdin_encoding)
1768 1823 self.interact_handle_input(line)
1769 1824
1770 1825
1771 1826 def interact(self, banner=None):
1772 1827 """Closely emulate the interactive Python console.
1773 1828
1774 1829 The optional banner argument specify the banner to print
1775 1830 before the first interaction; by default it prints a banner
1776 1831 similar to the one printed by the real Python interpreter,
1777 1832 followed by the current class name in parentheses (so as not
1778 1833 to confuse this with the real interpreter -- since it's so
1779 1834 close!).
1780 1835
1781 1836 """
1782 1837
1783 1838 if self.exit_now:
1784 1839 # batch run -> do not interact
1785 1840 return
1786 1841 cprt = 'Type "copyright", "credits" or "license" for more information.'
1787 1842 if banner is None:
1788 1843 self.write("Python %s on %s\n%s\n(%s)\n" %
1789 1844 (sys.version, sys.platform, cprt,
1790 1845 self.__class__.__name__))
1791 1846 else:
1792 1847 self.write(banner)
1793 1848
1794 1849 more = 0
1795 1850
1796 1851 # Mark activity in the builtins
1797 1852 __builtin__.__dict__['__IPYTHON__active'] += 1
1798 1853
1799 1854 if self.has_readline:
1800 1855 self.readline_startup_hook(self.pre_readline)
1801 1856 # exit_now is set by a call to %Exit or %Quit, through the
1802 1857 # ask_exit callback.
1803 1858
1804 1859 while not self.exit_now:
1805 1860 self.hooks.pre_prompt_hook()
1806 1861 if more:
1807 1862 try:
1808 1863 prompt = self.hooks.generate_prompt(True)
1809 1864 except:
1810 1865 self.showtraceback()
1811 1866 if self.autoindent:
1812 1867 self.rl_do_indent = True
1813 1868
1814 1869 else:
1815 1870 try:
1816 1871 prompt = self.hooks.generate_prompt(False)
1817 1872 except:
1818 1873 self.showtraceback()
1819 1874 try:
1820 1875 line = self.raw_input(prompt,more)
1821 1876 if self.exit_now:
1822 1877 # quick exit on sys.std[in|out] close
1823 1878 break
1824 1879 if self.autoindent:
1825 1880 self.rl_do_indent = False
1826 1881
1827 1882 except KeyboardInterrupt:
1828 1883 #double-guard against keyboardinterrupts during kbdint handling
1829 1884 try:
1830 1885 self.write('\nKeyboardInterrupt\n')
1831 1886 self.resetbuffer()
1832 1887 # keep cache in sync with the prompt counter:
1833 1888 self.outputcache.prompt_count -= 1
1834 1889
1835 1890 if self.autoindent:
1836 1891 self.indent_current_nsp = 0
1837 1892 more = 0
1838 1893 except KeyboardInterrupt:
1839 1894 pass
1840 1895 except EOFError:
1841 1896 if self.autoindent:
1842 1897 self.rl_do_indent = False
1843 1898 self.readline_startup_hook(None)
1844 1899 self.write('\n')
1845 1900 self.exit()
1846 1901 except bdb.BdbQuit:
1847 1902 warn('The Python debugger has exited with a BdbQuit exception.\n'
1848 1903 'Because of how pdb handles the stack, it is impossible\n'
1849 1904 'for IPython to properly format this particular exception.\n'
1850 1905 'IPython will resume normal operation.')
1851 1906 except:
1852 1907 # exceptions here are VERY RARE, but they can be triggered
1853 1908 # asynchronously by signal handlers, for example.
1854 1909 self.showtraceback()
1855 1910 else:
1856 1911 more = self.push(line)
1857 1912 if (self.SyntaxTB.last_syntax_error and
1858 1913 self.rc.autoedit_syntax):
1859 1914 self.edit_syntax_error()
1860 1915
1861 1916 # We are off again...
1862 1917 __builtin__.__dict__['__IPYTHON__active'] -= 1
1863 1918
1864 1919 def excepthook(self, etype, value, tb):
1865 1920 """One more defense for GUI apps that call sys.excepthook.
1866 1921
1867 1922 GUI frameworks like wxPython trap exceptions and call
1868 1923 sys.excepthook themselves. I guess this is a feature that
1869 1924 enables them to keep running after exceptions that would
1870 1925 otherwise kill their mainloop. This is a bother for IPython
1871 1926 which excepts to catch all of the program exceptions with a try:
1872 1927 except: statement.
1873 1928
1874 1929 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1875 1930 any app directly invokes sys.excepthook, it will look to the user like
1876 1931 IPython crashed. In order to work around this, we can disable the
1877 1932 CrashHandler and replace it with this excepthook instead, which prints a
1878 1933 regular traceback using our InteractiveTB. In this fashion, apps which
1879 1934 call sys.excepthook will generate a regular-looking exception from
1880 1935 IPython, and the CrashHandler will only be triggered by real IPython
1881 1936 crashes.
1882 1937
1883 1938 This hook should be used sparingly, only in places which are not likely
1884 1939 to be true IPython errors.
1885 1940 """
1886 1941 self.showtraceback((etype,value,tb),tb_offset=0)
1887 1942
1888 1943 def expand_aliases(self,fn,rest):
1889 1944 """ Expand multiple levels of aliases:
1890 1945
1891 1946 if:
1892 1947
1893 1948 alias foo bar /tmp
1894 1949 alias baz foo
1895 1950
1896 1951 then:
1897 1952
1898 1953 baz huhhahhei -> bar /tmp huhhahhei
1899 1954
1900 1955 """
1901 1956 line = fn + " " + rest
1902 1957
1903 1958 done = Set()
1904 1959 while 1:
1905 1960 pre,fn,rest = prefilter.splitUserInput(line,
1906 1961 prefilter.shell_line_split)
1907 1962 if fn in self.alias_table:
1908 1963 if fn in done:
1909 1964 warn("Cyclic alias definition, repeated '%s'" % fn)
1910 1965 return ""
1911 1966 done.add(fn)
1912 1967
1913 1968 l2 = self.transform_alias(fn,rest)
1914 1969 # dir -> dir
1915 1970 # print "alias",line, "->",l2 #dbg
1916 1971 if l2 == line:
1917 1972 break
1918 1973 # ls -> ls -F should not recurse forever
1919 1974 if l2.split(None,1)[0] == line.split(None,1)[0]:
1920 1975 line = l2
1921 1976 break
1922 1977
1923 1978 line=l2
1924 1979
1925 1980
1926 1981 # print "al expand to",line #dbg
1927 1982 else:
1928 1983 break
1929 1984
1930 1985 return line
1931 1986
1932 1987 def transform_alias(self, alias,rest=''):
1933 1988 """ Transform alias to system command string.
1934 1989 """
1935 1990 trg = self.alias_table[alias]
1936 1991
1937 1992 nargs,cmd = trg
1938 1993 # print trg #dbg
1939 1994 if ' ' in cmd and os.path.isfile(cmd):
1940 1995 cmd = '"%s"' % cmd
1941 1996
1942 1997 # Expand the %l special to be the user's input line
1943 1998 if cmd.find('%l') >= 0:
1944 1999 cmd = cmd.replace('%l',rest)
1945 2000 rest = ''
1946 2001 if nargs==0:
1947 2002 # Simple, argument-less aliases
1948 2003 cmd = '%s %s' % (cmd,rest)
1949 2004 else:
1950 2005 # Handle aliases with positional arguments
1951 2006 args = rest.split(None,nargs)
1952 2007 if len(args)< nargs:
1953 2008 error('Alias <%s> requires %s arguments, %s given.' %
1954 2009 (alias,nargs,len(args)))
1955 2010 return None
1956 2011 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1957 2012 # Now call the macro, evaluating in the user's namespace
1958 2013 #print 'new command: <%r>' % cmd # dbg
1959 2014 return cmd
1960 2015
1961 2016 def call_alias(self,alias,rest=''):
1962 2017 """Call an alias given its name and the rest of the line.
1963 2018
1964 2019 This is only used to provide backwards compatibility for users of
1965 2020 ipalias(), use of which is not recommended for anymore."""
1966 2021
1967 2022 # Now call the macro, evaluating in the user's namespace
1968 2023 cmd = self.transform_alias(alias, rest)
1969 2024 try:
1970 2025 self.system(cmd)
1971 2026 except:
1972 2027 self.showtraceback()
1973 2028
1974 2029 def indent_current_str(self):
1975 2030 """return the current level of indentation as a string"""
1976 2031 return self.indent_current_nsp * ' '
1977 2032
1978 2033 def autoindent_update(self,line):
1979 2034 """Keep track of the indent level."""
1980 2035
1981 2036 #debugx('line')
1982 2037 #debugx('self.indent_current_nsp')
1983 2038 if self.autoindent:
1984 2039 if line:
1985 2040 inisp = num_ini_spaces(line)
1986 2041 if inisp < self.indent_current_nsp:
1987 2042 self.indent_current_nsp = inisp
1988 2043
1989 2044 if line[-1] == ':':
1990 2045 self.indent_current_nsp += 4
1991 2046 elif dedent_re.match(line):
1992 2047 self.indent_current_nsp -= 4
1993 2048 else:
1994 2049 self.indent_current_nsp = 0
1995 2050
1996 2051 def runlines(self,lines):
1997 2052 """Run a string of one or more lines of source.
1998 2053
1999 2054 This method is capable of running a string containing multiple source
2000 2055 lines, as if they had been entered at the IPython prompt. Since it
2001 2056 exposes IPython's processing machinery, the given strings can contain
2002 2057 magic calls (%magic), special shell access (!cmd), etc."""
2003 2058
2004 2059 # We must start with a clean buffer, in case this is run from an
2005 2060 # interactive IPython session (via a magic, for example).
2006 2061 self.resetbuffer()
2007 2062 lines = lines.split('\n')
2008 2063 more = 0
2009 2064
2010 2065 for line in lines:
2011 2066 # skip blank lines so we don't mess up the prompt counter, but do
2012 2067 # NOT skip even a blank line if we are in a code block (more is
2013 2068 # true)
2014 2069
2015
2016 2070 if line or more:
2017 2071 # push to raw history, so hist line numbers stay in sync
2018 2072 self.input_hist_raw.append("# " + line + "\n")
2019 2073 more = self.push(self.prefilter(line,more))
2020 2074 # IPython's runsource returns None if there was an error
2021 2075 # compiling the code. This allows us to stop processing right
2022 2076 # away, so the user gets the error message at the right place.
2023 2077 if more is None:
2024 2078 break
2025 2079 else:
2026 2080 self.input_hist_raw.append("\n")
2027 2081 # final newline in case the input didn't have it, so that the code
2028 2082 # actually does get executed
2029 2083 if more:
2030 2084 self.push('\n')
2031 2085
2032 2086 def runsource(self, source, filename='<input>', symbol='single'):
2033 2087 """Compile and run some source in the interpreter.
2034 2088
2035 2089 Arguments are as for compile_command().
2036 2090
2037 2091 One several things can happen:
2038 2092
2039 2093 1) The input is incorrect; compile_command() raised an
2040 2094 exception (SyntaxError or OverflowError). A syntax traceback
2041 2095 will be printed by calling the showsyntaxerror() method.
2042 2096
2043 2097 2) The input is incomplete, and more input is required;
2044 2098 compile_command() returned None. Nothing happens.
2045 2099
2046 2100 3) The input is complete; compile_command() returned a code
2047 2101 object. The code is executed by calling self.runcode() (which
2048 2102 also handles run-time exceptions, except for SystemExit).
2049 2103
2050 2104 The return value is:
2051 2105
2052 2106 - True in case 2
2053 2107
2054 2108 - False in the other cases, unless an exception is raised, where
2055 2109 None is returned instead. This can be used by external callers to
2056 2110 know whether to continue feeding input or not.
2057 2111
2058 2112 The return value can be used to decide whether to use sys.ps1 or
2059 2113 sys.ps2 to prompt the next line."""
2060 2114
2061 2115 # if the source code has leading blanks, add 'if 1:\n' to it
2062 2116 # this allows execution of indented pasted code. It is tempting
2063 2117 # to add '\n' at the end of source to run commands like ' a=1'
2064 2118 # directly, but this fails for more complicated scenarios
2065 2119 source=source.encode(self.stdin_encoding)
2066 2120 if source[:1] in [' ', '\t']:
2067 2121 source = 'if 1:\n%s' % source
2068 2122
2069 2123 try:
2070 2124 code = self.compile(source,filename,symbol)
2071 2125 except (OverflowError, SyntaxError, ValueError, TypeError):
2072 2126 # Case 1
2073 2127 self.showsyntaxerror(filename)
2074 2128 return None
2075 2129
2076 2130 if code is None:
2077 2131 # Case 2
2078 2132 return True
2079 2133
2080 2134 # Case 3
2081 2135 # We store the code object so that threaded shells and
2082 2136 # custom exception handlers can access all this info if needed.
2083 2137 # The source corresponding to this can be obtained from the
2084 2138 # buffer attribute as '\n'.join(self.buffer).
2085 2139 self.code_to_run = code
2086 2140 # now actually execute the code object
2087 2141 if self.runcode(code) == 0:
2088 2142 return False
2089 2143 else:
2090 2144 return None
2091 2145
2092 2146 def runcode(self,code_obj):
2093 2147 """Execute a code object.
2094 2148
2095 2149 When an exception occurs, self.showtraceback() is called to display a
2096 2150 traceback.
2097 2151
2098 2152 Return value: a flag indicating whether the code to be run completed
2099 2153 successfully:
2100 2154
2101 2155 - 0: successful execution.
2102 2156 - 1: an error occurred.
2103 2157 """
2104 2158
2105 2159 # Set our own excepthook in case the user code tries to call it
2106 2160 # directly, so that the IPython crash handler doesn't get triggered
2107 2161 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2108 2162
2109 2163 # we save the original sys.excepthook in the instance, in case config
2110 2164 # code (such as magics) needs access to it.
2111 2165 self.sys_excepthook = old_excepthook
2112 2166 outflag = 1 # happens in more places, so it's easier as default
2113 2167 try:
2114 2168 try:
2115 2169 self.hooks.pre_runcode_hook()
2116 2170 exec code_obj in self.user_global_ns, self.user_ns
2117 2171 finally:
2118 2172 # Reset our crash handler in place
2119 2173 sys.excepthook = old_excepthook
2120 2174 except SystemExit:
2121 2175 self.resetbuffer()
2122 2176 self.showtraceback()
2123 2177 warn("Type %exit or %quit to exit IPython "
2124 2178 "(%Exit or %Quit do so unconditionally).",level=1)
2125 2179 except self.custom_exceptions:
2126 2180 etype,value,tb = sys.exc_info()
2127 2181 self.CustomTB(etype,value,tb)
2128 2182 except:
2129 2183 self.showtraceback()
2130 2184 else:
2131 2185 outflag = 0
2132 2186 if softspace(sys.stdout, 0):
2133 2187 print
2134 2188 # Flush out code object which has been run (and source)
2135 2189 self.code_to_run = None
2136 2190 return outflag
2137 2191
2138 2192 def push(self, line):
2139 2193 """Push a line to the interpreter.
2140 2194
2141 2195 The line should not have a trailing newline; it may have
2142 2196 internal newlines. The line is appended to a buffer and the
2143 2197 interpreter's runsource() method is called with the
2144 2198 concatenated contents of the buffer as source. If this
2145 2199 indicates that the command was executed or invalid, the buffer
2146 2200 is reset; otherwise, the command is incomplete, and the buffer
2147 2201 is left as it was after the line was appended. The return
2148 2202 value is 1 if more input is required, 0 if the line was dealt
2149 2203 with in some way (this is the same as runsource()).
2150 2204 """
2151 2205
2152 2206 # autoindent management should be done here, and not in the
2153 2207 # interactive loop, since that one is only seen by keyboard input. We
2154 2208 # need this done correctly even for code run via runlines (which uses
2155 2209 # push).
2156 2210
2157 2211 #print 'push line: <%s>' % line # dbg
2158 2212 for subline in line.splitlines():
2159 2213 self.autoindent_update(subline)
2160 2214 self.buffer.append(line)
2161 2215 more = self.runsource('\n'.join(self.buffer), self.filename)
2162 2216 if not more:
2163 2217 self.resetbuffer()
2164 2218 return more
2165 2219
2166 2220 def split_user_input(self, line):
2167 2221 # This is really a hold-over to support ipapi and some extensions
2168 2222 return prefilter.splitUserInput(line)
2169 2223
2170 2224 def resetbuffer(self):
2171 2225 """Reset the input buffer."""
2172 2226 self.buffer[:] = []
2173 2227
2174 2228 def raw_input(self,prompt='',continue_prompt=False):
2175 2229 """Write a prompt and read a line.
2176 2230
2177 2231 The returned line does not include the trailing newline.
2178 2232 When the user enters the EOF key sequence, EOFError is raised.
2179 2233
2180 2234 Optional inputs:
2181 2235
2182 2236 - prompt(''): a string to be printed to prompt the user.
2183 2237
2184 2238 - continue_prompt(False): whether this line is the first one or a
2185 2239 continuation in a sequence of inputs.
2186 2240 """
2187 2241
2188 2242 # Code run by the user may have modified the readline completer state.
2189 2243 # We must ensure that our completer is back in place.
2190 2244 if self.has_readline:
2191 2245 self.set_completer()
2192 2246
2193 2247 try:
2194 2248 line = raw_input_original(prompt).decode(self.stdin_encoding)
2195 2249 except ValueError:
2196 2250 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2197 2251 " or sys.stdout.close()!\nExiting IPython!")
2198 2252 self.ask_exit()
2199 2253 return ""
2200 2254
2201 2255 # Try to be reasonably smart about not re-indenting pasted input more
2202 2256 # than necessary. We do this by trimming out the auto-indent initial
2203 2257 # spaces, if the user's actual input started itself with whitespace.
2204 2258 #debugx('self.buffer[-1]')
2205 2259
2206 2260 if self.autoindent:
2207 2261 if num_ini_spaces(line) > self.indent_current_nsp:
2208 2262 line = line[self.indent_current_nsp:]
2209 2263 self.indent_current_nsp = 0
2210 2264
2211 2265 # store the unfiltered input before the user has any chance to modify
2212 2266 # it.
2213 2267 if line.strip():
2214 2268 if continue_prompt:
2215 2269 self.input_hist_raw[-1] += '%s\n' % line
2216 2270 if self.has_readline: # and some config option is set?
2217 2271 try:
2218 2272 histlen = self.readline.get_current_history_length()
2219 2273 if histlen > 1:
2220 2274 newhist = self.input_hist_raw[-1].rstrip()
2221 2275 self.readline.remove_history_item(histlen-1)
2222 2276 self.readline.replace_history_item(histlen-2,
2223 2277 newhist.encode(self.stdin_encoding))
2224 2278 except AttributeError:
2225 2279 pass # re{move,place}_history_item are new in 2.4.
2226 2280 else:
2227 2281 self.input_hist_raw.append('%s\n' % line)
2228 2282 # only entries starting at first column go to shadow history
2229 2283 if line.lstrip() == line:
2230 2284 self.shadowhist.add(line.strip())
2231 2285 elif not continue_prompt:
2232 2286 self.input_hist_raw.append('\n')
2233 2287 try:
2234 2288 lineout = self.prefilter(line,continue_prompt)
2235 2289 except:
2236 2290 # blanket except, in case a user-defined prefilter crashes, so it
2237 2291 # can't take all of ipython with it.
2238 2292 self.showtraceback()
2239 2293 return ''
2240 2294 else:
2241 2295 return lineout
2242 2296
2243 2297 def _prefilter(self, line, continue_prompt):
2244 2298 """Calls different preprocessors, depending on the form of line."""
2245 2299
2246 2300 # All handlers *must* return a value, even if it's blank ('').
2247 2301
2248 2302 # Lines are NOT logged here. Handlers should process the line as
2249 2303 # needed, update the cache AND log it (so that the input cache array
2250 2304 # stays synced).
2251 2305
2252 2306 #.....................................................................
2253 2307 # Code begins
2254 2308
2255 2309 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2256 2310
2257 2311 # save the line away in case we crash, so the post-mortem handler can
2258 2312 # record it
2259 2313 self._last_input_line = line
2260 2314
2261 2315 #print '***line: <%s>' % line # dbg
2262 2316
2263 2317 if not line:
2264 2318 # Return immediately on purely empty lines, so that if the user
2265 2319 # previously typed some whitespace that started a continuation
2266 2320 # prompt, he can break out of that loop with just an empty line.
2267 2321 # This is how the default python prompt works.
2268 2322
2269 2323 # Only return if the accumulated input buffer was just whitespace!
2270 2324 if ''.join(self.buffer).isspace():
2271 2325 self.buffer[:] = []
2272 2326 return ''
2273 2327
2274 2328 line_info = prefilter.LineInfo(line, continue_prompt)
2275 2329
2276 2330 # the input history needs to track even empty lines
2277 2331 stripped = line.strip()
2278 2332
2279 2333 if not stripped:
2280 2334 if not continue_prompt:
2281 2335 self.outputcache.prompt_count -= 1
2282 2336 return self.handle_normal(line_info)
2283 2337
2284 2338 # print '***cont',continue_prompt # dbg
2285 2339 # special handlers are only allowed for single line statements
2286 2340 if continue_prompt and not self.rc.multi_line_specials:
2287 2341 return self.handle_normal(line_info)
2288 2342
2289 2343
2290 2344 # See whether any pre-existing handler can take care of it
2291 2345 rewritten = self.hooks.input_prefilter(stripped)
2292 2346 if rewritten != stripped: # ok, some prefilter did something
2293 2347 rewritten = line_info.pre + rewritten # add indentation
2294 2348 return self.handle_normal(prefilter.LineInfo(rewritten,
2295 2349 continue_prompt))
2296 2350
2297 2351 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2298 2352
2299 2353 return prefilter.prefilter(line_info, self)
2300 2354
2301 2355
2302 2356 def _prefilter_dumb(self, line, continue_prompt):
2303 2357 """simple prefilter function, for debugging"""
2304 2358 return self.handle_normal(line,continue_prompt)
2305 2359
2306 2360
2307 2361 def multiline_prefilter(self, line, continue_prompt):
2308 2362 """ Run _prefilter for each line of input
2309 2363
2310 2364 Covers cases where there are multiple lines in the user entry,
2311 2365 which is the case when the user goes back to a multiline history
2312 2366 entry and presses enter.
2313 2367
2314 2368 """
2315 2369 out = []
2316 2370 for l in line.rstrip('\n').split('\n'):
2317 2371 out.append(self._prefilter(l, continue_prompt))
2318 2372 return '\n'.join(out)
2319 2373
2320 2374 # Set the default prefilter() function (this can be user-overridden)
2321 2375 prefilter = multiline_prefilter
2322 2376
2323 2377 def handle_normal(self,line_info):
2324 2378 """Handle normal input lines. Use as a template for handlers."""
2325 2379
2326 2380 # With autoindent on, we need some way to exit the input loop, and I
2327 2381 # don't want to force the user to have to backspace all the way to
2328 2382 # clear the line. The rule will be in this case, that either two
2329 2383 # lines of pure whitespace in a row, or a line of pure whitespace but
2330 2384 # of a size different to the indent level, will exit the input loop.
2331 2385 line = line_info.line
2332 2386 continue_prompt = line_info.continue_prompt
2333 2387
2334 2388 if (continue_prompt and self.autoindent and line.isspace() and
2335 2389 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2336 2390 (self.buffer[-1]).isspace() )):
2337 2391 line = ''
2338 2392
2339 2393 self.log(line,line,continue_prompt)
2340 2394 return line
2341 2395
2342 2396 def handle_alias(self,line_info):
2343 2397 """Handle alias input lines. """
2344 2398 tgt = self.alias_table[line_info.iFun]
2345 2399 # print "=>",tgt #dbg
2346 2400 if callable(tgt):
2347 2401 if '$' in line_info.line:
2348 2402 call_meth = '(_ip, _ip.itpl(%s))'
2349 2403 else:
2350 2404 call_meth = '(_ip,%s)'
2351 2405 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2352 2406 line_info.iFun,
2353 2407 make_quoted_expr(line_info.line))
2354 2408 else:
2355 2409 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2356 2410
2357 2411 # pre is needed, because it carries the leading whitespace. Otherwise
2358 2412 # aliases won't work in indented sections.
2359 2413 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2360 2414 make_quoted_expr( transformed ))
2361 2415
2362 2416 self.log(line_info.line,line_out,line_info.continue_prompt)
2363 2417 #print 'line out:',line_out # dbg
2364 2418 return line_out
2365 2419
2366 2420 def handle_shell_escape(self, line_info):
2367 2421 """Execute the line in a shell, empty return value"""
2368 2422 #print 'line in :', `line` # dbg
2369 2423 line = line_info.line
2370 2424 if line.lstrip().startswith('!!'):
2371 2425 # rewrite LineInfo's line, iFun and theRest to properly hold the
2372 2426 # call to %sx and the actual command to be executed, so
2373 2427 # handle_magic can work correctly. Note that this works even if
2374 2428 # the line is indented, so it handles multi_line_specials
2375 2429 # properly.
2376 2430 new_rest = line.lstrip()[2:]
2377 2431 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2378 2432 line_info.iFun = 'sx'
2379 2433 line_info.theRest = new_rest
2380 2434 return self.handle_magic(line_info)
2381 2435 else:
2382 2436 cmd = line.lstrip().lstrip('!')
2383 2437 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2384 2438 make_quoted_expr(cmd))
2385 2439 # update cache/log and return
2386 2440 self.log(line,line_out,line_info.continue_prompt)
2387 2441 return line_out
2388 2442
2389 2443 def handle_magic(self, line_info):
2390 2444 """Execute magic functions."""
2391 2445 iFun = line_info.iFun
2392 2446 theRest = line_info.theRest
2393 2447 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2394 2448 make_quoted_expr(iFun + " " + theRest))
2395 2449 self.log(line_info.line,cmd,line_info.continue_prompt)
2396 2450 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2397 2451 return cmd
2398 2452
2399 2453 def handle_auto(self, line_info):
2400 2454 """Hande lines which can be auto-executed, quoting if requested."""
2401 2455
2402 2456 line = line_info.line
2403 2457 iFun = line_info.iFun
2404 2458 theRest = line_info.theRest
2405 2459 pre = line_info.pre
2406 2460 continue_prompt = line_info.continue_prompt
2407 2461 obj = line_info.ofind(self)['obj']
2408 2462
2409 2463 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2410 2464
2411 2465 # This should only be active for single-line input!
2412 2466 if continue_prompt:
2413 2467 self.log(line,line,continue_prompt)
2414 2468 return line
2415 2469
2416 2470 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2417 2471 auto_rewrite = True
2418 2472
2419 2473 if pre == self.ESC_QUOTE:
2420 2474 # Auto-quote splitting on whitespace
2421 2475 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2422 2476 elif pre == self.ESC_QUOTE2:
2423 2477 # Auto-quote whole string
2424 2478 newcmd = '%s("%s")' % (iFun,theRest)
2425 2479 elif pre == self.ESC_PAREN:
2426 2480 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2427 2481 else:
2428 2482 # Auto-paren.
2429 2483 # We only apply it to argument-less calls if the autocall
2430 2484 # parameter is set to 2. We only need to check that autocall is <
2431 2485 # 2, since this function isn't called unless it's at least 1.
2432 2486 if not theRest and (self.rc.autocall < 2) and not force_auto:
2433 2487 newcmd = '%s %s' % (iFun,theRest)
2434 2488 auto_rewrite = False
2435 2489 else:
2436 2490 if not force_auto and theRest.startswith('['):
2437 2491 if hasattr(obj,'__getitem__'):
2438 2492 # Don't autocall in this case: item access for an object
2439 2493 # which is BOTH callable and implements __getitem__.
2440 2494 newcmd = '%s %s' % (iFun,theRest)
2441 2495 auto_rewrite = False
2442 2496 else:
2443 2497 # if the object doesn't support [] access, go ahead and
2444 2498 # autocall
2445 2499 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2446 2500 elif theRest.endswith(';'):
2447 2501 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2448 2502 else:
2449 2503 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2450 2504
2451 2505 if auto_rewrite:
2452 2506 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2453 2507
2454 2508 try:
2455 2509 # plain ascii works better w/ pyreadline, on some machines, so
2456 2510 # we use it and only print uncolored rewrite if we have unicode
2457 2511 rw = str(rw)
2458 2512 print >>Term.cout, rw
2459 2513 except UnicodeEncodeError:
2460 2514 print "-------------->" + newcmd
2461 2515
2462 2516 # log what is now valid Python, not the actual user input (without the
2463 2517 # final newline)
2464 2518 self.log(line,newcmd,continue_prompt)
2465 2519 return newcmd
2466 2520
2467 2521 def handle_help(self, line_info):
2468 2522 """Try to get some help for the object.
2469 2523
2470 2524 obj? or ?obj -> basic information.
2471 2525 obj?? or ??obj -> more details.
2472 2526 """
2473 2527
2474 2528 line = line_info.line
2475 2529 # We need to make sure that we don't process lines which would be
2476 2530 # otherwise valid python, such as "x=1 # what?"
2477 2531 try:
2478 2532 codeop.compile_command(line)
2479 2533 except SyntaxError:
2480 2534 # We should only handle as help stuff which is NOT valid syntax
2481 2535 if line[0]==self.ESC_HELP:
2482 2536 line = line[1:]
2483 2537 elif line[-1]==self.ESC_HELP:
2484 2538 line = line[:-1]
2485 2539 self.log(line,'#?'+line,line_info.continue_prompt)
2486 2540 if line:
2487 2541 #print 'line:<%r>' % line # dbg
2488 2542 self.magic_pinfo(line)
2489 2543 else:
2490 2544 page(self.usage,screen_lines=self.rc.screen_length)
2491 2545 return '' # Empty string is needed here!
2492 2546 except:
2493 2547 # Pass any other exceptions through to the normal handler
2494 2548 return self.handle_normal(line_info)
2495 2549 else:
2496 2550 # If the code compiles ok, we should handle it normally
2497 2551 return self.handle_normal(line_info)
2498 2552
2499 2553 def getapi(self):
2500 2554 """ Get an IPApi object for this shell instance
2501 2555
2502 2556 Getting an IPApi object is always preferable to accessing the shell
2503 2557 directly, but this holds true especially for extensions.
2504 2558
2505 2559 It should always be possible to implement an extension with IPApi
2506 2560 alone. If not, contact maintainer to request an addition.
2507 2561
2508 2562 """
2509 2563 return self.api
2510 2564
2511 2565 def handle_emacs(self, line_info):
2512 2566 """Handle input lines marked by python-mode."""
2513 2567
2514 2568 # Currently, nothing is done. Later more functionality can be added
2515 2569 # here if needed.
2516 2570
2517 2571 # The input cache shouldn't be updated
2518 2572 return line_info.line
2519 2573
2520 2574
2521 2575 def mktempfile(self,data=None):
2522 2576 """Make a new tempfile and return its filename.
2523 2577
2524 2578 This makes a call to tempfile.mktemp, but it registers the created
2525 2579 filename internally so ipython cleans it up at exit time.
2526 2580
2527 2581 Optional inputs:
2528 2582
2529 2583 - data(None): if data is given, it gets written out to the temp file
2530 2584 immediately, and the file is closed again."""
2531 2585
2532 2586 filename = tempfile.mktemp('.py','ipython_edit_')
2533 2587 self.tempfiles.append(filename)
2534 2588
2535 2589 if data:
2536 2590 tmp_file = open(filename,'w')
2537 2591 tmp_file.write(data)
2538 2592 tmp_file.close()
2539 2593 return filename
2540 2594
2541 2595 def write(self,data):
2542 2596 """Write a string to the default output"""
2543 2597 Term.cout.write(data)
2544 2598
2545 2599 def write_err(self,data):
2546 2600 """Write a string to the default error output"""
2547 2601 Term.cerr.write(data)
2548 2602
2549 2603 def ask_exit(self):
2550 2604 """ Call for exiting. Can be overiden and used as a callback. """
2551 2605 self.exit_now = True
2552 2606
2553 2607 def exit(self):
2554 2608 """Handle interactive exit.
2555 2609
2556 2610 This method calls the ask_exit callback."""
2557 2611
2558 2612 if self.rc.confirm_exit:
2559 2613 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2560 2614 self.ask_exit()
2561 2615 else:
2562 2616 self.ask_exit()
2563 2617
2564 2618 def safe_execfile(self,fname,*where,**kw):
2565 2619 """A safe version of the builtin execfile().
2566 2620
2567 2621 This version will never throw an exception, and knows how to handle
2568 2622 ipython logs as well.
2569 2623
2570 2624 :Parameters:
2571 2625 fname : string
2572 2626 Name of the file to be executed.
2573 2627
2574 2628 where : tuple
2575 2629 One or two namespaces, passed to execfile() as (globals,locals).
2576 2630 If only one is given, it is passed as both.
2577 2631
2578 2632 :Keywords:
2579 2633 islog : boolean (False)
2580 2634
2581 2635 quiet : boolean (True)
2582 2636
2583 2637 exit_ignore : boolean (False)
2584 2638 """
2585 2639
2586 2640 def syspath_cleanup():
2587 2641 """Internal cleanup routine for sys.path."""
2588 2642 if add_dname:
2589 2643 try:
2590 2644 sys.path.remove(dname)
2591 2645 except ValueError:
2592 2646 # For some reason the user has already removed it, ignore.
2593 2647 pass
2594 2648
2595 2649 fname = os.path.expanduser(fname)
2596 2650
2597 2651 # Find things also in current directory. This is needed to mimic the
2598 2652 # behavior of running a script from the system command line, where
2599 2653 # Python inserts the script's directory into sys.path
2600 2654 dname = os.path.dirname(os.path.abspath(fname))
2601 2655 add_dname = False
2602 2656 if dname not in sys.path:
2603 2657 sys.path.insert(0,dname)
2604 2658 add_dname = True
2605 2659
2606 2660 try:
2607 2661 xfile = open(fname)
2608 2662 except:
2609 2663 print >> Term.cerr, \
2610 2664 'Could not open file <%s> for safe execution.' % fname
2611 2665 syspath_cleanup()
2612 2666 return None
2613 2667
2614 2668 kw.setdefault('islog',0)
2615 2669 kw.setdefault('quiet',1)
2616 2670 kw.setdefault('exit_ignore',0)
2617 2671
2618 2672 first = xfile.readline()
2619 2673 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2620 2674 xfile.close()
2621 2675 # line by line execution
2622 2676 if first.startswith(loghead) or kw['islog']:
2623 2677 print 'Loading log file <%s> one line at a time...' % fname
2624 2678 if kw['quiet']:
2625 2679 stdout_save = sys.stdout
2626 2680 sys.stdout = StringIO.StringIO()
2627 2681 try:
2628 2682 globs,locs = where[0:2]
2629 2683 except:
2630 2684 try:
2631 2685 globs = locs = where[0]
2632 2686 except:
2633 2687 globs = locs = globals()
2634 2688 badblocks = []
2635 2689
2636 2690 # we also need to identify indented blocks of code when replaying
2637 2691 # logs and put them together before passing them to an exec
2638 2692 # statement. This takes a bit of regexp and look-ahead work in the
2639 2693 # file. It's easiest if we swallow the whole thing in memory
2640 2694 # first, and manually walk through the lines list moving the
2641 2695 # counter ourselves.
2642 2696 indent_re = re.compile('\s+\S')
2643 2697 xfile = open(fname)
2644 2698 filelines = xfile.readlines()
2645 2699 xfile.close()
2646 2700 nlines = len(filelines)
2647 2701 lnum = 0
2648 2702 while lnum < nlines:
2649 2703 line = filelines[lnum]
2650 2704 lnum += 1
2651 2705 # don't re-insert logger status info into cache
2652 2706 if line.startswith('#log#'):
2653 2707 continue
2654 2708 else:
2655 2709 # build a block of code (maybe a single line) for execution
2656 2710 block = line
2657 2711 try:
2658 2712 next = filelines[lnum] # lnum has already incremented
2659 2713 except:
2660 2714 next = None
2661 2715 while next and indent_re.match(next):
2662 2716 block += next
2663 2717 lnum += 1
2664 2718 try:
2665 2719 next = filelines[lnum]
2666 2720 except:
2667 2721 next = None
2668 2722 # now execute the block of one or more lines
2669 2723 try:
2670 2724 exec block in globs,locs
2671 2725 except SystemExit:
2672 2726 pass
2673 2727 except:
2674 2728 badblocks.append(block.rstrip())
2675 2729 if kw['quiet']: # restore stdout
2676 2730 sys.stdout.close()
2677 2731 sys.stdout = stdout_save
2678 2732 print 'Finished replaying log file <%s>' % fname
2679 2733 if badblocks:
2680 2734 print >> sys.stderr, ('\nThe following lines/blocks in file '
2681 2735 '<%s> reported errors:' % fname)
2682 2736
2683 2737 for badline in badblocks:
2684 2738 print >> sys.stderr, badline
2685 2739 else: # regular file execution
2686 2740 try:
2687 2741 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2688 2742 # Work around a bug in Python for Windows. The bug was
2689 2743 # fixed in in Python 2.5 r54159 and 54158, but that's still
2690 2744 # SVN Python as of March/07. For details, see:
2691 2745 # http://projects.scipy.org/ipython/ipython/ticket/123
2692 2746 try:
2693 2747 globs,locs = where[0:2]
2694 2748 except:
2695 2749 try:
2696 2750 globs = locs = where[0]
2697 2751 except:
2698 2752 globs = locs = globals()
2699 2753 exec file(fname) in globs,locs
2700 2754 else:
2701 2755 execfile(fname,*where)
2702 2756 except SyntaxError:
2703 2757 self.showsyntaxerror()
2704 2758 warn('Failure executing file: <%s>' % fname)
2705 2759 except SystemExit,status:
2706 2760 # Code that correctly sets the exit status flag to success (0)
2707 2761 # shouldn't be bothered with a traceback. Note that a plain
2708 2762 # sys.exit() does NOT set the message to 0 (it's empty) so that
2709 2763 # will still get a traceback. Note that the structure of the
2710 2764 # SystemExit exception changed between Python 2.4 and 2.5, so
2711 2765 # the checks must be done in a version-dependent way.
2712 2766 show = False
2713 2767
2714 2768 if sys.version_info[:2] > (2,5):
2715 2769 if status.message!=0 and not kw['exit_ignore']:
2716 2770 show = True
2717 2771 else:
2718 2772 if status.code and not kw['exit_ignore']:
2719 2773 show = True
2720 2774 if show:
2721 2775 self.showtraceback()
2722 2776 warn('Failure executing file: <%s>' % fname)
2723 2777 except:
2724 2778 self.showtraceback()
2725 2779 warn('Failure executing file: <%s>' % fname)
2726 2780
2727 2781 syspath_cleanup()
2728 2782
2729 2783 #************************* end of file <iplib.py> *****************************
@@ -1,782 +1,780 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 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>' % Release.authors['Fernando']
19 19 __license__ = Release.license
20 20 __version__ = Release.version
21 21
22 22 try:
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 except NameError:
35 35 # Can happen if ipython was started with 'python -S', so that site.py is
36 36 # not loaded
37 37 pass
38 38
39 39 #****************************************************************************
40 40 # Required modules
41 41
42 42 # From the standard library
43 43 import __main__
44 44 import __builtin__
45 45 import os
46 46 import re
47 47 import sys
48 48 import types
49 49 from pprint import pprint,pformat
50 50
51 51 # Our own
52 52 from IPython import DPyGetOpt
53 53 from IPython.ipstruct import Struct
54 54 from IPython.OutputTrap import OutputTrap
55 55 from IPython.ConfigLoader import ConfigLoader
56 56 from IPython.iplib import InteractiveShell
57 57 from IPython.usage import cmd_line_usage,interactive_usage
58 58 from IPython.genutils import *
59 59
60 60 def force_import(modname):
61 61 if modname in sys.modules:
62 62 print "reload",modname
63 63 reload(sys.modules[modname])
64 64 else:
65 65 __import__(modname)
66 66
67 67
68 68 #-----------------------------------------------------------------------------
69 69 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
70 70 rc_override=None,shell_class=InteractiveShell,
71 71 embedded=False,**kw):
72 72 """This is a dump of IPython into a single function.
73 73
74 74 Later it will have to be broken up in a sensible manner.
75 75
76 76 Arguments:
77 77
78 78 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
79 79 script name, b/c DPyGetOpt strips the first argument only for the real
80 80 sys.argv.
81 81
82 82 - user_ns: a dict to be used as the user's namespace."""
83 83
84 84 #----------------------------------------------------------------------
85 85 # Defaults and initialization
86 86
87 87 # For developer debugging, deactivates crash handler and uses pdb.
88 88 DEVDEBUG = False
89 89
90 90 if argv is None:
91 91 argv = sys.argv
92 92
93 93 # __IP is the main global that lives throughout and represents the whole
94 94 # application. If the user redefines it, all bets are off as to what
95 95 # happens.
96 96
97 97 # __IP is the name of he global which the caller will have accessible as
98 98 # __IP.name. We set its name via the first parameter passed to
99 99 # InteractiveShell:
100 100
101 101 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
102 102 embedded=embedded,**kw)
103 103
104 104 # Put 'help' in the user namespace
105 105 try:
106 106 from site import _Helper
107 107 IP.user_ns['help'] = _Helper()
108 108 except ImportError:
109 109 warn('help() not available - check site.py')
110 IP.user_config_ns = {}
111
112 110
113 111 if DEVDEBUG:
114 112 # For developer debugging only (global flag)
115 113 from IPython import ultraTB
116 114 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
117 115
118 116 IP.BANNER_PARTS = ['Python %s\n'
119 117 'Type "copyright", "credits" or "license" '
120 118 'for more information.\n'
121 119 % (sys.version.split('\n')[0],),
122 120 "IPython %s -- An enhanced Interactive Python."
123 121 % (__version__,),
124 122 """\
125 123 ? -> Introduction and overview of IPython's features.
126 124 %quickref -> Quick reference.
127 125 help -> Python's own help system.
128 126 object? -> Details about 'object'. ?object also works, ?? prints more.
129 127 """ ]
130 128
131 129 IP.usage = interactive_usage
132 130
133 131 # Platform-dependent suffix and directory names. We use _ipython instead
134 132 # of .ipython under win32 b/c there's software that breaks with .named
135 133 # directories on that platform.
136 134 if os.name == 'posix':
137 135 rc_suffix = ''
138 136 ipdir_def = '.ipython'
139 137 else:
140 138 rc_suffix = '.ini'
141 139 ipdir_def = '_ipython'
142 140
143 141 # default directory for configuration
144 142 ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR',
145 143 os.path.join(IP.home_dir,ipdir_def)))
146 144
147 145 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
148 146
149 147 # we need the directory where IPython itself is installed
150 148 import IPython
151 149 IPython_dir = os.path.dirname(IPython.__file__)
152 150 del IPython
153 151
154 152 #-------------------------------------------------------------------------
155 153 # Command line handling
156 154
157 155 # Valid command line options (uses DPyGetOpt syntax, like Perl's
158 156 # GetOpt::Long)
159 157
160 158 # Any key not listed here gets deleted even if in the file (like session
161 159 # or profile). That's deliberate, to maintain the rc namespace clean.
162 160
163 161 # Each set of options appears twice: under _conv only the names are
164 162 # listed, indicating which type they must be converted to when reading the
165 163 # ipythonrc file. And under DPyGetOpt they are listed with the regular
166 164 # DPyGetOpt syntax (=s,=i,:f,etc).
167 165
168 166 # Make sure there's a space before each end of line (they get auto-joined!)
169 167 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
170 168 'c=s classic|cl color_info! colors=s confirm_exit! '
171 169 'debug! deep_reload! editor=s log|l messages! nosep '
172 170 'object_info_string_level=i pdb! '
173 171 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
174 172 'pydb! '
175 173 'pylab_import_all! '
176 174 'quick screen_length|sl=i prompts_pad_left=i '
177 175 'logfile|lf=s logplay|lp=s profile|p=s '
178 176 'readline! readline_merge_completions! '
179 177 'readline_omit__names! '
180 178 'rcfile=s separate_in|si=s separate_out|so=s '
181 179 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
182 180 'magic_docstrings system_verbose! '
183 181 'multi_line_specials! '
184 182 'term_title! wxversion=s '
185 183 'autoedit_syntax!')
186 184
187 185 # Options that can *only* appear at the cmd line (not in rcfiles).
188 186
189 187 cmdline_only = ('help interact|i ipythondir=s Version upgrade '
190 188 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk! '
191 189 # 'twisted!' # disabled for now.
192 190 )
193 191
194 192 # Build the actual name list to be used by DPyGetOpt
195 193 opts_names = qw(cmdline_opts) + qw(cmdline_only)
196 194
197 195 # Set sensible command line defaults.
198 196 # This should have everything from cmdline_opts and cmdline_only
199 197 opts_def = Struct(autocall = 1,
200 198 autoedit_syntax = 0,
201 199 autoindent = 0,
202 200 automagic = 1,
203 201 autoexec = [],
204 202 banner = 1,
205 203 c = '',
206 204 cache_size = 1000,
207 205 classic = 0,
208 206 color_info = 0,
209 207 colors = 'NoColor',
210 208 confirm_exit = 1,
211 209 debug = 0,
212 210 deep_reload = 0,
213 211 editor = '0',
214 212 gthread = 0,
215 213 help = 0,
216 214 interact = 0,
217 215 ipythondir = ipythondir_def,
218 216 log = 0,
219 217 logfile = '',
220 218 logplay = '',
221 219 messages = 1,
222 220 multi_line_specials = 1,
223 221 nosep = 0,
224 222 object_info_string_level = 0,
225 223 pdb = 0,
226 224 pprint = 0,
227 225 profile = '',
228 226 prompt_in1 = 'In [\\#]: ',
229 227 prompt_in2 = ' .\\D.: ',
230 228 prompt_out = 'Out[\\#]: ',
231 229 prompts_pad_left = 1,
232 230 pydb = 0,
233 231 pylab = 0,
234 232 pylab_import_all = 1,
235 233 q4thread = 0,
236 234 qthread = 0,
237 235 quick = 0,
238 236 quiet = 0,
239 237 rcfile = 'ipythonrc' + rc_suffix,
240 238 readline = 1,
241 239 readline_merge_completions = 1,
242 240 readline_omit__names = 0,
243 241 screen_length = 0,
244 242 separate_in = '\n',
245 243 separate_out = '\n',
246 244 separate_out2 = '',
247 245 system_header = 'IPython system call: ',
248 246 system_verbose = 0,
249 247 term_title = 1,
250 248 tk = 0,
251 249 #twisted= 0, # disabled for now
252 250 upgrade = 0,
253 251 Version = 0,
254 252 wildcards_case_sensitive = 1,
255 253 wthread = 0,
256 254 wxversion = '0',
257 255 xmode = 'Context',
258 256 magic_docstrings = 0, # undocumented, for doc generation
259 257 )
260 258
261 259 # Things that will *only* appear in rcfiles (not at the command line).
262 260 # Make sure there's a space before each end of line (they get auto-joined!)
263 261 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
264 262 qw_lol: 'import_some ',
265 263 # for things with embedded whitespace:
266 264 list_strings:'execute alias readline_parse_and_bind ',
267 265 # Regular strings need no conversion:
268 266 None:'readline_remove_delims ',
269 267 }
270 268 # Default values for these
271 269 rc_def = Struct(include = [],
272 270 import_mod = [],
273 271 import_all = [],
274 272 import_some = [[]],
275 273 execute = [],
276 274 execfile = [],
277 275 alias = [],
278 276 readline_parse_and_bind = [],
279 277 readline_remove_delims = '',
280 278 )
281 279
282 280 # Build the type conversion dictionary from the above tables:
283 281 typeconv = rcfile_opts.copy()
284 282 typeconv.update(optstr2types(cmdline_opts))
285 283
286 284 # FIXME: the None key appears in both, put that back together by hand. Ugly!
287 285 typeconv[None] += ' ' + rcfile_opts[None]
288 286
289 287 # Remove quotes at ends of all strings (used to protect spaces)
290 288 typeconv[unquote_ends] = typeconv[None]
291 289 del typeconv[None]
292 290
293 291 # Build the list we'll use to make all config decisions with defaults:
294 292 opts_all = opts_def.copy()
295 293 opts_all.update(rc_def)
296 294
297 295 # Build conflict resolver for recursive loading of config files:
298 296 # - preserve means the outermost file maintains the value, it is not
299 297 # overwritten if an included file has the same key.
300 298 # - add_flip applies + to the two values, so it better make sense to add
301 299 # those types of keys. But it flips them first so that things loaded
302 300 # deeper in the inclusion chain have lower precedence.
303 301 conflict = {'preserve': ' '.join([ typeconv[int],
304 302 typeconv[unquote_ends] ]),
305 303 'add_flip': ' '.join([ typeconv[qwflat],
306 304 typeconv[qw_lol],
307 305 typeconv[list_strings] ])
308 306 }
309 307
310 308 # Now actually process the command line
311 309 getopt = DPyGetOpt.DPyGetOpt()
312 310 getopt.setIgnoreCase(0)
313 311
314 312 getopt.parseConfiguration(opts_names)
315 313
316 314 try:
317 315 getopt.processArguments(argv)
318 316 except DPyGetOpt.ArgumentError, exc:
319 317 print cmd_line_usage
320 318 warn('\nError in Arguments: "%s"' % exc)
321 319 sys.exit(1)
322 320
323 321 # convert the options dict to a struct for much lighter syntax later
324 322 opts = Struct(getopt.optionValues)
325 323 args = getopt.freeValues
326 324
327 325 # this is the struct (which has default values at this point) with which
328 326 # we make all decisions:
329 327 opts_all.update(opts)
330 328
331 329 # Options that force an immediate exit
332 330 if opts_all.help:
333 331 page(cmd_line_usage)
334 332 sys.exit()
335 333
336 334 if opts_all.Version:
337 335 print __version__
338 336 sys.exit()
339 337
340 338 if opts_all.magic_docstrings:
341 339 IP.magic_magic('-latex')
342 340 sys.exit()
343 341
344 342 # add personal ipythondir to sys.path so that users can put things in
345 343 # there for customization
346 344 sys.path.append(os.path.abspath(opts_all.ipythondir))
347 345
348 346 # Create user config directory if it doesn't exist. This must be done
349 347 # *after* getting the cmd line options.
350 348 if not os.path.isdir(opts_all.ipythondir):
351 349 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
352 350
353 351 # upgrade user config files while preserving a copy of the originals
354 352 if opts_all.upgrade:
355 353 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
356 354
357 355 # check mutually exclusive options in the *original* command line
358 356 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
359 357 qw('classic profile'),qw('classic rcfile')])
360 358
361 359 #---------------------------------------------------------------------------
362 360 # Log replay
363 361
364 362 # if -logplay, we need to 'become' the other session. That basically means
365 363 # replacing the current command line environment with that of the old
366 364 # session and moving on.
367 365
368 366 # this is needed so that later we know we're in session reload mode, as
369 367 # opts_all will get overwritten:
370 368 load_logplay = 0
371 369
372 370 if opts_all.logplay:
373 371 load_logplay = opts_all.logplay
374 372 opts_debug_save = opts_all.debug
375 373 try:
376 374 logplay = open(opts_all.logplay)
377 375 except IOError:
378 376 if opts_all.debug: IP.InteractiveTB()
379 377 warn('Could not open logplay file '+`opts_all.logplay`)
380 378 # restore state as if nothing had happened and move on, but make
381 379 # sure that later we don't try to actually load the session file
382 380 logplay = None
383 381 load_logplay = 0
384 382 del opts_all.logplay
385 383 else:
386 384 try:
387 385 logplay.readline()
388 386 logplay.readline();
389 387 # this reloads that session's command line
390 388 cmd = logplay.readline()[6:]
391 389 exec cmd
392 390 # restore the true debug flag given so that the process of
393 391 # session loading itself can be monitored.
394 392 opts.debug = opts_debug_save
395 393 # save the logplay flag so later we don't overwrite the log
396 394 opts.logplay = load_logplay
397 395 # now we must update our own structure with defaults
398 396 opts_all.update(opts)
399 397 # now load args
400 398 cmd = logplay.readline()[6:]
401 399 exec cmd
402 400 logplay.close()
403 401 except:
404 402 logplay.close()
405 403 if opts_all.debug: IP.InteractiveTB()
406 404 warn("Logplay file lacking full configuration information.\n"
407 405 "I'll try to read it, but some things may not work.")
408 406
409 407 #-------------------------------------------------------------------------
410 408 # set up output traps: catch all output from files, being run, modules
411 409 # loaded, etc. Then give it to the user in a clean form at the end.
412 410
413 411 msg_out = 'Output messages. '
414 412 msg_err = 'Error messages. '
415 413 msg_sep = '\n'
416 414 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
417 415 msg_err,msg_sep,debug,
418 416 quiet_out=1),
419 417 user_exec = OutputTrap('User File Execution',msg_out,
420 418 msg_err,msg_sep,debug),
421 419 logplay = OutputTrap('Log Loader',msg_out,
422 420 msg_err,msg_sep,debug),
423 421 summary = ''
424 422 )
425 423
426 424 #-------------------------------------------------------------------------
427 425 # Process user ipythonrc-type configuration files
428 426
429 427 # turn on output trapping and log to msg.config
430 428 # remember that with debug on, trapping is actually disabled
431 429 msg.config.trap_all()
432 430
433 431 # look for rcfile in current or default directory
434 432 try:
435 433 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
436 434 except IOError:
437 435 if opts_all.debug: IP.InteractiveTB()
438 436 warn('Configuration file %s not found. Ignoring request.'
439 437 % (opts_all.rcfile) )
440 438
441 439 # 'profiles' are a shorthand notation for config filenames
442 440 profile_handled_by_legacy = False
443 441 if opts_all.profile:
444 442
445 443 try:
446 444 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
447 445 + rc_suffix,
448 446 opts_all.ipythondir)
449 447 profile_handled_by_legacy = True
450 448 except IOError:
451 449 if opts_all.debug: IP.InteractiveTB()
452 450 opts.profile = '' # remove profile from options if invalid
453 451 # We won't warn anymore, primary method is ipy_profile_PROFNAME
454 452 # which does trigger a warning.
455 453
456 454 # load the config file
457 455 rcfiledata = None
458 456 if opts_all.quick:
459 457 print 'Launching IPython in quick mode. No config file read.'
460 458 elif opts_all.rcfile:
461 459 try:
462 460 cfg_loader = ConfigLoader(conflict)
463 461 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
464 462 'include',opts_all.ipythondir,
465 463 purge = 1,
466 464 unique = conflict['preserve'])
467 465 except:
468 466 IP.InteractiveTB()
469 467 warn('Problems loading configuration file '+
470 468 `opts_all.rcfile`+
471 469 '\nStarting with default -bare bones- configuration.')
472 470 else:
473 471 warn('No valid configuration file found in either currrent directory\n'+
474 472 'or in the IPython config. directory: '+`opts_all.ipythondir`+
475 473 '\nProceeding with internal defaults.')
476 474
477 475 #------------------------------------------------------------------------
478 476 # Set exception handlers in mode requested by user.
479 477 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
480 478 IP.magic_xmode(opts_all.xmode)
481 479 otrap.release_out()
482 480
483 481 #------------------------------------------------------------------------
484 482 # Execute user config
485 483
486 484 # Create a valid config structure with the right precedence order:
487 485 # defaults < rcfile < command line. This needs to be in the instance, so
488 486 # that method calls below that rely on it find it.
489 487 IP.rc = rc_def.copy()
490 488
491 489 # Work with a local alias inside this routine to avoid unnecessary
492 490 # attribute lookups.
493 491 IP_rc = IP.rc
494 492
495 493 IP_rc.update(opts_def)
496 494 if rcfiledata:
497 495 # now we can update
498 496 IP_rc.update(rcfiledata)
499 497 IP_rc.update(opts)
500 498 IP_rc.update(rc_override)
501 499
502 500 # Store the original cmd line for reference:
503 501 IP_rc.opts = opts
504 502 IP_rc.args = args
505 503
506 504 # create a *runtime* Struct like rc for holding parameters which may be
507 505 # created and/or modified by runtime user extensions.
508 506 IP.runtime_rc = Struct()
509 507
510 508 # from this point on, all config should be handled through IP_rc,
511 509 # opts* shouldn't be used anymore.
512 510
513 511
514 512 # update IP_rc with some special things that need manual
515 513 # tweaks. Basically options which affect other options. I guess this
516 514 # should just be written so that options are fully orthogonal and we
517 515 # wouldn't worry about this stuff!
518 516
519 517 if IP_rc.classic:
520 518 IP_rc.quick = 1
521 519 IP_rc.cache_size = 0
522 520 IP_rc.pprint = 0
523 521 IP_rc.prompt_in1 = '>>> '
524 522 IP_rc.prompt_in2 = '... '
525 523 IP_rc.prompt_out = ''
526 524 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
527 525 IP_rc.colors = 'NoColor'
528 526 IP_rc.xmode = 'Plain'
529 527
530 528 IP.pre_config_initialization()
531 529 # configure readline
532 530
533 531 # update exception handlers with rc file status
534 532 otrap.trap_out() # I don't want these messages ever.
535 533 IP.magic_xmode(IP_rc.xmode)
536 534 otrap.release_out()
537 535
538 536 # activate logging if requested and not reloading a log
539 537 if IP_rc.logplay:
540 538 IP.magic_logstart(IP_rc.logplay + ' append')
541 539 elif IP_rc.logfile:
542 540 IP.magic_logstart(IP_rc.logfile)
543 541 elif IP_rc.log:
544 542 IP.magic_logstart()
545 543
546 544 # find user editor so that it we don't have to look it up constantly
547 545 if IP_rc.editor.strip()=='0':
548 546 try:
549 547 ed = os.environ['EDITOR']
550 548 except KeyError:
551 549 if os.name == 'posix':
552 550 ed = 'vi' # the only one guaranteed to be there!
553 551 else:
554 552 ed = 'notepad' # same in Windows!
555 553 IP_rc.editor = ed
556 554
557 555 # Keep track of whether this is an embedded instance or not (useful for
558 556 # post-mortems).
559 557 IP_rc.embedded = IP.embedded
560 558
561 559 # Recursive reload
562 560 try:
563 561 from IPython import deep_reload
564 562 if IP_rc.deep_reload:
565 563 __builtin__.reload = deep_reload.reload
566 564 else:
567 565 __builtin__.dreload = deep_reload.reload
568 566 del deep_reload
569 567 except ImportError:
570 568 pass
571 569
572 570 # Save the current state of our namespace so that the interactive shell
573 571 # can later know which variables have been created by us from config files
574 572 # and loading. This way, loading a file (in any way) is treated just like
575 573 # defining things on the command line, and %who works as expected.
576 574
577 575 # DON'T do anything that affects the namespace beyond this point!
578 576 IP.internal_ns.update(__main__.__dict__)
579 577
580 578 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
581 579
582 580 # Now run through the different sections of the users's config
583 581 if IP_rc.debug:
584 582 print 'Trying to execute the following configuration structure:'
585 583 print '(Things listed first are deeper in the inclusion tree and get'
586 584 print 'loaded first).\n'
587 585 pprint(IP_rc.__dict__)
588 586
589 587 for mod in IP_rc.import_mod:
590 588 try:
591 589 exec 'import '+mod in IP.user_ns
592 590 except :
593 591 IP.InteractiveTB()
594 592 import_fail_info(mod)
595 593
596 594 for mod_fn in IP_rc.import_some:
597 595 if not mod_fn == []:
598 596 mod,fn = mod_fn[0],','.join(mod_fn[1:])
599 597 try:
600 598 exec 'from '+mod+' import '+fn in IP.user_ns
601 599 except :
602 600 IP.InteractiveTB()
603 601 import_fail_info(mod,fn)
604 602
605 603 for mod in IP_rc.import_all:
606 604 try:
607 605 exec 'from '+mod+' import *' in IP.user_ns
608 606 except :
609 607 IP.InteractiveTB()
610 608 import_fail_info(mod)
611 609
612 610 for code in IP_rc.execute:
613 611 try:
614 612 exec code in IP.user_ns
615 613 except:
616 614 IP.InteractiveTB()
617 615 warn('Failure executing code: ' + `code`)
618 616
619 617 # Execute the files the user wants in ipythonrc
620 618 for file in IP_rc.execfile:
621 619 try:
622 620 file = filefind(file,sys.path+[IPython_dir])
623 621 except IOError:
624 622 warn(itpl('File $file not found. Skipping it.'))
625 623 else:
626 624 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
627 625
628 626 # finally, try importing ipy_*_conf for final configuration
629 627 try:
630 628 import ipy_system_conf
631 629 except ImportError:
632 630 if opts_all.debug: IP.InteractiveTB()
633 631 warn("Could not import 'ipy_system_conf'")
634 632 except:
635 633 IP.InteractiveTB()
636 634 import_fail_info('ipy_system_conf')
637 635
638 636 # only import prof module if ipythonrc-PROF was not found
639 637 if opts_all.profile and not profile_handled_by_legacy:
640 638 profmodname = 'ipy_profile_' + opts_all.profile
641 639 try:
642 640
643 641 force_import(profmodname)
644 642 except:
645 643 IP.InteractiveTB()
646 644 print "Error importing",profmodname,"- perhaps you should run %upgrade?"
647 645 import_fail_info(profmodname)
648 646 else:
649 647 opts.profile = opts_all.profile
650 648 else:
651 649 force_import('ipy_profile_none')
652 650 try:
653 651
654 652 force_import('ipy_user_conf')
655 653
656 654 except:
657 655 conf = opts_all.ipythondir + "/ipy_user_conf.py"
658 656 IP.InteractiveTB()
659 657 if not os.path.isfile(conf):
660 658 warn(conf + ' does not exist, please run %upgrade!')
661 659
662 660 import_fail_info("ipy_user_conf")
663 661
664 662 # Define the history file for saving commands in between sessions
665 663 try:
666 664 histfname = 'history-%s' % opts.profile
667 665 except AttributeError:
668 666 histfname = 'history'
669 667 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
670 668
671 669 # finally, push the argv to options again to ensure highest priority
672 670 IP_rc.update(opts)
673 671
674 672 # release stdout and stderr and save config log into a global summary
675 673 msg.config.release_all()
676 674 if IP_rc.messages:
677 675 msg.summary += msg.config.summary_all()
678 676
679 677 #------------------------------------------------------------------------
680 678 # Setup interactive session
681 679
682 680 # Now we should be fully configured. We can then execute files or load
683 681 # things only needed for interactive use. Then we'll open the shell.
684 682
685 683 # Take a snapshot of the user namespace before opening the shell. That way
686 684 # we'll be able to identify which things were interactively defined and
687 685 # which were defined through config files.
688 686 IP.user_config_ns.update(IP.user_ns)
689 687
690 688 # Force reading a file as if it were a session log. Slower but safer.
691 689 if load_logplay:
692 690 print 'Replaying log...'
693 691 try:
694 692 if IP_rc.debug:
695 693 logplay_quiet = 0
696 694 else:
697 695 logplay_quiet = 1
698 696
699 697 msg.logplay.trap_all()
700 698 IP.safe_execfile(load_logplay,IP.user_ns,
701 699 islog = 1, quiet = logplay_quiet)
702 700 msg.logplay.release_all()
703 701 if IP_rc.messages:
704 702 msg.summary += msg.logplay.summary_all()
705 703 except:
706 704 warn('Problems replaying logfile %s.' % load_logplay)
707 705 IP.InteractiveTB()
708 706
709 707 # Load remaining files in command line
710 708 msg.user_exec.trap_all()
711 709
712 710 # Do NOT execute files named in the command line as scripts to be loaded
713 711 # by embedded instances. Doing so has the potential for an infinite
714 712 # recursion if there are exceptions thrown in the process.
715 713
716 714 # XXX FIXME: the execution of user files should be moved out to after
717 715 # ipython is fully initialized, just as if they were run via %run at the
718 716 # ipython prompt. This would also give them the benefit of ipython's
719 717 # nice tracebacks.
720 718
721 719 if (not embedded and IP_rc.args and
722 720 not IP_rc.args[0].lower().endswith('.ipy')):
723 721 name_save = IP.user_ns['__name__']
724 722 IP.user_ns['__name__'] = '__main__'
725 723 # Set our own excepthook in case the user code tries to call it
726 724 # directly. This prevents triggering the IPython crash handler.
727 725 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
728 726
729 727 save_argv = sys.argv[1:] # save it for later restoring
730 728
731 729 sys.argv = args
732 730
733 731 try:
734 732 IP.safe_execfile(args[0], IP.user_ns)
735 733 finally:
736 734 # Reset our crash handler in place
737 735 sys.excepthook = old_excepthook
738 736 sys.argv[:] = save_argv
739 737 IP.user_ns['__name__'] = name_save
740 738
741 739 msg.user_exec.release_all()
742 740
743 741 if IP_rc.messages:
744 742 msg.summary += msg.user_exec.summary_all()
745 743
746 744 # since we can't specify a null string on the cmd line, 0 is the equivalent:
747 745 if IP_rc.nosep:
748 746 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
749 747 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
750 748 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
751 749 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
752 750 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
753 751 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
754 752 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
755 753
756 754 # Determine how many lines at the bottom of the screen are needed for
757 755 # showing prompts, so we can know wheter long strings are to be printed or
758 756 # paged:
759 757 num_lines_bot = IP_rc.separate_in.count('\n')+1
760 758 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
761 759
762 760 # configure startup banner
763 761 if IP_rc.c: # regular python doesn't print the banner with -c
764 762 IP_rc.banner = 0
765 763 if IP_rc.banner:
766 764 BANN_P = IP.BANNER_PARTS
767 765 else:
768 766 BANN_P = []
769 767
770 768 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
771 769
772 770 # add message log (possibly empty)
773 771 if msg.summary: BANN_P.append(msg.summary)
774 772 # Final banner is a string
775 773 IP.BANNER = '\n'.join(BANN_P)
776 774
777 775 # Finalize the IPython instance. This assumes the rc structure is fully
778 776 # in place.
779 777 IP.post_config_initialization()
780 778
781 779 return IP
782 780 #************************ end of file <ipmaker.py> **************************
@@ -1,847 +1,847 b''
1 1 """Nose Plugin that supports IPython doctests.
2 2
3 3 Limitations:
4 4
5 5 - When generating examples for use as doctests, make sure that you have
6 6 pretty-printing OFF. This can be done either by starting ipython with the
7 7 flag '--nopprint', by setting pprint to 0 in your ipythonrc file, or by
8 8 interactively disabling it with %Pprint. This is required so that IPython
9 9 output matches that of normal Python, which is used by doctest for internal
10 10 execution.
11 11
12 12 - Do not rely on specific prompt numbers for results (such as using
13 13 '_34==True', for example). For IPython tests run via an external process the
14 14 prompt numbers may be different, and IPython tests run as normal python code
15 15 won't even have these special _NN variables set at all.
16 16 """
17 17
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Module imports
21 21
22 22 # From the standard library
23 23 import __builtin__
24 24 import commands
25 25 import doctest
26 26 import inspect
27 27 import logging
28 28 import os
29 29 import re
30 30 import sys
31 31 import traceback
32 32 import unittest
33 33
34 34 from inspect import getmodule
35 35 from StringIO import StringIO
36 36
37 37 # We are overriding the default doctest runner, so we need to import a few
38 38 # things from doctest directly
39 39 from doctest import (REPORTING_FLAGS, REPORT_ONLY_FIRST_FAILURE,
40 40 _unittest_reportflags, DocTestRunner,
41 41 _extract_future_flags, pdb, _OutputRedirectingPdb,
42 42 _exception_traceback,
43 43 linecache)
44 44
45 45 # Third-party modules
46 46 import nose.core
47 47
48 48 from nose.plugins import doctests, Plugin
49 49 from nose.util import anyp, getpackage, test_address, resolve_name, tolist
50 50
51 51 #-----------------------------------------------------------------------------
52 52 # Module globals and other constants
53 53
54 54 log = logging.getLogger(__name__)
55 55
56 56 ###########################################################################
57 57 # *** HACK ***
58 58 # We must start our own ipython object and heavily muck with it so that all the
59 59 # modifications IPython makes to system behavior don't send the doctest
60 60 # machinery into a fit. This code should be considered a gross hack, but it
61 61 # gets the job done.
62 62
63 63
64 64 # Hack to modify the %run command so we can sync the user's namespace with the
65 65 # test globals. Once we move over to a clean magic system, this will be done
66 66 # with much less ugliness.
67 67
68 68 class py_file_finder(object):
69 69 def __init__(self,test_filename):
70 70 self.test_filename = test_filename
71 71
72 72 def __call__(self,name):
73 73 from IPython.genutils import get_py_filename
74 74 try:
75 get_py_filename(name)
75 return get_py_filename(name)
76 76 except IOError:
77 77 test_dir = os.path.dirname(self.test_filename)
78 78 new_path = os.path.join(test_dir,name)
79 79 return get_py_filename(new_path)
80 80
81 81
82 82 def _run_ns_sync(self,arg_s,runner=None):
83 83 """Modified version of %run that syncs testing namespaces.
84 84
85 85 This is strictly needed for running doctests that call %run.
86 86 """
87 87
88 88 finder = py_file_finder(_run_ns_sync.test_filename)
89 89 out = _ip.IP.magic_run_ori(arg_s,runner,finder)
90 90 _run_ns_sync.test_globs.update(_ip.user_ns)
91 91 return out
92 92
93 93
94 94 class ipnsdict(dict):
95 95 """A special subclass of dict for use as an IPython namespace in doctests.
96 96
97 97 This subclass adds a simple checkpointing capability so that when testing
98 98 machinery clears it (we use it as the test execution context), it doesn't
99 99 get completely destroyed.
100 100 """
101 101
102 102 def __init__(self,*a):
103 103 dict.__init__(self,*a)
104 104 self._savedict = {}
105 105
106 106 def clear(self):
107 107 dict.clear(self)
108 108 self.update(self._savedict)
109 109
110 110 def _checkpoint(self):
111 111 self._savedict.clear()
112 112 self._savedict.update(self)
113 113
114 114 def update(self,other):
115 115 self._checkpoint()
116 116 dict.update(self,other)
117 117 # If '_' is in the namespace, python won't set it when executing code,
118 118 # and we have examples that test it. So we ensure that the namespace
119 119 # is always 'clean' of it before it's used for test code execution.
120 120 self.pop('_',None)
121 121
122 122
123 123 def start_ipython():
124 124 """Start a global IPython shell, which we need for IPython-specific syntax.
125 125 """
126 126 import new
127 127
128 128 import IPython
129 129
130 130 def xsys(cmd):
131 131 """Execute a command and print its output.
132 132
133 133 This is just a convenience function to replace the IPython system call
134 134 with one that is more doctest-friendly.
135 135 """
136 136 cmd = _ip.IP.var_expand(cmd,depth=1)
137 137 sys.stdout.write(commands.getoutput(cmd))
138 138 sys.stdout.flush()
139 139
140 140 # Store certain global objects that IPython modifies
141 141 _displayhook = sys.displayhook
142 142 _excepthook = sys.excepthook
143 143 _main = sys.modules.get('__main__')
144 144
145 145 # Start IPython instance. We customize it to start with minimal frills.
146 146 user_ns,global_ns = IPython.ipapi.make_user_namespaces(ipnsdict(),dict())
147 147 IPython.Shell.IPShell(['--colors=NoColor','--noterm_title'],
148 148 user_ns,global_ns)
149 149
150 150 # Deactivate the various python system hooks added by ipython for
151 151 # interactive convenience so we don't confuse the doctest system
152 152 sys.modules['__main__'] = _main
153 153 sys.displayhook = _displayhook
154 154 sys.excepthook = _excepthook
155 155
156 156 # So that ipython magics and aliases can be doctested (they work by making
157 157 # a call into a global _ip object)
158 158 _ip = IPython.ipapi.get()
159 159 __builtin__._ip = _ip
160 160
161 161 # Modify the IPython system call with one that uses getoutput, so that we
162 162 # can capture subcommands and print them to Python's stdout, otherwise the
163 163 # doctest machinery would miss them.
164 164 _ip.system = xsys
165 165
166 166 # Also patch our %run function in.
167 167 im = new.instancemethod(_run_ns_sync,_ip.IP, _ip.IP.__class__)
168 168 _ip.IP.magic_run_ori = _ip.IP.magic_run
169 169 _ip.IP.magic_run = im
170 170
171 171 # The start call MUST be made here. I'm not sure yet why it doesn't work if
172 172 # it is made later, at plugin initialization time, but in all my tests, that's
173 173 # the case.
174 174 start_ipython()
175 175
176 176 # *** END HACK ***
177 177 ###########################################################################
178 178
179 179 # Classes and functions
180 180
181 181 def is_extension_module(filename):
182 182 """Return whether the given filename is an extension module.
183 183
184 184 This simply checks that the extension is either .so or .pyd.
185 185 """
186 186 return os.path.splitext(filename)[1].lower() in ('.so','.pyd')
187 187
188 188
189 189 class DocTestSkip(object):
190 190 """Object wrapper for doctests to be skipped."""
191 191
192 192 ds_skip = """Doctest to skip.
193 193 >>> 1 #doctest: +SKIP
194 194 """
195 195
196 196 def __init__(self,obj):
197 197 self.obj = obj
198 198
199 199 def __getattribute__(self,key):
200 200 if key == '__doc__':
201 201 return DocTestSkip.ds_skip
202 202 else:
203 203 return getattr(object.__getattribute__(self,'obj'),key)
204 204
205 205 # Modified version of the one in the stdlib, that fixes a python bug (doctests
206 206 # not found in extension modules, http://bugs.python.org/issue3158)
207 207 class DocTestFinder(doctest.DocTestFinder):
208 208
209 209 def _from_module(self, module, object):
210 210 """
211 211 Return true if the given object is defined in the given
212 212 module.
213 213 """
214 214 if module is None:
215 215 return True
216 216 elif inspect.isfunction(object):
217 217 return module.__dict__ is object.func_globals
218 218 elif inspect.isbuiltin(object):
219 219 return module.__name__ == object.__module__
220 220 elif inspect.isclass(object):
221 221 return module.__name__ == object.__module__
222 222 elif inspect.ismethod(object):
223 223 # This one may be a bug in cython that fails to correctly set the
224 224 # __module__ attribute of methods, but since the same error is easy
225 225 # to make by extension code writers, having this safety in place
226 226 # isn't such a bad idea
227 227 return module.__name__ == object.im_class.__module__
228 228 elif inspect.getmodule(object) is not None:
229 229 return module is inspect.getmodule(object)
230 230 elif hasattr(object, '__module__'):
231 231 return module.__name__ == object.__module__
232 232 elif isinstance(object, property):
233 233 return True # [XX] no way not be sure.
234 234 else:
235 235 raise ValueError("object must be a class or function")
236 236
237 237 def _find(self, tests, obj, name, module, source_lines, globs, seen):
238 238 """
239 239 Find tests for the given object and any contained objects, and
240 240 add them to `tests`.
241 241 """
242 242
243 243 if hasattr(obj,"skip_doctest"):
244 244 #print 'SKIPPING DOCTEST FOR:',obj # dbg
245 245 obj = DocTestSkip(obj)
246 246
247 247 doctest.DocTestFinder._find(self,tests, obj, name, module,
248 248 source_lines, globs, seen)
249 249
250 250 # Below we re-run pieces of the above method with manual modifications,
251 251 # because the original code is buggy and fails to correctly identify
252 252 # doctests in extension modules.
253 253
254 254 # Local shorthands
255 255 from inspect import isroutine, isclass, ismodule
256 256
257 257 # Look for tests in a module's contained objects.
258 258 if inspect.ismodule(obj) and self._recurse:
259 259 for valname, val in obj.__dict__.items():
260 260 valname1 = '%s.%s' % (name, valname)
261 261 if ( (isroutine(val) or isclass(val))
262 262 and self._from_module(module, val) ):
263 263
264 264 self._find(tests, val, valname1, module, source_lines,
265 265 globs, seen)
266 266
267 267 # Look for tests in a class's contained objects.
268 268 if inspect.isclass(obj) and self._recurse:
269 269 #print 'RECURSE into class:',obj # dbg
270 270 for valname, val in obj.__dict__.items():
271 271 # Special handling for staticmethod/classmethod.
272 272 if isinstance(val, staticmethod):
273 273 val = getattr(obj, valname)
274 274 if isinstance(val, classmethod):
275 275 val = getattr(obj, valname).im_func
276 276
277 277 # Recurse to methods, properties, and nested classes.
278 278 if ((inspect.isfunction(val) or inspect.isclass(val) or
279 279 inspect.ismethod(val) or
280 280 isinstance(val, property)) and
281 281 self._from_module(module, val)):
282 282 valname = '%s.%s' % (name, valname)
283 283 self._find(tests, val, valname, module, source_lines,
284 284 globs, seen)
285 285
286 286
287 287 class IPDoctestOutputChecker(doctest.OutputChecker):
288 288 """Second-chance checker with support for random tests.
289 289
290 290 If the default comparison doesn't pass, this checker looks in the expected
291 291 output string for flags that tell us to ignore the output.
292 292 """
293 293
294 294 random_re = re.compile(r'#\s*random\s+')
295 295
296 296 def check_output(self, want, got, optionflags):
297 297 """Check output, accepting special markers embedded in the output.
298 298
299 299 If the output didn't pass the default validation but the special string
300 300 '#random' is included, we accept it."""
301 301
302 302 # Let the original tester verify first, in case people have valid tests
303 303 # that happen to have a comment saying '#random' embedded in.
304 304 ret = doctest.OutputChecker.check_output(self, want, got,
305 305 optionflags)
306 306 if not ret and self.random_re.search(want):
307 307 #print >> sys.stderr, 'RANDOM OK:',want # dbg
308 308 return True
309 309
310 310 return ret
311 311
312 312
313 313 class DocTestCase(doctests.DocTestCase):
314 314 """Proxy for DocTestCase: provides an address() method that
315 315 returns the correct address for the doctest case. Otherwise
316 316 acts as a proxy to the test case. To provide hints for address(),
317 317 an obj may also be passed -- this will be used as the test object
318 318 for purposes of determining the test address, if it is provided.
319 319 """
320 320
321 321 # Note: this method was taken from numpy's nosetester module.
322 322
323 323 # Subclass nose.plugins.doctests.DocTestCase to work around a bug in
324 324 # its constructor that blocks non-default arguments from being passed
325 325 # down into doctest.DocTestCase
326 326
327 327 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
328 328 checker=None, obj=None, result_var='_'):
329 329 self._result_var = result_var
330 330 doctests.DocTestCase.__init__(self, test,
331 331 optionflags=optionflags,
332 332 setUp=setUp, tearDown=tearDown,
333 333 checker=checker)
334 334 # Now we must actually copy the original constructor from the stdlib
335 335 # doctest class, because we can't call it directly and a bug in nose
336 336 # means it never gets passed the right arguments.
337 337
338 338 self._dt_optionflags = optionflags
339 339 self._dt_checker = checker
340 340 self._dt_test = test
341 341 self._dt_setUp = setUp
342 342 self._dt_tearDown = tearDown
343 343
344 344 # XXX - store this runner once in the object!
345 345 runner = IPDocTestRunner(optionflags=optionflags,
346 346 checker=checker, verbose=False)
347 347 self._dt_runner = runner
348 348
349 349
350 350 # Each doctest should remember what directory it was loaded from...
351 351 self._ori_dir = os.getcwd()
352 352
353 353 # Modified runTest from the default stdlib
354 354 def runTest(self):
355 355 test = self._dt_test
356 356 runner = self._dt_runner
357 357
358 358 old = sys.stdout
359 359 new = StringIO()
360 360 optionflags = self._dt_optionflags
361 361
362 362 if not (optionflags & REPORTING_FLAGS):
363 363 # The option flags don't include any reporting flags,
364 364 # so add the default reporting flags
365 365 optionflags |= _unittest_reportflags
366 366
367 367 try:
368 368 # Save our current directory and switch out to the one where the
369 369 # test was originally created, in case another doctest did a
370 370 # directory change. We'll restore this in the finally clause.
371 371 curdir = os.getcwd()
372 372 os.chdir(self._ori_dir)
373 373
374 374 runner.DIVIDER = "-"*70
375 375 failures, tries = runner.run(test,out=new.write,
376 376 clear_globs=False)
377 377 finally:
378 378 sys.stdout = old
379 379 os.chdir(curdir)
380 380
381 381 if failures:
382 382 raise self.failureException(self.format_failure(new.getvalue()))
383 383
384 384 def setUp(self):
385 385 """Modified test setup that syncs with ipython namespace"""
386 386
387 387 if isinstance(self._dt_test.examples[0],IPExample):
388 388 # for IPython examples *only*, we swap the globals with the ipython
389 389 # namespace, after updating it with the globals (which doctest
390 390 # fills with the necessary info from the module being tested).
391 391 _ip.IP.user_ns.update(self._dt_test.globs)
392 392 self._dt_test.globs = _ip.IP.user_ns
393 393
394 394 doctests.DocTestCase.setUp(self)
395 395
396 396
397 397
398 398 # A simple subclassing of the original with a different class name, so we can
399 399 # distinguish and treat differently IPython examples from pure python ones.
400 400 class IPExample(doctest.Example): pass
401 401
402 402
403 403 class IPExternalExample(doctest.Example):
404 404 """Doctest examples to be run in an external process."""
405 405
406 406 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
407 407 options=None):
408 408 # Parent constructor
409 409 doctest.Example.__init__(self,source,want,exc_msg,lineno,indent,options)
410 410
411 411 # An EXTRA newline is needed to prevent pexpect hangs
412 412 self.source += '\n'
413 413
414 414
415 415 class IPDocTestParser(doctest.DocTestParser):
416 416 """
417 417 A class used to parse strings containing doctest examples.
418 418
419 419 Note: This is a version modified to properly recognize IPython input and
420 420 convert any IPython examples into valid Python ones.
421 421 """
422 422 # This regular expression is used to find doctest examples in a
423 423 # string. It defines three groups: `source` is the source code
424 424 # (including leading indentation and prompts); `indent` is the
425 425 # indentation of the first (PS1) line of the source code; and
426 426 # `want` is the expected output (including leading indentation).
427 427
428 428 # Classic Python prompts or default IPython ones
429 429 _PS1_PY = r'>>>'
430 430 _PS2_PY = r'\.\.\.'
431 431
432 432 _PS1_IP = r'In\ \[\d+\]:'
433 433 _PS2_IP = r'\ \ \ \.\.\.+:'
434 434
435 435 _RE_TPL = r'''
436 436 # Source consists of a PS1 line followed by zero or more PS2 lines.
437 437 (?P<source>
438 438 (?:^(?P<indent> [ ]*) (?P<ps1> %s) .*) # PS1 line
439 439 (?:\n [ ]* (?P<ps2> %s) .*)*) # PS2 lines
440 440 \n? # a newline
441 441 # Want consists of any non-blank lines that do not start with PS1.
442 442 (?P<want> (?:(?![ ]*$) # Not a blank line
443 443 (?![ ]*%s) # Not a line starting with PS1
444 444 (?![ ]*%s) # Not a line starting with PS2
445 445 .*$\n? # But any other line
446 446 )*)
447 447 '''
448 448
449 449 _EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY),
450 450 re.MULTILINE | re.VERBOSE)
451 451
452 452 _EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP),
453 453 re.MULTILINE | re.VERBOSE)
454 454
455 455 # Mark a test as being fully random. In this case, we simply append the
456 456 # random marker ('#random') to each individual example's output. This way
457 457 # we don't need to modify any other code.
458 458 _RANDOM_TEST = re.compile(r'#\s*all-random\s+')
459 459
460 460 # Mark tests to be executed in an external process - currently unsupported.
461 461 _EXTERNAL_IP = re.compile(r'#\s*ipdoctest:\s*EXTERNAL')
462 462
463 463 def ip2py(self,source):
464 464 """Convert input IPython source into valid Python."""
465 465 out = []
466 466 newline = out.append
467 467 for lnum,line in enumerate(source.splitlines()):
468 468 newline(_ip.IP.prefilter(line,lnum>0))
469 469 newline('') # ensure a closing newline, needed by doctest
470 470 #print "PYSRC:", '\n'.join(out) # dbg
471 471 return '\n'.join(out)
472 472
473 473 def parse(self, string, name='<string>'):
474 474 """
475 475 Divide the given string into examples and intervening text,
476 476 and return them as a list of alternating Examples and strings.
477 477 Line numbers for the Examples are 0-based. The optional
478 478 argument `name` is a name identifying this string, and is only
479 479 used for error messages.
480 480 """
481 481
482 482 #print 'Parse string:\n',string # dbg
483 483
484 484 string = string.expandtabs()
485 485 # If all lines begin with the same indentation, then strip it.
486 486 min_indent = self._min_indent(string)
487 487 if min_indent > 0:
488 488 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
489 489
490 490 output = []
491 491 charno, lineno = 0, 0
492 492
493 493 # We make 'all random' tests by adding the '# random' mark to every
494 494 # block of output in the test.
495 495 if self._RANDOM_TEST.search(string):
496 496 random_marker = '\n# random'
497 497 else:
498 498 random_marker = ''
499 499
500 500 # Whether to convert the input from ipython to python syntax
501 501 ip2py = False
502 502 # Find all doctest examples in the string. First, try them as Python
503 503 # examples, then as IPython ones
504 504 terms = list(self._EXAMPLE_RE_PY.finditer(string))
505 505 if terms:
506 506 # Normal Python example
507 507 #print '-'*70 # dbg
508 508 #print 'PyExample, Source:\n',string # dbg
509 509 #print '-'*70 # dbg
510 510 Example = doctest.Example
511 511 else:
512 512 # It's an ipython example. Note that IPExamples are run
513 513 # in-process, so their syntax must be turned into valid python.
514 514 # IPExternalExamples are run out-of-process (via pexpect) so they
515 515 # don't need any filtering (a real ipython will be executing them).
516 516 terms = list(self._EXAMPLE_RE_IP.finditer(string))
517 517 if self._EXTERNAL_IP.search(string):
518 518 #print '-'*70 # dbg
519 519 #print 'IPExternalExample, Source:\n',string # dbg
520 520 #print '-'*70 # dbg
521 521 Example = IPExternalExample
522 522 else:
523 523 #print '-'*70 # dbg
524 524 #print 'IPExample, Source:\n',string # dbg
525 525 #print '-'*70 # dbg
526 526 Example = IPExample
527 527 ip2py = True
528 528
529 529 for m in terms:
530 530 # Add the pre-example text to `output`.
531 531 output.append(string[charno:m.start()])
532 532 # Update lineno (lines before this example)
533 533 lineno += string.count('\n', charno, m.start())
534 534 # Extract info from the regexp match.
535 535 (source, options, want, exc_msg) = \
536 536 self._parse_example(m, name, lineno,ip2py)
537 537
538 538 # Append the random-output marker (it defaults to empty in most
539 539 # cases, it's only non-empty for 'all-random' tests):
540 540 want += random_marker
541 541
542 542 if Example is IPExternalExample:
543 543 options[doctest.NORMALIZE_WHITESPACE] = True
544 544 want += '\n'
545 545
546 546 # Create an Example, and add it to the list.
547 547 if not self._IS_BLANK_OR_COMMENT(source):
548 548 output.append(Example(source, want, exc_msg,
549 549 lineno=lineno,
550 550 indent=min_indent+len(m.group('indent')),
551 551 options=options))
552 552 # Update lineno (lines inside this example)
553 553 lineno += string.count('\n', m.start(), m.end())
554 554 # Update charno.
555 555 charno = m.end()
556 556 # Add any remaining post-example text to `output`.
557 557 output.append(string[charno:])
558 558 return output
559 559
560 560 def _parse_example(self, m, name, lineno,ip2py=False):
561 561 """
562 562 Given a regular expression match from `_EXAMPLE_RE` (`m`),
563 563 return a pair `(source, want)`, where `source` is the matched
564 564 example's source code (with prompts and indentation stripped);
565 565 and `want` is the example's expected output (with indentation
566 566 stripped).
567 567
568 568 `name` is the string's name, and `lineno` is the line number
569 569 where the example starts; both are used for error messages.
570 570
571 571 Optional:
572 572 `ip2py`: if true, filter the input via IPython to convert the syntax
573 573 into valid python.
574 574 """
575 575
576 576 # Get the example's indentation level.
577 577 indent = len(m.group('indent'))
578 578
579 579 # Divide source into lines; check that they're properly
580 580 # indented; and then strip their indentation & prompts.
581 581 source_lines = m.group('source').split('\n')
582 582
583 583 # We're using variable-length input prompts
584 584 ps1 = m.group('ps1')
585 585 ps2 = m.group('ps2')
586 586 ps1_len = len(ps1)
587 587
588 588 self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len)
589 589 if ps2:
590 590 self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno)
591 591
592 592 source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines])
593 593
594 594 if ip2py:
595 595 # Convert source input from IPython into valid Python syntax
596 596 source = self.ip2py(source)
597 597
598 598 # Divide want into lines; check that it's properly indented; and
599 599 # then strip the indentation. Spaces before the last newline should
600 600 # be preserved, so plain rstrip() isn't good enough.
601 601 want = m.group('want')
602 602 want_lines = want.split('\n')
603 603 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
604 604 del want_lines[-1] # forget final newline & spaces after it
605 605 self._check_prefix(want_lines, ' '*indent, name,
606 606 lineno + len(source_lines))
607 607
608 608 # Remove ipython output prompt that might be present in the first line
609 609 want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0])
610 610
611 611 want = '\n'.join([wl[indent:] for wl in want_lines])
612 612
613 613 # If `want` contains a traceback message, then extract it.
614 614 m = self._EXCEPTION_RE.match(want)
615 615 if m:
616 616 exc_msg = m.group('msg')
617 617 else:
618 618 exc_msg = None
619 619
620 620 # Extract options from the source.
621 621 options = self._find_options(source, name, lineno)
622 622
623 623 return source, options, want, exc_msg
624 624
625 625 def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len):
626 626 """
627 627 Given the lines of a source string (including prompts and
628 628 leading indentation), check to make sure that every prompt is
629 629 followed by a space character. If any line is not followed by
630 630 a space character, then raise ValueError.
631 631
632 632 Note: IPython-modified version which takes the input prompt length as a
633 633 parameter, so that prompts of variable length can be dealt with.
634 634 """
635 635 space_idx = indent+ps1_len
636 636 min_len = space_idx+1
637 637 for i, line in enumerate(lines):
638 638 if len(line) >= min_len and line[space_idx] != ' ':
639 639 raise ValueError('line %r of the docstring for %s '
640 640 'lacks blank after %s: %r' %
641 641 (lineno+i+1, name,
642 642 line[indent:space_idx], line))
643 643
644 644
645 645 SKIP = doctest.register_optionflag('SKIP')
646 646
647 647
648 648 class IPDocTestRunner(doctest.DocTestRunner,object):
649 649 """Test runner that synchronizes the IPython namespace with test globals.
650 650 """
651 651
652 652 def run(self, test, compileflags=None, out=None, clear_globs=True):
653 653
654 654 # Hack: ipython needs access to the execution context of the example,
655 655 # so that it can propagate user variables loaded by %run into
656 656 # test.globs. We put them here into our modified %run as a function
657 657 # attribute. Our new %run will then only make the namespace update
658 658 # when called (rather than unconconditionally updating test.globs here
659 659 # for all examples, most of which won't be calling %run anyway).
660 660 _run_ns_sync.test_globs = test.globs
661 661 _run_ns_sync.test_filename = test.filename
662 662
663 663 return super(IPDocTestRunner,self).run(test,
664 664 compileflags,out,clear_globs)
665 665
666 666
667 667 class DocFileCase(doctest.DocFileCase):
668 668 """Overrides to provide filename
669 669 """
670 670 def address(self):
671 671 return (self._dt_test.filename, None, None)
672 672
673 673
674 674 class ExtensionDoctest(doctests.Doctest):
675 675 """Nose Plugin that supports doctests in extension modules.
676 676 """
677 677 name = 'extdoctest' # call nosetests with --with-extdoctest
678 678 enabled = True
679 679
680 680 def __init__(self,exclude_patterns=None):
681 681 """Create a new ExtensionDoctest plugin.
682 682
683 683 Parameters
684 684 ----------
685 685
686 686 exclude_patterns : sequence of strings, optional
687 687 These patterns are compiled as regular expressions, subsequently used
688 688 to exclude any filename which matches them from inclusion in the test
689 689 suite (using pattern.search(), NOT pattern.match() ).
690 690 """
691 691 if exclude_patterns is None:
692 692 exclude_patterns = []
693 693 self.exclude_patterns = map(re.compile,exclude_patterns)
694 694 doctests.Doctest.__init__(self)
695 695
696 696 def options(self, parser, env=os.environ):
697 697 Plugin.options(self, parser, env)
698 698 parser.add_option('--doctest-tests', action='store_true',
699 699 dest='doctest_tests',
700 700 default=env.get('NOSE_DOCTEST_TESTS',True),
701 701 help="Also look for doctests in test modules. "
702 702 "Note that classes, methods and functions should "
703 703 "have either doctests or non-doctest tests, "
704 704 "not both. [NOSE_DOCTEST_TESTS]")
705 705 parser.add_option('--doctest-extension', action="append",
706 706 dest="doctestExtension",
707 707 help="Also look for doctests in files with "
708 708 "this extension [NOSE_DOCTEST_EXTENSION]")
709 709 # Set the default as a list, if given in env; otherwise
710 710 # an additional value set on the command line will cause
711 711 # an error.
712 712 env_setting = env.get('NOSE_DOCTEST_EXTENSION')
713 713 if env_setting is not None:
714 714 parser.set_defaults(doctestExtension=tolist(env_setting))
715 715
716 716
717 717 def configure(self, options, config):
718 718 Plugin.configure(self, options, config)
719 719 self.doctest_tests = options.doctest_tests
720 720 self.extension = tolist(options.doctestExtension)
721 721
722 722 self.parser = doctest.DocTestParser()
723 723 self.finder = DocTestFinder()
724 724 self.checker = IPDoctestOutputChecker()
725 725 self.globs = None
726 726 self.extraglobs = None
727 727
728 728
729 729 def loadTestsFromExtensionModule(self,filename):
730 730 bpath,mod = os.path.split(filename)
731 731 modname = os.path.splitext(mod)[0]
732 732 try:
733 733 sys.path.append(bpath)
734 734 module = __import__(modname)
735 735 tests = list(self.loadTestsFromModule(module))
736 736 finally:
737 737 sys.path.pop()
738 738 return tests
739 739
740 740 # NOTE: the method below is almost a copy of the original one in nose, with
741 741 # a few modifications to control output checking.
742 742
743 743 def loadTestsFromModule(self, module):
744 744 #print '*** ipdoctest - lTM',module # dbg
745 745
746 746 if not self.matches(module.__name__):
747 747 log.debug("Doctest doesn't want module %s", module)
748 748 return
749 749
750 750 tests = self.finder.find(module,globs=self.globs,
751 751 extraglobs=self.extraglobs)
752 752 if not tests:
753 753 return
754 754
755 755 # always use whitespace and ellipsis options
756 756 optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
757 757
758 758 tests.sort()
759 759 module_file = module.__file__
760 760 if module_file[-4:] in ('.pyc', '.pyo'):
761 761 module_file = module_file[:-1]
762 762 for test in tests:
763 763 if not test.examples:
764 764 continue
765 765 if not test.filename:
766 766 test.filename = module_file
767 767
768 768 yield DocTestCase(test,
769 769 optionflags=optionflags,
770 770 checker=self.checker)
771 771
772 772
773 773 def loadTestsFromFile(self, filename):
774 774 if is_extension_module(filename):
775 775 for t in self.loadTestsFromExtensionModule(filename):
776 776 yield t
777 777 else:
778 778 if self.extension and anyp(filename.endswith, self.extension):
779 779 name = os.path.basename(filename)
780 780 dh = open(filename)
781 781 try:
782 782 doc = dh.read()
783 783 finally:
784 784 dh.close()
785 785 test = self.parser.get_doctest(
786 786 doc, globs={'__file__': filename}, name=name,
787 787 filename=filename, lineno=0)
788 788 if test.examples:
789 789 #print 'FileCase:',test.examples # dbg
790 790 yield DocFileCase(test)
791 791 else:
792 792 yield False # no tests to load
793 793
794 794 def wantFile(self,filename):
795 795 """Return whether the given filename should be scanned for tests.
796 796
797 797 Modified version that accepts extension modules as valid containers for
798 798 doctests.
799 799 """
800 800 #print '*** ipdoctest- wantFile:',filename # dbg
801 801
802 802 for pat in self.exclude_patterns:
803 803 if pat.search(filename):
804 804 #print '###>>> SKIP:',filename # dbg
805 805 return False
806 806
807 807 if is_extension_module(filename):
808 808 return True
809 809 else:
810 810 return doctests.Doctest.wantFile(self,filename)
811 811
812 812
813 813 class IPythonDoctest(ExtensionDoctest):
814 814 """Nose Plugin that supports doctests in extension modules.
815 815 """
816 816 name = 'ipdoctest' # call nosetests with --with-ipdoctest
817 817 enabled = True
818 818
819 819 def makeTest(self, obj, parent):
820 820 """Look for doctests in the given object, which will be a
821 821 function, method or class.
822 822 """
823 823 # always use whitespace and ellipsis options
824 824 optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
825 825
826 826 doctests = self.finder.find(obj, module=getmodule(parent))
827 827 if doctests:
828 828 for test in doctests:
829 829 if len(test.examples) == 0:
830 830 continue
831 831
832 832 yield DocTestCase(test, obj=obj,
833 833 optionflags=optionflags,
834 834 checker=self.checker)
835 835
836 836 def configure(self, options, config):
837 837
838 838 Plugin.configure(self, options, config)
839 839 self.doctest_tests = options.doctest_tests
840 840 self.extension = tolist(options.doctestExtension)
841 841
842 842 self.parser = IPDocTestParser()
843 843 self.finder = DocTestFinder(parser=self.parser)
844 844 self.checker = IPDoctestOutputChecker()
845 845 self.globs = None
846 846 self.extraglobs = None
847 847
@@ -1,127 +1,135 b''
1 1 """Tests for various magic functions.
2 2
3 3 Needs to be run by nose (to make ipython session available).
4 4 """
5 5
6 6 # Standard library imports
7 7 import os
8 8 import sys
9 9
10 10 # Third-party imports
11 11 import nose.tools as nt
12 12
13 13 # From our own code
14 14 from IPython.testing import decorators as dec
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Test functions begin
18 18
19 19 def test_rehashx():
20 20 # clear up everything
21 21 _ip.IP.alias_table.clear()
22 22 del _ip.db['syscmdlist']
23 23
24 24 _ip.magic('rehashx')
25 25 # Practically ALL ipython development systems will have more than 10 aliases
26 26
27 27 assert len(_ip.IP.alias_table) > 10
28 28 for key, val in _ip.IP.alias_table.items():
29 29 # we must strip dots from alias names
30 30 assert '.' not in key
31 31
32 32 # rehashx must fill up syscmdlist
33 33 scoms = _ip.db['syscmdlist']
34 34 assert len(scoms) > 10
35 35
36 36
37 37 def doctest_run_ns():
38 38 """Classes declared %run scripts must be instantiable afterwards.
39 39
40 40 In [11]: run tclass
41 41
42 42 In [12]: isinstance(f(),foo)
43 43 Out[12]: True
44 44 """
45 45
46 46
47 47 def doctest_run_ns2():
48 48 """Classes declared %run scripts must be instantiable afterwards.
49 49
50 50 In [3]: run tclass.py
51 51
52 52 In [4]: run tclass first_pass
53 53
54 54 In [5]: run tclass second_pass
55 55 Deleting object: first_pass
56 56 """
57 57
58 58
59 59 def doctest_hist_f():
60 60 """Test %hist -f with temporary filename.
61 61
62 62 In [9]: import tempfile
63 63
64 64 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
65 65
66 66 In [11]: %history -n -f $tfile 3
67 67 """
68 68
69 69
70 70 def doctest_hist_r():
71 71 """Test %hist -r
72 72
73 73 XXX - This test is not recording the output correctly. Not sure why...
74 74
75 75 In [6]: x=1
76 76
77 77 In [7]: hist -n -r 2
78 78 x=1 # random
79 79 hist -n -r 2 # random
80 80 """
81 81
82 82
83 def test_obj_del():
84 """Test that object's __del__ methods are called on exit."""
85 test_dir = os.path.dirname(__file__)
86 del_file = os.path.join(test_dir,'obj_del.py')
87 out = _ip.IP.getoutput('ipython %s' % del_file)
88 nt.assert_equals(out,'object A deleted')
89
90
83 91 def test_shist():
84 92 # Simple tests of ShadowHist class - test generator.
85 93 import os, shutil, tempfile
86 94
87 95 from IPython.Extensions import pickleshare
88 96 from IPython.history import ShadowHist
89 97
90 98 tfile = tempfile.mktemp('','tmp-ipython-')
91 99
92 100 db = pickleshare.PickleShareDB(tfile)
93 101 s = ShadowHist(db)
94 102 s.add('hello')
95 103 s.add('world')
96 104 s.add('hello')
97 105 s.add('hello')
98 106 s.add('karhu')
99 107
100 108 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
101 109
102 110 yield nt.assert_equal,s.get(2),'world'
103 111
104 112 shutil.rmtree(tfile)
105 113
106 114 @dec.skipif_not_numpy
107 115 def test_numpy_clear_array_undec():
108 116 _ip.ex('import numpy as np')
109 117 _ip.ex('a = np.empty(2)')
110 118
111 119 yield nt.assert_true,'a' in _ip.user_ns
112 120 _ip.magic('clear array')
113 121 yield nt.assert_false,'a' in _ip.user_ns
114 122
115 123
116 124 @dec.skip()
117 125 def test_fail_dec(*a,**k):
118 126 yield nt.assert_true, False
119 127
120 128 @dec.skip('This one shouldn not run')
121 129 def test_fail_dec2(*a,**k):
122 130 yield nt.assert_true, False
123 131
124 132 @dec.skipknownfailure
125 133 def test_fail_dec3(*a,**k):
126 134 yield nt.assert_true, False
127 135
General Comments 0
You need to be logged in to leave comments. Login now