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