##// END OF EJS Templates
Fix tab-completion bug in threaded shells.x
fperez -
Show More

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

@@ -1,900 +1,913 b''
1 1 # -*- coding: utf-8 -*-
2 2 """IPython Shell classes.
3 3
4 4 All the matplotlib support code was co-developed with John Hunter,
5 5 matplotlib's author.
6 6
7 $Id: Shell.py 958 2005-12-27 23:17:51Z fperez $"""
7 $Id: Shell.py 964 2005-12-28 21:03:01Z fperez $"""
8 8
9 9 #*****************************************************************************
10 10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #*****************************************************************************
15 15
16 16 from IPython import Release
17 17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 18 __license__ = Release.license
19 19
20 20 # Code begins
21 21 import __main__
22 22 import __builtin__
23 23 import os
24 24 import sys
25 25 import signal
26 26 import threading
27 27
28 28 import IPython
29 29 from IPython import ultraTB
30 30 from IPython.genutils import Term,warn,error,flag_calls
31 31 from IPython.iplib import InteractiveShell
32 32 from IPython.ipmaker import make_IPython
33 33 from IPython.Magic import Magic
34 34 from IPython.Struct import Struct
35 35
36 36 # global flag to pass around information about Ctrl-C without exceptions
37 37 KBINT = False
38 38
39 39 # global flag to turn on/off Tk support.
40 40 USE_TK = False
41 41
42 42 #-----------------------------------------------------------------------------
43 43 # This class is trivial now, but I want to have it in to publish a clean
44 44 # interface. Later when the internals are reorganized, code that uses this
45 45 # shouldn't have to change.
46 46
47 47 class IPShell:
48 48 """Create an IPython instance."""
49 49
50 def __init__(self,argv=None,user_ns=None,debug=1,
51 shell_class=InteractiveShell):
52 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
53 shell_class=shell_class)
50 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
51 debug=1,shell_class=InteractiveShell):
52 self.IP = make_IPython(argv,user_ns=user_ns,user_global_ns=user_global_ns,
53 debug=debug,shell_class=shell_class)
54 54
55 55 def mainloop(self,sys_exit=0,banner=None):
56 56 self.IP.mainloop(banner)
57 57 if sys_exit:
58 58 sys.exit()
59 59
60 60 #-----------------------------------------------------------------------------
61 61 class IPShellEmbed:
62 62 """Allow embedding an IPython shell into a running program.
63 63
64 64 Instances of this class are callable, with the __call__ method being an
65 65 alias to the embed() method of an InteractiveShell instance.
66 66
67 67 Usage (see also the example-embed.py file for a running example):
68 68
69 69 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
70 70
71 71 - argv: list containing valid command-line options for IPython, as they
72 72 would appear in sys.argv[1:].
73 73
74 74 For example, the following command-line options:
75 75
76 76 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
77 77
78 78 would be passed in the argv list as:
79 79
80 80 ['-prompt_in1','Input <\\#>','-colors','LightBG']
81 81
82 82 - banner: string which gets printed every time the interpreter starts.
83 83
84 84 - exit_msg: string which gets printed every time the interpreter exits.
85 85
86 86 - rc_override: a dict or Struct of configuration options such as those
87 87 used by IPython. These options are read from your ~/.ipython/ipythonrc
88 88 file when the Shell object is created. Passing an explicit rc_override
89 89 dict with any options you want allows you to override those values at
90 90 creation time without having to modify the file. This way you can create
91 91 embeddable instances configured in any way you want without editing any
92 92 global files (thus keeping your interactive IPython configuration
93 93 unchanged).
94 94
95 95 Then the ipshell instance can be called anywhere inside your code:
96 96
97 97 ipshell(header='') -> Opens up an IPython shell.
98 98
99 99 - header: string printed by the IPython shell upon startup. This can let
100 100 you know where in your code you are when dropping into the shell. Note
101 101 that 'banner' gets prepended to all calls, so header is used for
102 102 location-specific information.
103 103
104 104 For more details, see the __call__ method below.
105 105
106 106 When the IPython shell is exited with Ctrl-D, normal program execution
107 107 resumes.
108 108
109 109 This functionality was inspired by a posting on comp.lang.python by cmkl
110 110 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
111 111 by the IDL stop/continue commands."""
112 112
113 113 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
114 114 """Note that argv here is a string, NOT a list."""
115 115 self.set_banner(banner)
116 116 self.set_exit_msg(exit_msg)
117 117 self.set_dummy_mode(0)
118 118
119 119 # sys.displayhook is a global, we need to save the user's original
120 120 # Don't rely on __displayhook__, as the user may have changed that.
121 121 self.sys_displayhook_ori = sys.displayhook
122 122
123 123 # save readline completer status
124 124 try:
125 125 #print 'Save completer',sys.ipcompleter # dbg
126 126 self.sys_ipcompleter_ori = sys.ipcompleter
127 127 except:
128 128 pass # not nested with IPython
129 129
130 130 # FIXME. Passing user_ns breaks namespace handling.
131 131 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
132 132 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
133 133
134 134 # copy our own displayhook also
135 135 self.sys_displayhook_embed = sys.displayhook
136 136 # and leave the system's display hook clean
137 137 sys.displayhook = self.sys_displayhook_ori
138 138 # don't use the ipython crash handler so that user exceptions aren't
139 139 # trapped
140 140 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
141 141 mode = self.IP.rc.xmode,
142 142 call_pdb = self.IP.rc.pdb)
143 143 self.restore_system_completer()
144 144
145 145 def restore_system_completer(self):
146 146 """Restores the readline completer which was in place.
147 147
148 148 This allows embedded IPython within IPython not to disrupt the
149 149 parent's completion.
150 150 """
151 151
152 152 try:
153 153 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
154 154 sys.ipcompleter = self.sys_ipcompleter_ori
155 155 except:
156 156 pass
157 157
158 158 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
159 159 """Activate the interactive interpreter.
160 160
161 161 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
162 162 the interpreter shell with the given local and global namespaces, and
163 163 optionally print a header string at startup.
164 164
165 165 The shell can be globally activated/deactivated using the
166 166 set/get_dummy_mode methods. This allows you to turn off a shell used
167 167 for debugging globally.
168 168
169 169 However, *each* time you call the shell you can override the current
170 170 state of dummy_mode with the optional keyword parameter 'dummy'. For
171 171 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
172 172 can still have a specific call work by making it as IPShell(dummy=0).
173 173
174 174 The optional keyword parameter dummy controls whether the call
175 175 actually does anything. """
176 176
177 177 # Allow the dummy parameter to override the global __dummy_mode
178 178 if dummy or (dummy != 0 and self.__dummy_mode):
179 179 return
180 180
181 181 # Set global subsystems (display,completions) to our values
182 182 sys.displayhook = self.sys_displayhook_embed
183 183 if self.IP.has_readline:
184 184 self.IP.readline.set_completer(self.IP.Completer.complete)
185 185
186 186 if self.banner and header:
187 187 format = '%s\n%s\n'
188 188 else:
189 189 format = '%s%s\n'
190 190 banner = format % (self.banner,header)
191 191
192 192 # Call the embedding code with a stack depth of 1 so it can skip over
193 193 # our call and get the original caller's namespaces.
194 194 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
195 195
196 196 if self.exit_msg:
197 197 print self.exit_msg
198 198
199 199 # Restore global systems (display, completion)
200 200 sys.displayhook = self.sys_displayhook_ori
201 201 self.restore_system_completer()
202 202
203 203 def set_dummy_mode(self,dummy):
204 204 """Sets the embeddable shell's dummy mode parameter.
205 205
206 206 set_dummy_mode(dummy): dummy = 0 or 1.
207 207
208 208 This parameter is persistent and makes calls to the embeddable shell
209 209 silently return without performing any action. This allows you to
210 210 globally activate or deactivate a shell you're using with a single call.
211 211
212 212 If you need to manually"""
213 213
214 214 if dummy not in [0,1,False,True]:
215 215 raise ValueError,'dummy parameter must be boolean'
216 216 self.__dummy_mode = dummy
217 217
218 218 def get_dummy_mode(self):
219 219 """Return the current value of the dummy mode parameter.
220 220 """
221 221 return self.__dummy_mode
222 222
223 223 def set_banner(self,banner):
224 224 """Sets the global banner.
225 225
226 226 This banner gets prepended to every header printed when the shell
227 227 instance is called."""
228 228
229 229 self.banner = banner
230 230
231 231 def set_exit_msg(self,exit_msg):
232 232 """Sets the global exit_msg.
233 233
234 234 This exit message gets printed upon exiting every time the embedded
235 235 shell is called. It is None by default. """
236 236
237 237 self.exit_msg = exit_msg
238 238
239 239 #-----------------------------------------------------------------------------
240 240 def sigint_handler (signum,stack_frame):
241 241 """Sigint handler for threaded apps.
242 242
243 243 This is a horrible hack to pass information about SIGINT _without_ using
244 244 exceptions, since I haven't been able to properly manage cross-thread
245 245 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
246 246 that's my understanding from a c.l.py thread where this was discussed)."""
247 247
248 248 global KBINT
249 249
250 250 print '\nKeyboardInterrupt - Press <Enter> to continue.',
251 251 Term.cout.flush()
252 252 # Set global flag so that runsource can know that Ctrl-C was hit
253 253 KBINT = True
254 254
255 255 class MTInteractiveShell(InteractiveShell):
256 256 """Simple multi-threaded shell."""
257 257
258 258 # Threading strategy taken from:
259 259 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
260 260 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
261 261 # from the pygtk mailing list, to avoid lockups with system calls.
262 262
263 263 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
264 user_ns = None, banner2='',**kw):
264 user_ns=None,user_global_ns=None,banner2='',**kw):
265 265 """Similar to the normal InteractiveShell, but with threading control"""
266 266
267 IPython.iplib.InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2)
267 InteractiveShell.__init__(self,name,usage,rc,user_ns,
268 user_global_ns,banner2)
268 269
269 270 # Locking control variable
270 271 self.thread_ready = threading.Condition()
271 272
272 273 # Stuff to do at closing time
273 274 self._kill = False
274 275 on_kill = kw.get('on_kill')
275 276 if on_kill is None:
276 277 on_kill = []
277 278 # Check that all things to kill are callable:
278 279 for t in on_kill:
279 280 if not callable(t):
280 281 raise TypeError,'on_kill must be a list of callables'
281 282 self.on_kill = on_kill
282 283
283 284 def runsource(self, source, filename="<input>", symbol="single"):
284 285 """Compile and run some source in the interpreter.
285 286
286 287 Modified version of code.py's runsource(), to handle threading issues.
287 288 See the original for full docstring details."""
288 289
289 290 global KBINT
290 291
291 292 # If Ctrl-C was typed, we reset the flag and return right away
292 293 if KBINT:
293 294 KBINT = False
294 295 return False
295 296
296 297 try:
297 298 code = self.compile(source, filename, symbol)
298 299 except (OverflowError, SyntaxError, ValueError):
299 300 # Case 1
300 301 self.showsyntaxerror(filename)
301 302 return False
302 303
303 304 if code is None:
304 305 # Case 2
305 306 return True
306 307
307 308 # Case 3
308 309 # Store code in self, so the execution thread can handle it
309 310 self.thread_ready.acquire()
310 311 self.code_to_run = code
311 312 self.thread_ready.wait() # Wait until processed in timeout interval
312 313 self.thread_ready.release()
313 314
314 315 return False
315 316
316 317 def runcode(self):
317 318 """Execute a code object.
318 319
319 320 Multithreaded wrapper around IPython's runcode()."""
320 321
321 322 # lock thread-protected stuff
322 323 self.thread_ready.acquire()
323 324
324 325 # Install sigint handler
325 326 try:
326 327 signal.signal(signal.SIGINT, sigint_handler)
327 328 except SystemError:
328 329 # This happens under Windows, which seems to have all sorts
329 330 # of problems with signal handling. Oh well...
330 331 pass
331 332
332 333 if self._kill:
333 334 print >>Term.cout, 'Closing threads...',
334 335 Term.cout.flush()
335 336 for tokill in self.on_kill:
336 337 tokill()
337 338 print >>Term.cout, 'Done.'
338 339
339 340 # Run pending code by calling parent class
340 341 if self.code_to_run is not None:
341 342 self.thread_ready.notify()
342 343 InteractiveShell.runcode(self,self.code_to_run)
343 344
344 345 # We're done with thread-protected variables
345 346 self.thread_ready.release()
346 347 # This MUST return true for gtk threading to work
347 348 return True
348 349
349 350 def kill (self):
350 351 """Kill the thread, returning when it has been shut down."""
351 352 self.thread_ready.acquire()
352 353 self._kill = True
353 354 self.thread_ready.release()
354 355
355 356 class MatplotlibShellBase:
356 357 """Mixin class to provide the necessary modifications to regular IPython
357 358 shell classes for matplotlib support.
358 359
359 360 Given Python's MRO, this should be used as the FIRST class in the
360 361 inheritance hierarchy, so that it overrides the relevant methods."""
361 362
362 363 def _matplotlib_config(self,name):
363 364 """Return various items needed to setup the user's shell with matplotlib"""
364 365
365 366 # Initialize matplotlib to interactive mode always
366 367 import matplotlib
367 368 from matplotlib import backends
368 369 matplotlib.interactive(True)
369 370
370 371 def use(arg):
371 372 """IPython wrapper for matplotlib's backend switcher.
372 373
373 374 In interactive use, we can not allow switching to a different
374 375 interactive backend, since thread conflicts will most likely crash
375 376 the python interpreter. This routine does a safety check first,
376 377 and refuses to perform a dangerous switch. It still allows
377 378 switching to non-interactive backends."""
378 379
379 380 if arg in backends.interactive_bk and arg != self.mpl_backend:
380 381 m=('invalid matplotlib backend switch.\n'
381 382 'This script attempted to switch to the interactive '
382 383 'backend: `%s`\n'
383 384 'Your current choice of interactive backend is: `%s`\n\n'
384 385 'Switching interactive matplotlib backends at runtime\n'
385 386 'would crash the python interpreter, '
386 387 'and IPython has blocked it.\n\n'
387 388 'You need to either change your choice of matplotlib backend\n'
388 389 'by editing your .matplotlibrc file, or run this script as a \n'
389 390 'standalone file from the command line, not using IPython.\n' %
390 391 (arg,self.mpl_backend) )
391 392 raise RuntimeError, m
392 393 else:
393 394 self.mpl_use(arg)
394 395 self.mpl_use._called = True
395 396
396 397 self.matplotlib = matplotlib
397 398 self.mpl_backend = matplotlib.rcParams['backend']
398 399
399 400 # we also need to block switching of interactive backends by use()
400 401 self.mpl_use = matplotlib.use
401 402 self.mpl_use._called = False
402 403 # overwrite the original matplotlib.use with our wrapper
403 404 matplotlib.use = use
404 405
405 406
406 407 # This must be imported last in the matplotlib series, after
407 408 # backend/interactivity choices have been made
408 409 try:
409 410 import matplotlib.pylab as pylab
410 411 self.pylab = pylab
411 412 self.pylab_name = 'pylab'
412 413 except ImportError:
413 414 import matplotlib.matlab as matlab
414 415 self.pylab = matlab
415 416 self.pylab_name = 'matlab'
416 417
417 418 self.pylab.show._needmain = False
418 419 # We need to detect at runtime whether show() is called by the user.
419 420 # For this, we wrap it into a decorator which adds a 'called' flag.
420 421 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
421 422
422 423 # Build a user namespace initialized with matplotlib/matlab features.
423 424 user_ns = {'__name__':'__main__',
424 425 '__builtins__' : __builtin__ }
425 426
426 427 # Be careful not to remove the final \n in the code string below, or
427 428 # things will break badly with py22 (I think it's a python bug, 2.3 is
428 429 # OK).
429 430 pname = self.pylab_name # Python can't interpolate dotted var names
430 431 exec ("import matplotlib\n"
431 432 "import matplotlib.%(pname)s as %(pname)s\n"
432 433 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
433 434
434 435 # Build matplotlib info banner
435 436 b="""
436 437 Welcome to pylab, a matplotlib-based Python environment.
437 438 For more information, type 'help(pylab)'.
438 439 """
439 440 return user_ns,b
440 441
441 442 def mplot_exec(self,fname,*where,**kw):
442 443 """Execute a matplotlib script.
443 444
444 445 This is a call to execfile(), but wrapped in safeties to properly
445 446 handle interactive rendering and backend switching."""
446 447
447 448 #print '*** Matplotlib runner ***' # dbg
448 449 # turn off rendering until end of script
449 450 isInteractive = self.matplotlib.rcParams['interactive']
450 451 self.matplotlib.interactive(False)
451 452 self.safe_execfile(fname,*where,**kw)
452 453 self.matplotlib.interactive(isInteractive)
453 454 # make rendering call now, if the user tried to do it
454 455 if self.pylab.draw_if_interactive.called:
455 456 self.pylab.draw()
456 457 self.pylab.draw_if_interactive.called = False
457 458
458 459 # if a backend switch was performed, reverse it now
459 460 if self.mpl_use._called:
460 461 self.matplotlib.rcParams['backend'] = self.mpl_backend
461 462
462 463 def magic_run(self,parameter_s=''):
463 464 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
464 465
465 466 # Fix the docstring so users see the original as well
466 467 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
467 468 "\n *** Modified %run for Matplotlib,"
468 469 " with proper interactive handling ***")
469 470
470 471 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
471 472 # and multithreaded. Note that these are meant for internal use, the IPShell*
472 473 # classes below are the ones meant for public consumption.
473 474
474 475 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
475 476 """Single-threaded shell with matplotlib support."""
476 477
477 478 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
478 user_ns = None, **kw):
479 user_ns=None,user_global_ns=None,**kw):
479 480 user_ns,b2 = self._matplotlib_config(name)
480 InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
481 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
482 banner2=b2,**kw)
481 483
482 484 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
483 485 """Multi-threaded shell with matplotlib support."""
484 486
485 487 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
486 user_ns = None, **kw):
488 user_ns=None,user_global_ns=None, **kw):
487 489 user_ns,b2 = self._matplotlib_config(name)
488 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
490 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
491 banner2=b2,**kw)
489 492
490 493 #-----------------------------------------------------------------------------
491 494 # Utility functions for the different GUI enabled IPShell* classes.
492 495
493 496 def get_tk():
494 497 """Tries to import Tkinter and returns a withdrawn Tkinter root
495 498 window. If Tkinter is already imported or not available, this
496 499 returns None. This function calls `hijack_tk` underneath.
497 500 """
498 501 if not USE_TK or sys.modules.has_key('Tkinter'):
499 502 return None
500 503 else:
501 504 try:
502 505 import Tkinter
503 506 except ImportError:
504 507 return None
505 508 else:
506 509 hijack_tk()
507 510 r = Tkinter.Tk()
508 511 r.withdraw()
509 512 return r
510 513
511 514 def hijack_tk():
512 515 """Modifies Tkinter's mainloop with a dummy so when a module calls
513 516 mainloop, it does not block.
514 517
515 518 """
516 519 def misc_mainloop(self, n=0):
517 520 pass
518 521 def tkinter_mainloop(n=0):
519 522 pass
520 523
521 524 import Tkinter
522 525 Tkinter.Misc.mainloop = misc_mainloop
523 526 Tkinter.mainloop = tkinter_mainloop
524 527
525 528 def update_tk(tk):
526 529 """Updates the Tkinter event loop. This is typically called from
527 530 the respective WX or GTK mainloops.
528 531 """
529 532 if tk:
530 533 tk.update()
531 534
532 535 def hijack_wx():
533 536 """Modifies wxPython's MainLoop with a dummy so user code does not
534 537 block IPython. The hijacked mainloop function is returned.
535 538 """
536 539 def dummy_mainloop(*args, **kw):
537 540 pass
538 541 import wxPython
539 542 ver = wxPython.__version__
540 543 orig_mainloop = None
541 544 if ver[:3] >= '2.5':
542 545 import wx
543 546 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
544 547 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
545 548 else: raise AttributeError('Could not find wx core module')
546 549 orig_mainloop = core.PyApp_MainLoop
547 550 core.PyApp_MainLoop = dummy_mainloop
548 551 elif ver[:3] == '2.4':
549 552 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
550 553 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
551 554 else:
552 555 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
553 556 return orig_mainloop
554 557
555 558 def hijack_gtk():
556 559 """Modifies pyGTK's mainloop with a dummy so user code does not
557 560 block IPython. This function returns the original `gtk.mainloop`
558 561 function that has been hijacked.
559 562 """
560 563 def dummy_mainloop(*args, **kw):
561 564 pass
562 565 import gtk
563 566 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
564 567 else: orig_mainloop = gtk.mainloop
565 568 gtk.mainloop = dummy_mainloop
566 569 gtk.main = dummy_mainloop
567 570 return orig_mainloop
568 571
569 572 #-----------------------------------------------------------------------------
570 573 # The IPShell* classes below are the ones meant to be run by external code as
571 574 # IPython instances. Note that unless a specific threading strategy is
572 575 # desired, the factory function start() below should be used instead (it
573 576 # selects the proper threaded class).
574 577
575 578 class IPShellGTK(threading.Thread):
576 579 """Run a gtk mainloop() in a separate thread.
577 580
578 581 Python commands can be passed to the thread where they will be executed.
579 582 This is implemented by periodically checking for passed code using a
580 583 GTK timeout callback."""
581 584
582 585 TIMEOUT = 100 # Millisecond interval between timeouts.
583 586
584 def __init__(self,argv=None,user_ns=None,debug=1,
585 shell_class=MTInteractiveShell):
587 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
588 debug=1,shell_class=MTInteractiveShell):
586 589
587 590 import gtk
588 591
589 592 self.gtk = gtk
590 593 self.gtk_mainloop = hijack_gtk()
591 594
592 595 # Allows us to use both Tk and GTK.
593 596 self.tk = get_tk()
594 597
595 598 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
596 599 else: mainquit = self.gtk.mainquit
597 600
598 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
601 self.IP = make_IPython(argv,user_ns=user_ns,
602 user_global_ns=user_global_ns,
603 debug=debug,
599 604 shell_class=shell_class,
600 605 on_kill=[mainquit])
601 606
602 607 # HACK: slot for banner in self; it will be passed to the mainloop
603 608 # method only and .run() needs it. The actual value will be set by
604 609 # .mainloop().
605 610 self._banner = None
606 611
607 612 threading.Thread.__init__(self)
608 613
609 614 def run(self):
610 615 self.IP.mainloop(self._banner)
611 616 self.IP.kill()
612 617
613 618 def mainloop(self,sys_exit=0,banner=None):
614 619
615 620 self._banner = banner
616 621
617 622 if self.gtk.pygtk_version >= (2,4,0):
618 623 import gobject
619 624 gobject.idle_add(self.on_timer)
620 625 else:
621 626 self.gtk.idle_add(self.on_timer)
622 627
623 628 if sys.platform != 'win32':
624 629 try:
625 630 if self.gtk.gtk_version[0] >= 2:
626 631 self.gtk.threads_init()
627 632 except AttributeError:
628 633 pass
629 634 except RuntimeError:
630 635 error('Your pyGTK likely has not been compiled with '
631 636 'threading support.\n'
632 637 'The exception printout is below.\n'
633 638 'You can either rebuild pyGTK with threads, or '
634 639 'try using \n'
635 640 'matplotlib with a different backend (like Tk or WX).\n'
636 641 'Note that matplotlib will most likely not work in its '
637 642 'current state!')
638 643 self.IP.InteractiveTB()
639 644 self.start()
640 645 self.gtk.threads_enter()
641 646 self.gtk_mainloop()
642 647 self.gtk.threads_leave()
643 648 self.join()
644 649
645 650 def on_timer(self):
646 651 update_tk(self.tk)
647 652 return self.IP.runcode()
648 653
649 654
650 655 class IPShellWX(threading.Thread):
651 656 """Run a wx mainloop() in a separate thread.
652 657
653 658 Python commands can be passed to the thread where they will be executed.
654 659 This is implemented by periodically checking for passed code using a
655 660 GTK timeout callback."""
656 661
657 662 TIMEOUT = 100 # Millisecond interval between timeouts.
658 663
659 def __init__(self,argv=None,user_ns=None,debug=1,
660 shell_class=MTInteractiveShell):
664 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
665 debug=1,shell_class=MTInteractiveShell):
661 666
662 667 import wxPython.wx as wx
663 668
664 669 threading.Thread.__init__(self)
665 670 self.wx = wx
666 671 self.wx_mainloop = hijack_wx()
667 672
668 673 # Allows us to use both Tk and GTK.
669 674 self.tk = get_tk()
670 675
671 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
676 self.IP = make_IPython(argv,user_ns=user_ns,
677 user_global_ns=user_global_ns,
678 debug=debug,
672 679 shell_class=shell_class,
673 680 on_kill=[self.wxexit])
674 681 # HACK: slot for banner in self; it will be passed to the mainloop
675 682 # method only and .run() needs it. The actual value will be set by
676 683 # .mainloop().
677 684 self._banner = None
678 685
679 686 self.app = None
680 687
681 688 def wxexit(self, *args):
682 689 if self.app is not None:
683 690 self.app.agent.timer.Stop()
684 691 self.app.ExitMainLoop()
685 692
686 693 def run(self):
687 694 self.IP.mainloop(self._banner)
688 695 self.IP.kill()
689 696
690 697 def mainloop(self,sys_exit=0,banner=None):
691 698
692 699 self._banner = banner
693 700
694 701 self.start()
695 702
696 703 class TimerAgent(self.wx.wxMiniFrame):
697 704 wx = self.wx
698 705 IP = self.IP
699 706 tk = self.tk
700 707 def __init__(self, parent, interval):
701 708 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
702 709 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
703 710 size=(100, 100),style=style)
704 711 self.Show(False)
705 712 self.interval = interval
706 713 self.timerId = self.wx.wxNewId()
707 714
708 715 def StartWork(self):
709 716 self.timer = self.wx.wxTimer(self, self.timerId)
710 717 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
711 718 self.timer.Start(self.interval)
712 719
713 720 def OnTimer(self, event):
714 721 update_tk(self.tk)
715 722 self.IP.runcode()
716 723
717 724 class App(self.wx.wxApp):
718 725 wx = self.wx
719 726 TIMEOUT = self.TIMEOUT
720 727 def OnInit(self):
721 728 'Create the main window and insert the custom frame'
722 729 self.agent = TimerAgent(None, self.TIMEOUT)
723 730 self.agent.Show(self.wx.false)
724 731 self.agent.StartWork()
725 732 return self.wx.true
726 733
727 734 self.app = App(redirect=False)
728 735 self.wx_mainloop(self.app)
729 736 self.join()
730 737
731 738
732 739 class IPShellQt(threading.Thread):
733 740 """Run a Qt event loop in a separate thread.
734 741
735 742 Python commands can be passed to the thread where they will be executed.
736 743 This is implemented by periodically checking for passed code using a
737 744 Qt timer / slot."""
738 745
739 746 TIMEOUT = 100 # Millisecond interval between timeouts.
740 747
741 def __init__(self,argv=None,user_ns=None,debug=0,
742 shell_class=MTInteractiveShell):
748 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
749 debug=0,shell_class=MTInteractiveShell):
743 750
744 751 import qt
745 752
746 753 class newQApplication:
747 754 def __init__( self ):
748 755 self.QApplication = qt.QApplication
749 756
750 757 def __call__( *args, **kwargs ):
751 758 return qt.qApp
752 759
753 760 def exec_loop( *args, **kwargs ):
754 761 pass
755 762
756 763 def __getattr__( self, name ):
757 764 return getattr( self.QApplication, name )
758 765
759 766 qt.QApplication = newQApplication()
760 767
761 768 # Allows us to use both Tk and QT.
762 769 self.tk = get_tk()
763 770
764 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
771 self.IP = make_IPython(argv,user_ns=user_ns,
772 user_global_ns=user_global_ns,
773 debug=debug,
765 774 shell_class=shell_class,
766 775 on_kill=[qt.qApp.exit])
767 776
768 777 # HACK: slot for banner in self; it will be passed to the mainloop
769 778 # method only and .run() needs it. The actual value will be set by
770 779 # .mainloop().
771 780 self._banner = None
772 781
773 782 threading.Thread.__init__(self)
774 783
775 784 def run(self):
776 785 self.IP.mainloop(self._banner)
777 786 self.IP.kill()
778 787
779 788 def mainloop(self,sys_exit=0,banner=None):
780 789
781 790 import qt
782 791
783 792 self._banner = banner
784 793
785 794 if qt.QApplication.startingUp():
786 795 a = qt.QApplication.QApplication(sys.argv)
787 796 self.timer = qt.QTimer()
788 797 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
789 798
790 799 self.start()
791 800 self.timer.start( self.TIMEOUT, True )
792 801 while True:
793 802 if self.IP._kill: break
794 803 qt.qApp.exec_loop()
795 804 self.join()
796 805
797 806 def on_timer(self):
798 807 update_tk(self.tk)
799 808 result = self.IP.runcode()
800 809 self.timer.start( self.TIMEOUT, True )
801 810 return result
802 811
803 812 # A set of matplotlib public IPython shell classes, for single-threaded
804 813 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
805 814 class IPShellMatplotlib(IPShell):
806 815 """Subclass IPShell with MatplotlibShell as the internal shell.
807 816
808 817 Single-threaded class, meant for the Tk* and FLTK* backends.
809 818
810 819 Having this on a separate class simplifies the external driver code."""
811 820
812 def __init__(self,argv=None,user_ns=None,debug=1):
813 IPShell.__init__(self,argv,user_ns,debug,shell_class=MatplotlibShell)
821 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
822 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
823 shell_class=MatplotlibShell)
814 824
815 825 class IPShellMatplotlibGTK(IPShellGTK):
816 826 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
817 827
818 828 Multi-threaded class, meant for the GTK* backends."""
819 829
820 def __init__(self,argv=None,user_ns=None,debug=1):
821 IPShellGTK.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
830 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
831 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
832 shell_class=MatplotlibMTShell)
822 833
823 834 class IPShellMatplotlibWX(IPShellWX):
824 835 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
825 836
826 837 Multi-threaded class, meant for the WX* backends."""
827 838
828 def __init__(self,argv=None,user_ns=None,debug=1):
829 IPShellWX.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
839 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
840 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
841 shell_class=MatplotlibMTShell)
830 842
831 843 class IPShellMatplotlibQt(IPShellQt):
832 844 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
833 845
834 846 Multi-threaded class, meant for the Qt* backends."""
835 847
836 def __init__(self,argv=None,user_ns=None,debug=1):
837 IPShellQt.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
848 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
849 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
850 shell_class=MatplotlibMTShell)
838 851
839 852 #-----------------------------------------------------------------------------
840 853 # Factory functions to actually start the proper thread-aware shell
841 854
842 855 def _matplotlib_shell_class():
843 856 """Factory function to handle shell class selection for matplotlib.
844 857
845 858 The proper shell class to use depends on the matplotlib backend, since
846 859 each backend requires a different threading strategy."""
847 860
848 861 try:
849 862 import matplotlib
850 863 except ImportError:
851 864 error('matplotlib could NOT be imported! Starting normal IPython.')
852 865 sh_class = IPShell
853 866 else:
854 867 backend = matplotlib.rcParams['backend']
855 868 if backend.startswith('GTK'):
856 869 sh_class = IPShellMatplotlibGTK
857 870 elif backend.startswith('WX'):
858 871 sh_class = IPShellMatplotlibWX
859 872 elif backend.startswith('Qt'):
860 873 sh_class = IPShellMatplotlibQt
861 874 else:
862 875 sh_class = IPShellMatplotlib
863 876 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
864 877 return sh_class
865 878
866 879 # This is the one which should be called by external code.
867 880 def start():
868 881 """Return a running shell instance, dealing with threading options.
869 882
870 883 This is a factory function which will instantiate the proper IPython shell
871 884 based on the user's threading choice. Such a selector is needed because
872 885 different GUI toolkits require different thread handling details."""
873 886
874 887 global USE_TK
875 888 # Crude sys.argv hack to extract the threading options.
876 889 argv = sys.argv
877 890 if len(argv) > 1:
878 891 if len(argv) > 2:
879 892 arg2 = argv[2]
880 893 if arg2.endswith('-tk'):
881 894 USE_TK = True
882 895 arg1 = argv[1]
883 896 if arg1.endswith('-gthread'):
884 897 shell = IPShellGTK
885 898 elif arg1.endswith( '-qthread' ):
886 899 shell = IPShellQt
887 900 elif arg1.endswith('-wthread'):
888 901 shell = IPShellWX
889 902 elif arg1.endswith('-pylab'):
890 903 shell = _matplotlib_shell_class()
891 904 else:
892 905 shell = IPShell
893 906 else:
894 907 shell = IPShell
895 908 return shell()
896 909
897 910 # Some aliases for backwards compatibility
898 911 IPythonShell = IPShell
899 912 IPythonShellEmbed = IPShellEmbed
900 913 #************************ End of file <Shell.py> ***************************
@@ -1,523 +1,526 b''
1 1 """Word completion for IPython.
2 2
3 3 This module is a fork of the rlcompleter module in the Python standard
4 4 library. The original enhancements made to rlcompleter have been sent
5 5 upstream and were accepted as of Python 2.3, but we need a lot more
6 6 functionality specific to IPython, so this module will continue to live as an
7 7 IPython-specific utility.
8 8
9 9 ---------------------------------------------------------------------------
10 10 Original rlcompleter documentation:
11 11
12 12 This requires the latest extension to the readline module (the
13 13 completes keywords, built-ins and globals in __main__; when completing
14 14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 15 completes its attributes.
16 16
17 17 It's very cool to do "import string" type "string.", hit the
18 18 completion key (twice), and see the list of names defined by the
19 19 string module!
20 20
21 21 Tip: to use the tab key as the completion key, call
22 22
23 23 readline.parse_and_bind("tab: complete")
24 24
25 25 Notes:
26 26
27 27 - Exceptions raised by the completer function are *ignored* (and
28 28 generally cause the completion to fail). This is a feature -- since
29 29 readline sets the tty device in raw (or cbreak) mode, printing a
30 30 traceback wouldn't work well without some complicated hoopla to save,
31 31 reset and restore the tty state.
32 32
33 33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 34 application defined code to be executed if an object with a
35 35 __getattr__ hook is found. Since it is the responsibility of the
36 36 application (or the user) to enable this feature, I consider this an
37 37 acceptable risk. More complicated expressions (e.g. function calls or
38 38 indexing operations) are *not* evaluated.
39 39
40 40 - GNU readline is also used by the built-in functions input() and
41 41 raw_input(), and thus these also benefit/suffer from the completer
42 42 features. Clearly an interactive application can benefit by
43 43 specifying its own completer function and using raw_input() for all
44 44 its input.
45 45
46 46 - When the original stdin is not a tty device, GNU readline is never
47 47 used, and this module (and the readline module) are silently inactive.
48 48
49 49 """
50 50
51 51 #*****************************************************************************
52 52 #
53 53 # Since this file is essentially a minimally modified copy of the rlcompleter
54 54 # module which is part of the standard Python distribution, I assume that the
55 55 # proper procedure is to maintain its copyright as belonging to the Python
56 56 # Software Foundation (in addition to my own, for all new code).
57 57 #
58 58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 59 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
60 60 #
61 61 # Distributed under the terms of the BSD License. The full license is in
62 62 # the file COPYING, distributed as part of this software.
63 63 #
64 64 #*****************************************************************************
65 65
66 66 import __builtin__
67 67 import __main__
68 68 import glob
69 69 import keyword
70 70 import os
71 71 import re
72 72 import readline
73 73 import sys
74 74 import types
75 75
76 76 from IPython.genutils import shlex_split
77 77
78 78 __all__ = ['Completer','IPCompleter']
79 79
80 80 def get_class_members(cls):
81 81 ret = dir(cls)
82 82 if hasattr(cls,'__bases__'):
83 83 for base in cls.__bases__:
84 84 ret.extend(get_class_members(base))
85 85 return ret
86 86
87 87 class Completer:
88 88 def __init__(self,namespace=None,global_namespace=None):
89 89 """Create a new completer for the command line.
90 90
91 91 Completer([namespace,global_namespace]) -> completer instance.
92 92
93 93 If unspecified, the default namespace where completions are performed
94 94 is __main__ (technically, __main__.__dict__). Namespaces should be
95 95 given as dictionaries.
96 96
97 97 An optional second namespace can be given. This allows the completer
98 98 to handle cases where both the local and global scopes need to be
99 99 distinguished.
100 100
101 101 Completer instances should be used as the completion mechanism of
102 102 readline via the set_completer() call:
103 103
104 104 readline.set_completer(Completer(my_namespace).complete)
105 105 """
106
107 if namespace and type(namespace) != types.DictType:
108 raise TypeError,'namespace must be a dictionary'
109 106
110 if global_namespace and type(global_namespace) != types.DictType:
111 raise TypeError,'global_namespace must be a dictionary'
107 # some minimal strict typechecks. For some core data structures, I
108 # want actual basic python types, not just anything that looks like
109 # one. This is especially true for namespaces.
110 for ns in (namespace,global_namespace):
111 if ns is not None and type(ns) != types.DictType:
112 raise TypeError,'namespace must be a dictionary'
112 113
113 114 # Don't bind to namespace quite yet, but flag whether the user wants a
114 115 # specific namespace or to use __main__.__dict__. This will allow us
115 116 # to bind to __main__.__dict__ at completion time, not now.
116 117 if namespace is None:
117 118 self.use_main_ns = 1
118 119 else:
119 120 self.use_main_ns = 0
120 121 self.namespace = namespace
121 122
122 123 # The global namespace, if given, can be bound directly
123 124 if global_namespace is None:
124 125 self.global_namespace = {}
125 126 else:
126 127 self.global_namespace = global_namespace
127 128
128 129 def complete(self, text, state):
129 130 """Return the next possible completion for 'text'.
130 131
131 132 This is called successively with state == 0, 1, 2, ... until it
132 133 returns None. The completion should begin with 'text'.
133 134
134 135 """
135 136 if self.use_main_ns:
136 137 self.namespace = __main__.__dict__
137 138
138 139 if state == 0:
139 140 if "." in text:
140 141 self.matches = self.attr_matches(text)
141 142 else:
142 143 self.matches = self.global_matches(text)
143 144 try:
144 145 return self.matches[state]
145 146 except IndexError:
146 147 return None
147 148
148 149 def global_matches(self, text):
149 150 """Compute matches when text is a simple name.
150 151
151 152 Return a list of all keywords, built-in functions and names currently
152 153 defined in self.namespace or self.global_namespace that match.
153 154
154 155 """
155 156 matches = []
156 157 match_append = matches.append
157 158 n = len(text)
158 159 for lst in [keyword.kwlist,
159 160 __builtin__.__dict__.keys(),
160 161 self.namespace.keys(),
161 162 self.global_namespace.keys()]:
162 163 for word in lst:
163 164 if word[:n] == text and word != "__builtins__":
164 165 match_append(word)
165 166 return matches
166 167
167 168 def attr_matches(self, text):
168 169 """Compute matches when text contains a dot.
169 170
170 171 Assuming the text is of the form NAME.NAME....[NAME], and is
171 172 evaluatable in self.namespace or self.global_namespace, it will be
172 173 evaluated and its attributes (as revealed by dir()) are used as
173 174 possible completions. (For class instances, class members are are
174 175 also considered.)
175 176
176 177 WARNING: this can still invoke arbitrary C code, if an object
177 178 with a __getattr__ hook is evaluated.
178 179
179 180 """
180 181 import re
181 182
182 183 # Another option, seems to work great. Catches things like ''.<tab>
183 184 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
184 185
185 186 if not m:
186 187 return []
187 188 expr, attr = m.group(1, 3)
188 189 try:
189 190 object = eval(expr, self.namespace)
190 191 except:
191 192 object = eval(expr, self.global_namespace)
192 193 words = [w for w in dir(object) if isinstance(w, basestring)]
193 194 if hasattr(object,'__class__'):
194 195 words.append('__class__')
195 196 words.extend(get_class_members(object.__class__))
196 197 n = len(attr)
197 198 matches = []
198 199 for word in words:
199 200 if word[:n] == attr and word != "__builtins__":
200 201 matches.append("%s.%s" % (expr, word))
201 202 return matches
202 203
203 204 class IPCompleter(Completer):
204 205 """Extension of the completer class with IPython-specific features"""
205 206
206 207 def __init__(self,shell,namespace=None,global_namespace=None,
207 208 omit__names=0,alias_table=None):
208 209 """IPCompleter() -> completer
209 210
210 211 Return a completer object suitable for use by the readline library
211 212 via readline.set_completer().
212 213
213 214 Inputs:
214 215
215 216 - shell: a pointer to the ipython shell itself. This is needed
216 217 because this completer knows about magic functions, and those can
217 218 only be accessed via the ipython instance.
218 219
219 220 - namespace: an optional dict where completions are performed.
220 221
221 222 - global_namespace: secondary optional dict for completions, to
222 223 handle cases (such as IPython embedded inside functions) where
223 224 both Python scopes are visible.
224 225
225 226 - The optional omit__names parameter sets the completer to omit the
226 227 'magic' names (__magicname__) for python objects unless the text
227 228 to be completed explicitly starts with one or more underscores.
228 229
229 230 - If alias_table is supplied, it should be a dictionary of aliases
230 231 to complete. """
231 232
232 233 Completer.__init__(self,namespace,global_namespace)
233 234 self.magic_prefix = shell.name+'.magic_'
234 235 self.magic_escape = shell.ESC_MAGIC
235 236 self.readline = readline
236 237 delims = self.readline.get_completer_delims()
237 238 delims = delims.replace(self.magic_escape,'')
238 239 self.readline.set_completer_delims(delims)
239 240 self.get_line_buffer = self.readline.get_line_buffer
240 241 self.omit__names = omit__names
241 242 self.merge_completions = shell.rc.readline_merge_completions
242 243
243 244 if alias_table is None:
244 245 alias_table = {}
245 246 self.alias_table = alias_table
246 247 # Regexp to split filenames with spaces in them
247 248 self.space_name_re = re.compile(r'([^\\] )')
248 249 # Hold a local ref. to glob.glob for speed
249 250 self.glob = glob.glob
250 251 # Special handling of backslashes needed in win32 platforms
251 252 if sys.platform == "win32":
252 253 self.clean_glob = self._clean_glob_win32
253 254 else:
254 255 self.clean_glob = self._clean_glob
255 256 self.matchers = [self.python_matches,
256 257 self.file_matches,
257 258 self.alias_matches,
258 259 self.python_func_kw_matches]
259 260
260 261 # Code contributed by Alex Schmolck, for ipython/emacs integration
261 262 def all_completions(self, text):
262 263 """Return all possible completions for the benefit of emacs."""
263 264
264 265 completions = []
265 266 comp_append = completions.append
266 267 try:
267 268 for i in xrange(sys.maxint):
268 269 res = self.complete(text, i)
269 270
270 271 if not res: break
271 272
272 273 comp_append(res)
273 274 #XXX workaround for ``notDefined.<tab>``
274 275 except NameError:
275 276 pass
276 277 return completions
277 278 # /end Alex Schmolck code.
278 279
279 280 def _clean_glob(self,text):
280 281 return self.glob("%s*" % text)
281 282
282 283 def _clean_glob_win32(self,text):
283 284 return [f.replace("\\","/")
284 285 for f in self.glob("%s*" % text)]
285 286
286 287 def file_matches(self, text):
287 288 """Match filneames, expanding ~USER type strings.
288 289
289 290 Most of the seemingly convoluted logic in this completer is an
290 291 attempt to handle filenames with spaces in them. And yet it's not
291 292 quite perfect, because Python's readline doesn't expose all of the
292 293 GNU readline details needed for this to be done correctly.
293 294
294 295 For a filename with a space in it, the printed completions will be
295 296 only the parts after what's already been typed (instead of the
296 297 full completions, as is normally done). I don't think with the
297 298 current (as of Python 2.3) Python readline it's possible to do
298 299 better."""
299 300
300 301 #print 'Completer->file_matches: <%s>' % text # dbg
301 302
302 303 # chars that require escaping with backslash - i.e. chars
303 304 # that readline treats incorrectly as delimiters, but we
304 305 # don't want to treat as delimiters in filename matching
305 306 # when escaped with backslash
306 307
307 308 protectables = ' ()[]{}'
308 309
309 310 def protect_filename(s):
310 311 return "".join([(ch in protectables and '\\' + ch or ch)
311 312 for ch in s])
312 313
313 314 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
314 315 open_quotes = 0 # track strings with open quotes
315 316 try:
316 317 lsplit = shlex_split(lbuf)[-1]
317 318 except ValueError:
318 319 # typically an unmatched ", or backslash without escaped char.
319 320 if lbuf.count('"')==1:
320 321 open_quotes = 1
321 322 lsplit = lbuf.split('"')[-1]
322 323 elif lbuf.count("'")==1:
323 324 open_quotes = 1
324 325 lsplit = lbuf.split("'")[-1]
325 326 else:
326 327 return None
327 328 except IndexError:
328 329 # tab pressed on empty line
329 330 lsplit = ""
330 331
331 332 if lsplit != protect_filename(lsplit):
332 333 # if protectables are found, do matching on the whole escaped
333 334 # name
334 335 has_protectables = 1
335 336 text0,text = text,lsplit
336 337 else:
337 338 has_protectables = 0
338 339 text = os.path.expanduser(text)
339 340
340 341 if text == "":
341 342 return [protect_filename(f) for f in self.glob("*")]
342 343
343 344 m0 = self.clean_glob(text.replace('\\',''))
344 345 if has_protectables:
345 346 # If we had protectables, we need to revert our changes to the
346 347 # beginning of filename so that we don't double-write the part
347 348 # of the filename we have so far
348 349 len_lsplit = len(lsplit)
349 350 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
350 351 else:
351 352 if open_quotes:
352 353 # if we have a string with an open quote, we don't need to
353 354 # protect the names at all (and we _shouldn't_, as it
354 355 # would cause bugs when the filesystem call is made).
355 356 matches = m0
356 357 else:
357 358 matches = [protect_filename(f) for f in m0]
358 359 if len(matches) == 1 and os.path.isdir(matches[0]):
359 360 # Takes care of links to directories also. Use '/'
360 361 # explicitly, even under Windows, so that name completions
361 362 # don't end up escaped.
362 363 matches[0] += '/'
363 364 return matches
364 365
365 366 def alias_matches(self, text):
366 367 """Match internal system aliases"""
367 368 #print 'Completer->alias_matches:',text # dbg
368 369 text = os.path.expanduser(text)
369 370 aliases = self.alias_table.keys()
370 371 if text == "":
371 372 return aliases
372 373 else:
373 374 return [alias for alias in aliases if alias.startswith(text)]
374 375
375 376 def python_matches(self,text):
376 377 """Match attributes or global python names"""
377 378 #print 'Completer->python_matches' # dbg
378 379 if "." in text:
379 380 try:
380 381 matches = self.attr_matches(text)
381 382 if text.endswith('.') and self.omit__names:
382 383 if self.omit__names == 1:
383 384 # true if txt is _not_ a __ name, false otherwise:
384 385 no__name = (lambda txt:
385 386 re.match(r'.*\.__.*?__',txt) is None)
386 387 else:
387 388 # true if txt is _not_ a _ name, false otherwise:
388 389 no__name = (lambda txt:
389 390 re.match(r'.*\._.*?',txt) is None)
390 391 matches = filter(no__name, matches)
391 392 except NameError:
392 393 # catches <undefined attributes>.<tab>
393 394 matches = []
394 395 else:
395 396 matches = self.global_matches(text)
396 397 # this is so completion finds magics when automagic is on:
397 398 if matches == [] and not text.startswith(os.sep):
398 399 matches = self.attr_matches(self.magic_prefix+text)
399 400 return matches
400 401
401 402 def _default_arguments(self, obj):
402 403 """Return the list of default arguments of obj if it is callable,
403 404 or empty list otherwise."""
404 405
405 406 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
406 407 # for classes, check for __init__,__new__
407 408 if inspect.isclass(obj):
408 409 obj = (getattr(obj,'__init__',None) or
409 410 getattr(obj,'__new__',None))
410 411 # for all others, check if they are __call__able
411 412 elif hasattr(obj, '__call__'):
412 413 obj = obj.__call__
413 414 # XXX: is there a way to handle the builtins ?
414 415 try:
415 416 args,_,_1,defaults = inspect.getargspec(obj)
416 417 if defaults:
417 418 return args[-len(defaults):]
418 419 except TypeError: pass
419 420 return []
420 421
421 422 def python_func_kw_matches(self,text):
422 423 """Match named parameters (kwargs) of the last open function"""
423 424
424 425 if "." in text: # a parameter cannot be dotted
425 426 return []
426 427 try: regexp = self.__funcParamsRegex
427 428 except AttributeError:
428 429 regexp = self.__funcParamsRegex = re.compile(r'''
429 430 '.*?' | # single quoted strings or
430 431 ".*?" | # double quoted strings or
431 432 \w+ | # identifier
432 433 \S # other characters
433 434 ''', re.VERBOSE | re.DOTALL)
434 435 # 1. find the nearest identifier that comes before an unclosed
435 436 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
436 437 tokens = regexp.findall(self.get_line_buffer())
437 438 tokens.reverse()
438 439 iterTokens = iter(tokens); openPar = 0
439 440 for token in iterTokens:
440 441 if token == ')':
441 442 openPar -= 1
442 443 elif token == '(':
443 444 openPar += 1
444 445 if openPar > 0:
445 446 # found the last unclosed parenthesis
446 447 break
447 448 else:
448 449 return []
449 450 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
450 451 ids = []
451 452 isId = re.compile(r'\w+$').match
452 453 while True:
453 454 try:
454 455 ids.append(iterTokens.next())
455 456 if not isId(ids[-1]):
456 457 ids.pop(); break
457 458 if not iterTokens.next() == '.':
458 459 break
459 460 except StopIteration:
460 461 break
461 462 # lookup the candidate callable matches either using global_matches
462 463 # or attr_matches for dotted names
463 464 if len(ids) == 1:
464 465 callableMatches = self.global_matches(ids[0])
465 466 else:
466 467 callableMatches = self.attr_matches('.'.join(ids[::-1]))
467 468 argMatches = []
468 469 for callableMatch in callableMatches:
469 470 try: namedArgs = self._default_arguments(eval(callableMatch,
470 471 self.namespace))
471 472 except: continue
472 473 for namedArg in namedArgs:
473 474 if namedArg.startswith(text):
474 475 argMatches.append("%s=" %namedArg)
475 476 return argMatches
476 477
477 478 def complete(self, text, state):
478 479 """Return the next possible completion for 'text'.
479 480
480 481 This is called successively with state == 0, 1, 2, ... until it
481 482 returns None. The completion should begin with 'text'. """
482 483
483 484 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
484 485
485 486 # if there is only a tab on a line with only whitespace, instead
486 487 # of the mostly useless 'do you want to see all million
487 488 # completions' message, just do the right thing and give the user
488 489 # his tab! Incidentally, this enables pasting of tabbed text from
489 490 # an editor (as long as autoindent is off).
490 491 if not self.get_line_buffer().strip():
491 492 self.readline.insert_text('\t')
492 493 return None
493 494
494 495 magic_escape = self.magic_escape
495 496 magic_prefix = self.magic_prefix
496 497
497 498 try:
498 499 if text.startswith(magic_escape):
499 500 text = text.replace(magic_escape,magic_prefix)
500 501 elif text.startswith('~'):
501 502 text = os.path.expanduser(text)
502 503 if state == 0:
503 504 # Extend the list of completions with the results of each
504 505 # matcher, so we return results to the user from all
505 506 # namespaces.
506 507 if self.merge_completions:
507 508 self.matches = []
508 509 for matcher in self.matchers:
509 510 self.matches.extend(matcher(text))
510 511 else:
511 512 for matcher in self.matchers:
512 513 self.matches = matcher(text)
513 514 if self.matches:
514 515 break
515 516
516 517 try:
517 518 return self.matches[state].replace(magic_prefix,magic_escape)
518 519 except IndexError:
519 520 return None
520 521 except:
521 #import traceback; traceback.print_exc() # dbg
522 #from IPython.ultraTB import AutoFormattedTB; # dbg
523 #tb=AutoFormattedTB('Verbose');tb() #dbg
524
522 525 # If completion fails, don't annoy the user.
523 526 return None
@@ -1,1961 +1,1968 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 963 2005-12-28 19:21:29Z fperez $
9 $Id: iplib.py 964 2005-12-28 21:03:01Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from __future__ import generators # for 2.2 backwards-compatibility
32 32
33 33 from IPython import Release
34 34 __author__ = '%s <%s>\n%s <%s>' % \
35 35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 36 __license__ = Release.license
37 37 __version__ = Release.version
38 38
39 39 # Python standard modules
40 40 import __main__
41 41 import __builtin__
42 42 import StringIO
43 43 import bdb
44 44 import cPickle as pickle
45 45 import codeop
46 46 import exceptions
47 47 import glob
48 48 import inspect
49 49 import keyword
50 50 import new
51 51 import os
52 52 import pdb
53 53 import pydoc
54 54 import re
55 55 import shutil
56 56 import string
57 57 import sys
58 58 import traceback
59 59 import types
60 60
61 61 from pprint import pprint, pformat
62 62
63 63 # IPython's own modules
64 64 import IPython
65 65 from IPython import OInspect,PyColorize,ultraTB
66 66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
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,magic2python
71 71 from IPython.Struct import Struct
72 72 from IPython.background_jobs import BackgroundJobManager
73 73 from IPython.usage import cmd_line_usage,interactive_usage
74 74 from IPython.genutils import *
75 75
76 76 # store the builtin raw_input globally, and use this always, in case user code
77 77 # overwrites it (like wx.py.PyShell does)
78 78 raw_input_original = raw_input
79 79
80 80 #****************************************************************************
81 81 # Some utility function definitions
82 82
83 83 # This can be replaced with an isspace() call once we drop 2.2 compatibility
84 84 _isspace_match = re.compile(r'^\s+$').match
85 85 def isspace(s):
86 86 return bool(_isspace_match(s))
87 87
88 88 def esc_quotes(strng):
89 89 """Return the input string with single and double quotes escaped out"""
90 90
91 91 return strng.replace('"','\\"').replace("'","\\'")
92 92
93 93 def import_fail_info(mod_name,fns=None):
94 94 """Inform load failure for a module."""
95 95
96 96 if fns == None:
97 97 warn("Loading of %s failed.\n" % (mod_name,))
98 98 else:
99 99 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
100 100
101 101 def qw_lol(indata):
102 102 """qw_lol('a b') -> [['a','b']],
103 103 otherwise it's just a call to qw().
104 104
105 105 We need this to make sure the modules_some keys *always* end up as a
106 106 list of lists."""
107 107
108 108 if type(indata) in StringTypes:
109 109 return [qw(indata)]
110 110 else:
111 111 return qw(indata)
112 112
113 113 def ipmagic(arg_s):
114 114 """Call a magic function by name.
115 115
116 116 Input: a string containing the name of the magic function to call and any
117 117 additional arguments to be passed to the magic.
118 118
119 119 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
120 120 prompt:
121 121
122 122 In[1]: %name -opt foo bar
123 123
124 124 To call a magic without arguments, simply use ipmagic('name').
125 125
126 126 This provides a proper Python function to call IPython's magics in any
127 127 valid Python code you can type at the interpreter, including loops and
128 128 compound statements. It is added by IPython to the Python builtin
129 129 namespace upon initialization."""
130 130
131 131 args = arg_s.split(' ',1)
132 132 magic_name = args[0]
133 133 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
134 134 magic_name = magic_name[1:]
135 135 try:
136 136 magic_args = args[1]
137 137 except IndexError:
138 138 magic_args = ''
139 139 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
140 140 if fn is None:
141 141 error("Magic function `%s` not found." % magic_name)
142 142 else:
143 143 magic_args = __IPYTHON__.var_expand(magic_args)
144 144 return fn(magic_args)
145 145
146 146 def ipalias(arg_s):
147 147 """Call an alias by name.
148 148
149 149 Input: a string containing the name of the alias to call and any
150 150 additional arguments to be passed to the magic.
151 151
152 152 ipalias('name -opt foo bar') is equivalent to typing at the ipython
153 153 prompt:
154 154
155 155 In[1]: name -opt foo bar
156 156
157 157 To call an alias without arguments, simply use ipalias('name').
158 158
159 159 This provides a proper Python function to call IPython's aliases in any
160 160 valid Python code you can type at the interpreter, including loops and
161 161 compound statements. It is added by IPython to the Python builtin
162 162 namespace upon initialization."""
163 163
164 164 args = arg_s.split(' ',1)
165 165 alias_name = args[0]
166 166 try:
167 167 alias_args = args[1]
168 168 except IndexError:
169 169 alias_args = ''
170 170 if alias_name in __IPYTHON__.alias_table:
171 171 __IPYTHON__.call_alias(alias_name,alias_args)
172 172 else:
173 173 error("Alias `%s` not found." % alias_name)
174 174
175 175 def softspace(file, newvalue):
176 176 """Copied from code.py, to remove the dependency"""
177 177 oldvalue = 0
178 178 try:
179 179 oldvalue = file.softspace
180 180 except AttributeError:
181 181 pass
182 182 try:
183 183 file.softspace = newvalue
184 184 except (AttributeError, TypeError):
185 185 # "attribute-less object" or "read-only attributes"
186 186 pass
187 187 return oldvalue
188 188
189 189
190 190 #****************************************************************************
191 191 # Local use exceptions
192 192 class SpaceInInput(exceptions.Exception): pass
193 193
194 194 #****************************************************************************
195 195 # Local use classes
196 196 class Bunch: pass
197 197
198 198 class InputList(list):
199 199 """Class to store user input.
200 200
201 201 It's basically a list, but slices return a string instead of a list, thus
202 202 allowing things like (assuming 'In' is an instance):
203 203
204 204 exec In[4:7]
205 205
206 206 or
207 207
208 208 exec In[5:9] + In[14] + In[21:25]"""
209 209
210 210 def __getslice__(self,i,j):
211 211 return ''.join(list.__getslice__(self,i,j))
212 212
213 213 class SyntaxTB(ultraTB.ListTB):
214 214 """Extension which holds some state: the last exception value"""
215 215
216 216 def __init__(self,color_scheme = 'NoColor'):
217 217 ultraTB.ListTB.__init__(self,color_scheme)
218 218 self.last_syntax_error = None
219 219
220 220 def __call__(self, etype, value, elist):
221 221 self.last_syntax_error = value
222 222 ultraTB.ListTB.__call__(self,etype,value,elist)
223 223
224 224 def clear_err_state(self):
225 225 """Return the current error state and clear it"""
226 226 e = self.last_syntax_error
227 227 self.last_syntax_error = None
228 228 return e
229 229
230 230 #****************************************************************************
231 231 # Main IPython class
232 232 class InteractiveShell(Logger, Magic):
233 233 """An enhanced console for Python."""
234 234
235 235 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
236 236 user_ns = None,user_global_ns=None,banner2='',
237 237 custom_exceptions=((),None),embedded=False):
238 238
239 # some minimal strict typechecks. For some core data structures, I
240 # want actual basic python types, not just anything that looks like
241 # one. This is especially true for namespaces.
242 for ns in (user_ns,user_global_ns):
243 if ns is not None and type(ns) != types.DictType:
244 raise TypeError,'namespace must be a dictionary'
245
239 246 # Put a reference to self in builtins so that any form of embedded or
240 247 # imported code can test for being inside IPython.
241 248 __builtin__.__IPYTHON__ = self
242 249
243 250 # And load into builtins ipmagic/ipalias as well
244 251 __builtin__.ipmagic = ipmagic
245 252 __builtin__.ipalias = ipalias
246 253
247 254 # Add to __builtin__ other parts of IPython's public API
248 255 __builtin__.ip_set_hook = self.set_hook
249 256
250 257 # Keep in the builtins a flag for when IPython is active. We set it
251 258 # with setdefault so that multiple nested IPythons don't clobber one
252 259 # another. Each will increase its value by one upon being activated,
253 260 # which also gives us a way to determine the nesting level.
254 261 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
255 262
256 263 # Do the intuitively correct thing for quit/exit: we remove the
257 264 # builtins if they exist, and our own prefilter routine will handle
258 265 # these special cases
259 266 try:
260 267 del __builtin__.exit, __builtin__.quit
261 268 except AttributeError:
262 269 pass
263 270
264 271 # We need to know whether the instance is meant for embedding, since
265 272 # global/local namespaces need to be handled differently in that case
266 273 self.embedded = embedded
267 274
268 275 # command compiler
269 276 self.compile = codeop.CommandCompiler()
270 277
271 278 # User input buffer
272 279 self.buffer = []
273 280
274 281 # Default name given in compilation of code
275 282 self.filename = '<ipython console>'
276 283
277 284 # Create the namespace where the user will operate. user_ns is
278 285 # normally the only one used, and it is passed to the exec calls as
279 286 # the locals argument. But we do carry a user_global_ns namespace
280 287 # given as the exec 'globals' argument, This is useful in embedding
281 288 # situations where the ipython shell opens in a context where the
282 289 # distinction between locals and globals is meaningful.
283 290
284 291 # FIXME. For some strange reason, __builtins__ is showing up at user
285 292 # level as a dict instead of a module. This is a manual fix, but I
286 293 # should really track down where the problem is coming from. Alex
287 294 # Schmolck reported this problem first.
288 295
289 296 # A useful post by Alex Martelli on this topic:
290 297 # Re: inconsistent value from __builtins__
291 298 # Von: Alex Martelli <aleaxit@yahoo.com>
292 299 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
293 300 # Gruppen: comp.lang.python
294 301 # Referenzen: 1
295 302
296 303 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
297 304 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
298 305 # > <type 'dict'>
299 306 # > >>> print type(__builtins__)
300 307 # > <type 'module'>
301 308 # > Is this difference in return value intentional?
302 309
303 310 # Well, it's documented that '__builtins__' can be either a dictionary
304 311 # or a module, and it's been that way for a long time. Whether it's
305 312 # intentional (or sensible), I don't know. In any case, the idea is
306 313 # that if you need to access the built-in namespace directly, you
307 314 # should start with "import __builtin__" (note, no 's') which will
308 315 # definitely give you a module. Yeah, it's somewhat confusing:-(.
309 316
310 317 if user_ns is None:
311 318 # Set __name__ to __main__ to better match the behavior of the
312 319 # normal interpreter.
313 320 user_ns = {'__name__' :'__main__',
314 321 '__builtins__' : __builtin__,
315 322 }
316 323
317 324 if user_global_ns is None:
318 325 user_global_ns = {}
319 326
320 327 # Assign namespaces
321 328 # This is the namespace where all normal user variables live
322 329 self.user_ns = user_ns
323 330 # Embedded instances require a separate namespace for globals.
324 331 # Normally this one is unused by non-embedded instances.
325 332 self.user_global_ns = user_global_ns
326 333 # A namespace to keep track of internal data structures to prevent
327 334 # them from cluttering user-visible stuff. Will be updated later
328 335 self.internal_ns = {}
329 336
330 337 # Namespace of system aliases. Each entry in the alias
331 338 # table must be a 2-tuple of the form (N,name), where N is the number
332 339 # of positional arguments of the alias.
333 340 self.alias_table = {}
334 341
335 342 # A table holding all the namespaces IPython deals with, so that
336 343 # introspection facilities can search easily.
337 344 self.ns_table = {'user':user_ns,
338 345 'user_global':user_global_ns,
339 346 'alias':self.alias_table,
340 347 'internal':self.internal_ns,
341 348 'builtin':__builtin__.__dict__
342 349 }
343 350
344 351 # The user namespace MUST have a pointer to the shell itself.
345 352 self.user_ns[name] = self
346 353
347 354 # We need to insert into sys.modules something that looks like a
348 355 # module but which accesses the IPython namespace, for shelve and
349 356 # pickle to work interactively. Normally they rely on getting
350 357 # everything out of __main__, but for embedding purposes each IPython
351 358 # instance has its own private namespace, so we can't go shoving
352 359 # everything into __main__.
353 360
354 361 # note, however, that we should only do this for non-embedded
355 362 # ipythons, which really mimic the __main__.__dict__ with their own
356 363 # namespace. Embedded instances, on the other hand, should not do
357 364 # this because they need to manage the user local/global namespaces
358 365 # only, but they live within a 'normal' __main__ (meaning, they
359 366 # shouldn't overtake the execution environment of the script they're
360 367 # embedded in).
361 368
362 369 if not embedded:
363 370 try:
364 371 main_name = self.user_ns['__name__']
365 372 except KeyError:
366 373 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
367 374 else:
368 375 #print "pickle hack in place" # dbg
369 376 sys.modules[main_name] = FakeModule(self.user_ns)
370 377
371 378 # List of input with multi-line handling.
372 379 # Fill its zero entry, user counter starts at 1
373 380 self.input_hist = InputList(['\n'])
374 381
375 382 # list of visited directories
376 383 try:
377 384 self.dir_hist = [os.getcwd()]
378 385 except IOError, e:
379 386 self.dir_hist = []
380 387
381 388 # dict of output history
382 389 self.output_hist = {}
383 390
384 391 # dict of things NOT to alias (keywords, builtins and some magics)
385 392 no_alias = {}
386 393 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
387 394 for key in keyword.kwlist + no_alias_magics:
388 395 no_alias[key] = 1
389 396 no_alias.update(__builtin__.__dict__)
390 397 self.no_alias = no_alias
391 398
392 399 # make global variables for user access to these
393 400 self.user_ns['_ih'] = self.input_hist
394 401 self.user_ns['_oh'] = self.output_hist
395 402 self.user_ns['_dh'] = self.dir_hist
396 403
397 404 # user aliases to input and output histories
398 405 self.user_ns['In'] = self.input_hist
399 406 self.user_ns['Out'] = self.output_hist
400 407
401 408 # Store the actual shell's name
402 409 self.name = name
403 410
404 411 # Object variable to store code object waiting execution. This is
405 412 # used mainly by the multithreaded shells, but it can come in handy in
406 413 # other situations. No need to use a Queue here, since it's a single
407 414 # item which gets cleared once run.
408 415 self.code_to_run = None
409 416
410 417 # Job manager (for jobs run as background threads)
411 418 self.jobs = BackgroundJobManager()
412 419 # Put the job manager into builtins so it's always there.
413 420 __builtin__.jobs = self.jobs
414 421
415 422 # escapes for automatic behavior on the command line
416 423 self.ESC_SHELL = '!'
417 424 self.ESC_HELP = '?'
418 425 self.ESC_MAGIC = '%'
419 426 self.ESC_QUOTE = ','
420 427 self.ESC_QUOTE2 = ';'
421 428 self.ESC_PAREN = '/'
422 429
423 430 # And their associated handlers
424 431 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
425 432 self.ESC_QUOTE:self.handle_auto,
426 433 self.ESC_QUOTE2:self.handle_auto,
427 434 self.ESC_MAGIC:self.handle_magic,
428 435 self.ESC_HELP:self.handle_help,
429 436 self.ESC_SHELL:self.handle_shell_escape,
430 437 }
431 438
432 439 # class initializations
433 440 Logger.__init__(self,log_ns = self.user_ns)
434 441 Magic.__init__(self,self)
435 442
436 443 # an ugly hack to get a pointer to the shell, so I can start writing
437 444 # magic code via this pointer instead of the current mixin salad.
438 445 Magic.set_shell(self,self)
439 446
440 447 # Python source parser/formatter for syntax highlighting
441 448 pyformat = PyColorize.Parser().format
442 449 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
443 450
444 451 # hooks holds pointers used for user-side customizations
445 452 self.hooks = Struct()
446 453
447 454 # Set all default hooks, defined in the IPython.hooks module.
448 455 hooks = IPython.hooks
449 456 for hook_name in hooks.__all__:
450 457 self.set_hook(hook_name,getattr(hooks,hook_name))
451 458
452 459 # Flag to mark unconditional exit
453 460 self.exit_now = False
454 461
455 462 self.usage_min = """\
456 463 An enhanced console for Python.
457 464 Some of its features are:
458 465 - Readline support if the readline library is present.
459 466 - Tab completion in the local namespace.
460 467 - Logging of input, see command-line options.
461 468 - System shell escape via ! , eg !ls.
462 469 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
463 470 - Keeps track of locally defined variables via %who, %whos.
464 471 - Show object information with a ? eg ?x or x? (use ?? for more info).
465 472 """
466 473 if usage: self.usage = usage
467 474 else: self.usage = self.usage_min
468 475
469 476 # Storage
470 477 self.rc = rc # This will hold all configuration information
471 478 self.inputcache = []
472 479 self._boundcache = []
473 480 self.pager = 'less'
474 481 # temporary files used for various purposes. Deleted at exit.
475 482 self.tempfiles = []
476 483
477 484 # Keep track of readline usage (later set by init_readline)
478 485 self.has_readline = False
479 486
480 487 # for pushd/popd management
481 488 try:
482 489 self.home_dir = get_home_dir()
483 490 except HomeDirError,msg:
484 491 fatal(msg)
485 492
486 493 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
487 494
488 495 # Functions to call the underlying shell.
489 496
490 497 # utility to expand user variables via Itpl
491 498 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
492 499 self.user_ns))
493 500 # The first is similar to os.system, but it doesn't return a value,
494 501 # and it allows interpolation of variables in the user's namespace.
495 502 self.system = lambda cmd: shell(self.var_expand(cmd),
496 503 header='IPython system call: ',
497 504 verbose=self.rc.system_verbose)
498 505 # These are for getoutput and getoutputerror:
499 506 self.getoutput = lambda cmd: \
500 507 getoutput(self.var_expand(cmd),
501 508 header='IPython system call: ',
502 509 verbose=self.rc.system_verbose)
503 510 self.getoutputerror = lambda cmd: \
504 511 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
505 512 self.user_ns)),
506 513 header='IPython system call: ',
507 514 verbose=self.rc.system_verbose)
508 515
509 516 # RegExp for splitting line contents into pre-char//first
510 517 # word-method//rest. For clarity, each group in on one line.
511 518
512 519 # WARNING: update the regexp if the above escapes are changed, as they
513 520 # are hardwired in.
514 521
515 522 # Don't get carried away with trying to make the autocalling catch too
516 523 # much: it's better to be conservative rather than to trigger hidden
517 524 # evals() somewhere and end up causing side effects.
518 525
519 526 self.line_split = re.compile(r'^([\s*,;/])'
520 527 r'([\?\w\.]+\w*\s*)'
521 528 r'(\(?.*$)')
522 529
523 530 # Original re, keep around for a while in case changes break something
524 531 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
525 532 # r'(\s*[\?\w\.]+\w*\s*)'
526 533 # r'(\(?.*$)')
527 534
528 535 # RegExp to identify potential function names
529 536 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
530 537 # RegExp to exclude strings with this start from autocalling
531 538 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
532 539
533 540 # try to catch also methods for stuff in lists/tuples/dicts: off
534 541 # (experimental). For this to work, the line_split regexp would need
535 542 # to be modified so it wouldn't break things at '['. That line is
536 543 # nasty enough that I shouldn't change it until I can test it _well_.
537 544 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
538 545
539 546 # keep track of where we started running (mainly for crash post-mortem)
540 547 self.starting_dir = os.getcwd()
541 548
542 549 # Attributes for Logger mixin class, make defaults here
543 550 self._dolog = False
544 551 self.LOG = ''
545 552 self.LOGDEF = '.InteractiveShell.log'
546 553 self.LOGMODE = 'over'
547 554 self.LOGHEAD = Itpl(
548 555 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
549 556 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
550 557 #log# opts = $self.rc.opts
551 558 #log# args = $self.rc.args
552 559 #log# It is safe to make manual edits below here.
553 560 #log#-----------------------------------------------------------------------
554 561 """)
555 562 # Various switches which can be set
556 563 self.CACHELENGTH = 5000 # this is cheap, it's just text
557 564 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
558 565 self.banner2 = banner2
559 566
560 567 # TraceBack handlers:
561 568 # Need two, one for syntax errors and one for other exceptions.
562 569 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
563 570 # The interactive one is initialized with an offset, meaning we always
564 571 # want to remove the topmost item in the traceback, which is our own
565 572 # internal code. Valid modes: ['Plain','Context','Verbose']
566 573 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
567 574 color_scheme='NoColor',
568 575 tb_offset = 1)
569 576 # and add any custom exception handlers the user may have specified
570 577 self.set_custom_exc(*custom_exceptions)
571 578
572 579 # Object inspector
573 580 self.inspector = OInspect.Inspector(OInspect.InspectColors,
574 581 PyColorize.ANSICodeColors,
575 582 'NoColor')
576 583 # indentation management
577 584 self.autoindent = False
578 585 self.indent_current_nsp = 0
579 586 self.indent_current = '' # actual indent string
580 587
581 588 # Make some aliases automatically
582 589 # Prepare list of shell aliases to auto-define
583 590 if os.name == 'posix':
584 591 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
585 592 'mv mv -i','rm rm -i','cp cp -i',
586 593 'cat cat','less less','clear clear',
587 594 # a better ls
588 595 'ls ls -F',
589 596 # long ls
590 597 'll ls -lF',
591 598 # color ls
592 599 'lc ls -F -o --color',
593 600 # ls normal files only
594 601 'lf ls -F -o --color %l | grep ^-',
595 602 # ls symbolic links
596 603 'lk ls -F -o --color %l | grep ^l',
597 604 # directories or links to directories,
598 605 'ldir ls -F -o --color %l | grep /$',
599 606 # things which are executable
600 607 'lx ls -F -o --color %l | grep ^-..x',
601 608 )
602 609 elif os.name in ['nt','dos']:
603 610 auto_alias = ('dir dir /on', 'ls dir /on',
604 611 'ddir dir /ad /on', 'ldir dir /ad /on',
605 612 'mkdir mkdir','rmdir rmdir','echo echo',
606 613 'ren ren','cls cls','copy copy')
607 614 else:
608 615 auto_alias = ()
609 616 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
610 617 # Call the actual (public) initializer
611 618 self.init_auto_alias()
612 619 # end __init__
613 620
614 621 def set_hook(self,name,hook):
615 622 """set_hook(name,hook) -> sets an internal IPython hook.
616 623
617 624 IPython exposes some of its internal API as user-modifiable hooks. By
618 625 resetting one of these hooks, you can modify IPython's behavior to
619 626 call at runtime your own routines."""
620 627
621 628 # At some point in the future, this should validate the hook before it
622 629 # accepts it. Probably at least check that the hook takes the number
623 630 # of args it's supposed to.
624 631 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
625 632
626 633 def set_custom_exc(self,exc_tuple,handler):
627 634 """set_custom_exc(exc_tuple,handler)
628 635
629 636 Set a custom exception handler, which will be called if any of the
630 637 exceptions in exc_tuple occur in the mainloop (specifically, in the
631 638 runcode() method.
632 639
633 640 Inputs:
634 641
635 642 - exc_tuple: a *tuple* of valid exceptions to call the defined
636 643 handler for. It is very important that you use a tuple, and NOT A
637 644 LIST here, because of the way Python's except statement works. If
638 645 you only want to trap a single exception, use a singleton tuple:
639 646
640 647 exc_tuple == (MyCustomException,)
641 648
642 649 - handler: this must be defined as a function with the following
643 650 basic interface: def my_handler(self,etype,value,tb).
644 651
645 652 This will be made into an instance method (via new.instancemethod)
646 653 of IPython itself, and it will be called if any of the exceptions
647 654 listed in the exc_tuple are caught. If the handler is None, an
648 655 internal basic one is used, which just prints basic info.
649 656
650 657 WARNING: by putting in your own exception handler into IPython's main
651 658 execution loop, you run a very good chance of nasty crashes. This
652 659 facility should only be used if you really know what you are doing."""
653 660
654 661 assert type(exc_tuple)==type(()) , \
655 662 "The custom exceptions must be given AS A TUPLE."
656 663
657 664 def dummy_handler(self,etype,value,tb):
658 665 print '*** Simple custom exception handler ***'
659 666 print 'Exception type :',etype
660 667 print 'Exception value:',value
661 668 print 'Traceback :',tb
662 669 print 'Source code :','\n'.join(self.buffer)
663 670
664 671 if handler is None: handler = dummy_handler
665 672
666 673 self.CustomTB = new.instancemethod(handler,self,self.__class__)
667 674 self.custom_exceptions = exc_tuple
668 675
669 676 def set_custom_completer(self,completer,pos=0):
670 677 """set_custom_completer(completer,pos=0)
671 678
672 679 Adds a new custom completer function.
673 680
674 681 The position argument (defaults to 0) is the index in the completers
675 682 list where you want the completer to be inserted."""
676 683
677 684 newcomp = new.instancemethod(completer,self.Completer,
678 685 self.Completer.__class__)
679 686 self.Completer.matchers.insert(pos,newcomp)
680 687
681 688 def complete(self,text):
682 689 """Return a sorted list of all possible completions on text.
683 690
684 691 Inputs:
685 692
686 693 - text: a string of text to be completed on.
687 694
688 695 This is a wrapper around the completion mechanism, similar to what
689 696 readline does at the command line when the TAB key is hit. By
690 697 exposing it as a method, it can be used by other non-readline
691 698 environments (such as GUIs) for text completion.
692 699
693 700 Simple usage example:
694 701
695 702 In [1]: x = 'hello'
696 703
697 704 In [2]: __IP.complete('x.l')
698 705 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
699 706
700 707 complete = self.Completer.complete
701 708 state = 0
702 709 # use a dict so we get unique keys, since ipyhton's multiple
703 710 # completers can return duplicates.
704 711 comps = {}
705 712 while True:
706 713 newcomp = complete(text,state)
707 714 if newcomp is None:
708 715 break
709 716 comps[newcomp] = 1
710 717 state += 1
711 718 outcomps = comps.keys()
712 719 outcomps.sort()
713 720 return outcomps
714 721
715 722 def set_completer_frame(self, frame):
716 723 if frame:
717 724 self.Completer.namespace = frame.f_locals
718 725 self.Completer.global_namespace = frame.f_globals
719 726 else:
720 727 self.Completer.namespace = self.user_ns
721 728 self.Completer.global_namespace = self.user_global_ns
722 729
723 730 def post_config_initialization(self):
724 731 """Post configuration init method
725 732
726 733 This is called after the configuration files have been processed to
727 734 'finalize' the initialization."""
728 735
729 736 rc = self.rc
730 737
731 738 # Load readline proper
732 739 if rc.readline:
733 740 self.init_readline()
734 741
735 742 # Set user colors (don't do it in the constructor above so that it
736 743 # doesn't crash if colors option is invalid)
737 744 self.magic_colors(rc.colors)
738 745
739 746 # Load user aliases
740 747 for alias in rc.alias:
741 748 self.magic_alias(alias)
742 749
743 750 # dynamic data that survives through sessions
744 751 # XXX make the filename a config option?
745 752 persist_base = 'persist'
746 753 if rc.profile:
747 754 persist_base += '_%s' % rc.profile
748 755 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
749 756
750 757 try:
751 758 self.persist = pickle.load(file(self.persist_fname))
752 759 except:
753 760 self.persist = {}
754 761
755 762 def init_auto_alias(self):
756 763 """Define some aliases automatically.
757 764
758 765 These are ALL parameter-less aliases"""
759 766 for alias,cmd in self.auto_alias:
760 767 self.alias_table[alias] = (0,cmd)
761 768
762 769 def alias_table_validate(self,verbose=0):
763 770 """Update information about the alias table.
764 771
765 772 In particular, make sure no Python keywords/builtins are in it."""
766 773
767 774 no_alias = self.no_alias
768 775 for k in self.alias_table.keys():
769 776 if k in no_alias:
770 777 del self.alias_table[k]
771 778 if verbose:
772 779 print ("Deleting alias <%s>, it's a Python "
773 780 "keyword or builtin." % k)
774 781
775 782 def set_autoindent(self,value=None):
776 783 """Set the autoindent flag, checking for readline support.
777 784
778 785 If called with no arguments, it acts as a toggle."""
779 786
780 787 if not self.has_readline:
781 788 if os.name == 'posix':
782 789 warn("The auto-indent feature requires the readline library")
783 790 self.autoindent = 0
784 791 return
785 792 if value is None:
786 793 self.autoindent = not self.autoindent
787 794 else:
788 795 self.autoindent = value
789 796
790 797 def rc_set_toggle(self,rc_field,value=None):
791 798 """Set or toggle a field in IPython's rc config. structure.
792 799
793 800 If called with no arguments, it acts as a toggle.
794 801
795 802 If called with a non-existent field, the resulting AttributeError
796 803 exception will propagate out."""
797 804
798 805 rc_val = getattr(self.rc,rc_field)
799 806 if value is None:
800 807 value = not rc_val
801 808 setattr(self.rc,rc_field,value)
802 809
803 810 def user_setup(self,ipythondir,rc_suffix,mode='install'):
804 811 """Install the user configuration directory.
805 812
806 813 Can be called when running for the first time or to upgrade the user's
807 814 .ipython/ directory with the mode parameter. Valid modes are 'install'
808 815 and 'upgrade'."""
809 816
810 817 def wait():
811 818 try:
812 819 raw_input("Please press <RETURN> to start IPython.")
813 820 except EOFError:
814 821 print >> Term.cout
815 822 print '*'*70
816 823
817 824 cwd = os.getcwd() # remember where we started
818 825 glb = glob.glob
819 826 print '*'*70
820 827 if mode == 'install':
821 828 print \
822 829 """Welcome to IPython. I will try to create a personal configuration directory
823 830 where you can customize many aspects of IPython's functionality in:\n"""
824 831 else:
825 832 print 'I am going to upgrade your configuration in:'
826 833
827 834 print ipythondir
828 835
829 836 rcdirend = os.path.join('IPython','UserConfig')
830 837 cfg = lambda d: os.path.join(d,rcdirend)
831 838 try:
832 839 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
833 840 except IOError:
834 841 warning = """
835 842 Installation error. IPython's directory was not found.
836 843
837 844 Check the following:
838 845
839 846 The ipython/IPython directory should be in a directory belonging to your
840 847 PYTHONPATH environment variable (that is, it should be in a directory
841 848 belonging to sys.path). You can copy it explicitly there or just link to it.
842 849
843 850 IPython will proceed with builtin defaults.
844 851 """
845 852 warn(warning)
846 853 wait()
847 854 return
848 855
849 856 if mode == 'install':
850 857 try:
851 858 shutil.copytree(rcdir,ipythondir)
852 859 os.chdir(ipythondir)
853 860 rc_files = glb("ipythonrc*")
854 861 for rc_file in rc_files:
855 862 os.rename(rc_file,rc_file+rc_suffix)
856 863 except:
857 864 warning = """
858 865
859 866 There was a problem with the installation:
860 867 %s
861 868 Try to correct it or contact the developers if you think it's a bug.
862 869 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
863 870 warn(warning)
864 871 wait()
865 872 return
866 873
867 874 elif mode == 'upgrade':
868 875 try:
869 876 os.chdir(ipythondir)
870 877 except:
871 878 print """
872 879 Can not upgrade: changing to directory %s failed. Details:
873 880 %s
874 881 """ % (ipythondir,sys.exc_info()[1])
875 882 wait()
876 883 return
877 884 else:
878 885 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
879 886 for new_full_path in sources:
880 887 new_filename = os.path.basename(new_full_path)
881 888 if new_filename.startswith('ipythonrc'):
882 889 new_filename = new_filename + rc_suffix
883 890 # The config directory should only contain files, skip any
884 891 # directories which may be there (like CVS)
885 892 if os.path.isdir(new_full_path):
886 893 continue
887 894 if os.path.exists(new_filename):
888 895 old_file = new_filename+'.old'
889 896 if os.path.exists(old_file):
890 897 os.remove(old_file)
891 898 os.rename(new_filename,old_file)
892 899 shutil.copy(new_full_path,new_filename)
893 900 else:
894 901 raise ValueError,'unrecognized mode for install:',`mode`
895 902
896 903 # Fix line-endings to those native to each platform in the config
897 904 # directory.
898 905 try:
899 906 os.chdir(ipythondir)
900 907 except:
901 908 print """
902 909 Problem: changing to directory %s failed.
903 910 Details:
904 911 %s
905 912
906 913 Some configuration files may have incorrect line endings. This should not
907 914 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
908 915 wait()
909 916 else:
910 917 for fname in glb('ipythonrc*'):
911 918 try:
912 919 native_line_ends(fname,backup=0)
913 920 except IOError:
914 921 pass
915 922
916 923 if mode == 'install':
917 924 print """
918 925 Successful installation!
919 926
920 927 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
921 928 IPython manual (there are both HTML and PDF versions supplied with the
922 929 distribution) to make sure that your system environment is properly configured
923 930 to take advantage of IPython's features."""
924 931 else:
925 932 print """
926 933 Successful upgrade!
927 934
928 935 All files in your directory:
929 936 %(ipythondir)s
930 937 which would have been overwritten by the upgrade were backed up with a .old
931 938 extension. If you had made particular customizations in those files you may
932 939 want to merge them back into the new files.""" % locals()
933 940 wait()
934 941 os.chdir(cwd)
935 942 # end user_setup()
936 943
937 944 def atexit_operations(self):
938 945 """This will be executed at the time of exit.
939 946
940 947 Saving of persistent data should be performed here. """
941 948
942 949 # input history
943 950 self.savehist()
944 951
945 952 # Cleanup all tempfiles left around
946 953 for tfile in self.tempfiles:
947 954 try:
948 955 os.unlink(tfile)
949 956 except OSError:
950 957 pass
951 958
952 959 # save the "persistent data" catch-all dictionary
953 960 try:
954 961 pickle.dump(self.persist, open(self.persist_fname,"w"))
955 962 except:
956 963 print "*** ERROR *** persistent data saving failed."
957 964
958 965 def savehist(self):
959 966 """Save input history to a file (via readline library)."""
960 967 try:
961 968 self.readline.write_history_file(self.histfile)
962 969 except:
963 970 print 'Unable to save IPython command history to file: ' + \
964 971 `self.histfile`
965 972
966 973 def pre_readline(self):
967 974 """readline hook to be used at the start of each line.
968 975
969 976 Currently it handles auto-indent only."""
970 977
971 978 self.readline.insert_text(self.indent_current)
972 979
973 980 def init_readline(self):
974 981 """Command history completion/saving/reloading."""
975 982 try:
976 983 import readline
977 984 except ImportError:
978 985 self.has_readline = 0
979 986 self.readline = None
980 987 # no point in bugging windows users with this every time:
981 988 if os.name == 'posix':
982 989 warn('Readline services not available on this platform.')
983 990 else:
984 991 import atexit
985 992 from IPython.completer import IPCompleter
986 993 self.Completer = IPCompleter(self,
987 994 self.user_ns,
988 995 self.user_global_ns,
989 996 self.rc.readline_omit__names,
990 997 self.alias_table)
991 998
992 999 # Platform-specific configuration
993 1000 if os.name == 'nt':
994 1001 self.readline_startup_hook = readline.set_pre_input_hook
995 1002 else:
996 1003 self.readline_startup_hook = readline.set_startup_hook
997 1004
998 1005 # Load user's initrc file (readline config)
999 1006 inputrc_name = os.environ.get('INPUTRC')
1000 1007 if inputrc_name is None:
1001 1008 home_dir = get_home_dir()
1002 1009 if home_dir is not None:
1003 1010 inputrc_name = os.path.join(home_dir,'.inputrc')
1004 1011 if os.path.isfile(inputrc_name):
1005 1012 try:
1006 1013 readline.read_init_file(inputrc_name)
1007 1014 except:
1008 1015 warn('Problems reading readline initialization file <%s>'
1009 1016 % inputrc_name)
1010 1017
1011 1018 self.has_readline = 1
1012 1019 self.readline = readline
1013 1020 # save this in sys so embedded copies can restore it properly
1014 1021 sys.ipcompleter = self.Completer.complete
1015 1022 readline.set_completer(self.Completer.complete)
1016 1023
1017 1024 # Configure readline according to user's prefs
1018 1025 for rlcommand in self.rc.readline_parse_and_bind:
1019 1026 readline.parse_and_bind(rlcommand)
1020 1027
1021 1028 # remove some chars from the delimiters list
1022 1029 delims = readline.get_completer_delims()
1023 1030 delims = delims.translate(string._idmap,
1024 1031 self.rc.readline_remove_delims)
1025 1032 readline.set_completer_delims(delims)
1026 1033 # otherwise we end up with a monster history after a while:
1027 1034 readline.set_history_length(1000)
1028 1035 try:
1029 1036 #print '*** Reading readline history' # dbg
1030 1037 readline.read_history_file(self.histfile)
1031 1038 except IOError:
1032 1039 pass # It doesn't exist yet.
1033 1040
1034 1041 atexit.register(self.atexit_operations)
1035 1042 del atexit
1036 1043
1037 1044 # Configure auto-indent for all platforms
1038 1045 self.set_autoindent(self.rc.autoindent)
1039 1046
1040 1047 def _should_recompile(self,e):
1041 1048 """Utility routine for edit_syntax_error"""
1042 1049
1043 1050 if e.filename in ('<ipython console>','<input>','<string>',
1044 1051 '<console>'):
1045 1052 return False
1046 1053 try:
1047 1054 if not ask_yes_no('Return to editor to correct syntax error? '
1048 1055 '[Y/n] ','y'):
1049 1056 return False
1050 1057 except EOFError:
1051 1058 return False
1052 1059 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1053 1060 return True
1054 1061
1055 1062 def edit_syntax_error(self):
1056 1063 """The bottom half of the syntax error handler called in the main loop.
1057 1064
1058 1065 Loop until syntax error is fixed or user cancels.
1059 1066 """
1060 1067
1061 1068 while self.SyntaxTB.last_syntax_error:
1062 1069 # copy and clear last_syntax_error
1063 1070 err = self.SyntaxTB.clear_err_state()
1064 1071 if not self._should_recompile(err):
1065 1072 return
1066 1073 try:
1067 1074 # may set last_syntax_error again if a SyntaxError is raised
1068 1075 self.safe_execfile(err.filename,self.shell.user_ns)
1069 1076 except:
1070 1077 self.showtraceback()
1071 1078 else:
1072 1079 f = file(err.filename)
1073 1080 try:
1074 1081 sys.displayhook(f.read())
1075 1082 finally:
1076 1083 f.close()
1077 1084
1078 1085 def showsyntaxerror(self, filename=None):
1079 1086 """Display the syntax error that just occurred.
1080 1087
1081 1088 This doesn't display a stack trace because there isn't one.
1082 1089
1083 1090 If a filename is given, it is stuffed in the exception instead
1084 1091 of what was there before (because Python's parser always uses
1085 1092 "<string>" when reading from a string).
1086 1093 """
1087 1094 type, value, sys.last_traceback = sys.exc_info()
1088 1095 sys.last_type = type
1089 1096 sys.last_value = value
1090 1097 if filename and type is SyntaxError:
1091 1098 # Work hard to stuff the correct filename in the exception
1092 1099 try:
1093 1100 msg, (dummy_filename, lineno, offset, line) = value
1094 1101 except:
1095 1102 # Not the format we expect; leave it alone
1096 1103 pass
1097 1104 else:
1098 1105 # Stuff in the right filename
1099 1106 try:
1100 1107 # Assume SyntaxError is a class exception
1101 1108 value = SyntaxError(msg, (filename, lineno, offset, line))
1102 1109 except:
1103 1110 # If that failed, assume SyntaxError is a string
1104 1111 value = msg, (filename, lineno, offset, line)
1105 1112 self.SyntaxTB(type,value,[])
1106 1113
1107 1114 def debugger(self):
1108 1115 """Call the pdb debugger."""
1109 1116
1110 1117 if not self.rc.pdb:
1111 1118 return
1112 1119 pdb.pm()
1113 1120
1114 1121 def showtraceback(self,exc_tuple = None,filename=None):
1115 1122 """Display the exception that just occurred."""
1116 1123
1117 1124 # Though this won't be called by syntax errors in the input line,
1118 1125 # there may be SyntaxError cases whith imported code.
1119 1126 if exc_tuple is None:
1120 1127 type, value, tb = sys.exc_info()
1121 1128 else:
1122 1129 type, value, tb = exc_tuple
1123 1130 if type is SyntaxError:
1124 1131 self.showsyntaxerror(filename)
1125 1132 else:
1126 1133 sys.last_type = type
1127 1134 sys.last_value = value
1128 1135 sys.last_traceback = tb
1129 1136 self.InteractiveTB()
1130 1137 if self.InteractiveTB.call_pdb and self.has_readline:
1131 1138 # pdb mucks up readline, fix it back
1132 1139 self.readline.set_completer(self.Completer.complete)
1133 1140
1134 1141 def update_cache(self, line):
1135 1142 """puts line into cache"""
1136 1143 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1137 1144 if len(self.inputcache) >= self.CACHELENGTH:
1138 1145 self.inputcache.pop() # This doesn't :-)
1139 1146
1140 1147 def mainloop(self,banner=None):
1141 1148 """Creates the local namespace and starts the mainloop.
1142 1149
1143 1150 If an optional banner argument is given, it will override the
1144 1151 internally created default banner."""
1145 1152
1146 1153 if self.rc.c: # Emulate Python's -c option
1147 1154 self.exec_init_cmd()
1148 1155 if banner is None:
1149 1156 if self.rc.banner:
1150 1157 banner = self.BANNER+self.banner2
1151 1158 else:
1152 1159 banner = ''
1153 1160 self.interact(banner)
1154 1161
1155 1162 def exec_init_cmd(self):
1156 1163 """Execute a command given at the command line.
1157 1164
1158 1165 This emulates Python's -c option."""
1159 1166
1160 1167 sys.argv = ['-c']
1161 1168 self.push(self.rc.c)
1162 1169
1163 1170 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1164 1171 """Embeds IPython into a running python program.
1165 1172
1166 1173 Input:
1167 1174
1168 1175 - header: An optional header message can be specified.
1169 1176
1170 1177 - local_ns, global_ns: working namespaces. If given as None, the
1171 1178 IPython-initialized one is updated with __main__.__dict__, so that
1172 1179 program variables become visible but user-specific configuration
1173 1180 remains possible.
1174 1181
1175 1182 - stack_depth: specifies how many levels in the stack to go to
1176 1183 looking for namespaces (when local_ns and global_ns are None). This
1177 1184 allows an intermediate caller to make sure that this function gets
1178 1185 the namespace from the intended level in the stack. By default (0)
1179 1186 it will get its locals and globals from the immediate caller.
1180 1187
1181 1188 Warning: it's possible to use this in a program which is being run by
1182 1189 IPython itself (via %run), but some funny things will happen (a few
1183 1190 globals get overwritten). In the future this will be cleaned up, as
1184 1191 there is no fundamental reason why it can't work perfectly."""
1185 1192
1186 1193 # Get locals and globals from caller
1187 1194 if local_ns is None or global_ns is None:
1188 1195 call_frame = sys._getframe(stack_depth).f_back
1189 1196
1190 1197 if local_ns is None:
1191 1198 local_ns = call_frame.f_locals
1192 1199 if global_ns is None:
1193 1200 global_ns = call_frame.f_globals
1194 1201
1195 1202 # Update namespaces and fire up interpreter
1196 1203 self.user_ns = local_ns
1197 1204 self.user_global_ns = global_ns
1198 1205
1199 1206 # Patch for global embedding to make sure that things don't overwrite
1200 1207 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1201 1208 # FIXME. Test this a bit more carefully (the if.. is new)
1202 1209 if local_ns is None and global_ns is None:
1203 1210 self.user_global_ns.update(__main__.__dict__)
1204 1211
1205 1212 # make sure the tab-completer has the correct frame information, so it
1206 1213 # actually completes using the frame's locals/globals
1207 1214 self.set_completer_frame(call_frame)
1208 1215
1209 1216 self.interact(header)
1210 1217
1211 1218 def interact(self, banner=None):
1212 1219 """Closely emulate the interactive Python console.
1213 1220
1214 1221 The optional banner argument specify the banner to print
1215 1222 before the first interaction; by default it prints a banner
1216 1223 similar to the one printed by the real Python interpreter,
1217 1224 followed by the current class name in parentheses (so as not
1218 1225 to confuse this with the real interpreter -- since it's so
1219 1226 close!).
1220 1227
1221 1228 """
1222 1229 cprt = 'Type "copyright", "credits" or "license" for more information.'
1223 1230 if banner is None:
1224 1231 self.write("Python %s on %s\n%s\n(%s)\n" %
1225 1232 (sys.version, sys.platform, cprt,
1226 1233 self.__class__.__name__))
1227 1234 else:
1228 1235 self.write(banner)
1229 1236
1230 1237 more = 0
1231 1238
1232 1239 # Mark activity in the builtins
1233 1240 __builtin__.__dict__['__IPYTHON__active'] += 1
1234 1241
1235 1242 # compiled regexps for autoindent management
1236 1243 ini_spaces_re = re.compile(r'^(\s+)')
1237 1244 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
1238 1245
1239 1246 # exit_now is set by a call to %Exit or %Quit
1240 1247 while not self.exit_now:
1241 1248 try:
1242 1249 if more:
1243 1250 prompt = self.outputcache.prompt2
1244 1251 if self.autoindent:
1245 1252 self.readline_startup_hook(self.pre_readline)
1246 1253 else:
1247 1254 prompt = self.outputcache.prompt1
1248 1255 try:
1249 1256 line = self.raw_input(prompt,more)
1250 1257 if self.autoindent:
1251 1258 self.readline_startup_hook(None)
1252 1259 except EOFError:
1253 1260 if self.autoindent:
1254 1261 self.readline_startup_hook(None)
1255 1262 self.write("\n")
1256 1263 self.exit()
1257 1264 else:
1258 1265 more = self.push(line)
1259 1266 # Auto-indent management
1260 1267 if self.autoindent:
1261 1268 if line:
1262 1269 ini_spaces = ini_spaces_re.match(line)
1263 1270 if ini_spaces:
1264 1271 nspaces = ini_spaces.end()
1265 1272 else:
1266 1273 nspaces = 0
1267 1274 self.indent_current_nsp = nspaces
1268 1275
1269 1276 if line[-1] == ':':
1270 1277 self.indent_current_nsp += 4
1271 1278 elif dedent_re.match(line):
1272 1279 self.indent_current_nsp -= 4
1273 1280 else:
1274 1281 self.indent_current_nsp = 0
1275 1282
1276 1283 # indent_current is the actual string to be inserted
1277 1284 # by the readline hooks for indentation
1278 1285 self.indent_current = ' '* self.indent_current_nsp
1279 1286
1280 1287 if (self.SyntaxTB.last_syntax_error and
1281 1288 self.rc.autoedit_syntax):
1282 1289 self.edit_syntax_error()
1283 1290
1284 1291 except KeyboardInterrupt:
1285 1292 self.write("\nKeyboardInterrupt\n")
1286 1293 self.resetbuffer()
1287 1294 more = 0
1288 1295 # keep cache in sync with the prompt counter:
1289 1296 self.outputcache.prompt_count -= 1
1290 1297
1291 1298 if self.autoindent:
1292 1299 self.indent_current_nsp = 0
1293 1300 self.indent_current = ' '* self.indent_current_nsp
1294 1301
1295 1302 except bdb.BdbQuit:
1296 1303 warn("The Python debugger has exited with a BdbQuit exception.\n"
1297 1304 "Because of how pdb handles the stack, it is impossible\n"
1298 1305 "for IPython to properly format this particular exception.\n"
1299 1306 "IPython will resume normal operation.")
1300 1307
1301 1308 # We are off again...
1302 1309 __builtin__.__dict__['__IPYTHON__active'] -= 1
1303 1310
1304 1311 def excepthook(self, type, value, tb):
1305 1312 """One more defense for GUI apps that call sys.excepthook.
1306 1313
1307 1314 GUI frameworks like wxPython trap exceptions and call
1308 1315 sys.excepthook themselves. I guess this is a feature that
1309 1316 enables them to keep running after exceptions that would
1310 1317 otherwise kill their mainloop. This is a bother for IPython
1311 1318 which excepts to catch all of the program exceptions with a try:
1312 1319 except: statement.
1313 1320
1314 1321 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1315 1322 any app directly invokes sys.excepthook, it will look to the user like
1316 1323 IPython crashed. In order to work around this, we can disable the
1317 1324 CrashHandler and replace it with this excepthook instead, which prints a
1318 1325 regular traceback using our InteractiveTB. In this fashion, apps which
1319 1326 call sys.excepthook will generate a regular-looking exception from
1320 1327 IPython, and the CrashHandler will only be triggered by real IPython
1321 1328 crashes.
1322 1329
1323 1330 This hook should be used sparingly, only in places which are not likely
1324 1331 to be true IPython errors.
1325 1332 """
1326 1333
1327 1334 self.InteractiveTB(type, value, tb, tb_offset=0)
1328 1335 if self.InteractiveTB.call_pdb and self.has_readline:
1329 1336 self.readline.set_completer(self.Completer.complete)
1330 1337
1331 1338 def call_alias(self,alias,rest=''):
1332 1339 """Call an alias given its name and the rest of the line.
1333 1340
1334 1341 This function MUST be given a proper alias, because it doesn't make
1335 1342 any checks when looking up into the alias table. The caller is
1336 1343 responsible for invoking it only with a valid alias."""
1337 1344
1338 1345 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1339 1346 nargs,cmd = self.alias_table[alias]
1340 1347 # Expand the %l special to be the user's input line
1341 1348 if cmd.find('%l') >= 0:
1342 1349 cmd = cmd.replace('%l',rest)
1343 1350 rest = ''
1344 1351 if nargs==0:
1345 1352 # Simple, argument-less aliases
1346 1353 cmd = '%s %s' % (cmd,rest)
1347 1354 else:
1348 1355 # Handle aliases with positional arguments
1349 1356 args = rest.split(None,nargs)
1350 1357 if len(args)< nargs:
1351 1358 error('Alias <%s> requires %s arguments, %s given.' %
1352 1359 (alias,nargs,len(args)))
1353 1360 return
1354 1361 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1355 1362 # Now call the macro, evaluating in the user's namespace
1356 1363 try:
1357 1364 self.system(cmd)
1358 1365 except:
1359 1366 self.showtraceback()
1360 1367
1361 1368 def runlines(self,lines):
1362 1369 """Run a string of one or more lines of source.
1363 1370
1364 1371 This method is capable of running a string containing multiple source
1365 1372 lines, as if they had been entered at the IPython prompt. Since it
1366 1373 exposes IPython's processing machinery, the given strings can contain
1367 1374 magic calls (%magic), special shell access (!cmd), etc."""
1368 1375
1369 1376 # We must start with a clean buffer, in case this is run from an
1370 1377 # interactive IPython session (via a magic, for example).
1371 1378 self.resetbuffer()
1372 1379 lines = lines.split('\n')
1373 1380 more = 0
1374 1381 for line in lines:
1375 1382 # skip blank lines so we don't mess up the prompt counter, but do
1376 1383 # NOT skip even a blank line if we are in a code block (more is
1377 1384 # true)
1378 1385 if line or more:
1379 1386 more = self.push((self.prefilter(line,more)))
1380 1387 # IPython's runsource returns None if there was an error
1381 1388 # compiling the code. This allows us to stop processing right
1382 1389 # away, so the user gets the error message at the right place.
1383 1390 if more is None:
1384 1391 break
1385 1392 # final newline in case the input didn't have it, so that the code
1386 1393 # actually does get executed
1387 1394 if more:
1388 1395 self.push('\n')
1389 1396
1390 1397 def runsource(self, source, filename='<input>', symbol='single'):
1391 1398 """Compile and run some source in the interpreter.
1392 1399
1393 1400 Arguments are as for compile_command().
1394 1401
1395 1402 One several things can happen:
1396 1403
1397 1404 1) The input is incorrect; compile_command() raised an
1398 1405 exception (SyntaxError or OverflowError). A syntax traceback
1399 1406 will be printed by calling the showsyntaxerror() method.
1400 1407
1401 1408 2) The input is incomplete, and more input is required;
1402 1409 compile_command() returned None. Nothing happens.
1403 1410
1404 1411 3) The input is complete; compile_command() returned a code
1405 1412 object. The code is executed by calling self.runcode() (which
1406 1413 also handles run-time exceptions, except for SystemExit).
1407 1414
1408 1415 The return value is:
1409 1416
1410 1417 - True in case 2
1411 1418
1412 1419 - False in the other cases, unless an exception is raised, where
1413 1420 None is returned instead. This can be used by external callers to
1414 1421 know whether to continue feeding input or not.
1415 1422
1416 1423 The return value can be used to decide whether to use sys.ps1 or
1417 1424 sys.ps2 to prompt the next line."""
1418 1425
1419 1426 try:
1420 1427 code = self.compile(source,filename,symbol)
1421 1428 except (OverflowError, SyntaxError, ValueError):
1422 1429 # Case 1
1423 1430 self.showsyntaxerror(filename)
1424 1431 return None
1425 1432
1426 1433 if code is None:
1427 1434 # Case 2
1428 1435 return True
1429 1436
1430 1437 # Case 3
1431 1438 # We store the code object so that threaded shells and
1432 1439 # custom exception handlers can access all this info if needed.
1433 1440 # The source corresponding to this can be obtained from the
1434 1441 # buffer attribute as '\n'.join(self.buffer).
1435 1442 self.code_to_run = code
1436 1443 # now actually execute the code object
1437 1444 if self.runcode(code) == 0:
1438 1445 return False
1439 1446 else:
1440 1447 return None
1441 1448
1442 1449 def runcode(self,code_obj):
1443 1450 """Execute a code object.
1444 1451
1445 1452 When an exception occurs, self.showtraceback() is called to display a
1446 1453 traceback.
1447 1454
1448 1455 Return value: a flag indicating whether the code to be run completed
1449 1456 successfully:
1450 1457
1451 1458 - 0: successful execution.
1452 1459 - 1: an error occurred.
1453 1460 """
1454 1461
1455 1462 # Set our own excepthook in case the user code tries to call it
1456 1463 # directly, so that the IPython crash handler doesn't get triggered
1457 1464 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1458 1465 outflag = 1 # happens in more places, so it's easier as default
1459 1466 try:
1460 1467 try:
1461 1468 # Embedded instances require separate global/local namespaces
1462 1469 # so they can see both the surrounding (local) namespace and
1463 1470 # the module-level globals when called inside another function.
1464 1471 if self.embedded:
1465 1472 exec code_obj in self.user_global_ns, self.user_ns
1466 1473 # Normal (non-embedded) instances should only have a single
1467 1474 # namespace for user code execution, otherwise functions won't
1468 1475 # see interactive top-level globals.
1469 1476 else:
1470 1477 exec code_obj in self.user_ns
1471 1478 finally:
1472 1479 # Reset our crash handler in place
1473 1480 sys.excepthook = old_excepthook
1474 1481 except SystemExit:
1475 1482 self.resetbuffer()
1476 1483 self.showtraceback()
1477 1484 warn("Type exit or quit to exit IPython "
1478 1485 "(%Exit or %Quit do so unconditionally).",level=1)
1479 1486 except self.custom_exceptions:
1480 1487 etype,value,tb = sys.exc_info()
1481 1488 self.CustomTB(etype,value,tb)
1482 1489 except:
1483 1490 self.showtraceback()
1484 1491 else:
1485 1492 outflag = 0
1486 1493 if softspace(sys.stdout, 0):
1487 1494 print
1488 1495 # Flush out code object which has been run (and source)
1489 1496 self.code_to_run = None
1490 1497 return outflag
1491 1498
1492 1499 def push(self, line):
1493 1500 """Push a line to the interpreter.
1494 1501
1495 1502 The line should not have a trailing newline; it may have
1496 1503 internal newlines. The line is appended to a buffer and the
1497 1504 interpreter's runsource() method is called with the
1498 1505 concatenated contents of the buffer as source. If this
1499 1506 indicates that the command was executed or invalid, the buffer
1500 1507 is reset; otherwise, the command is incomplete, and the buffer
1501 1508 is left as it was after the line was appended. The return
1502 1509 value is 1 if more input is required, 0 if the line was dealt
1503 1510 with in some way (this is the same as runsource()).
1504 1511
1505 1512 """
1506 1513 self.buffer.append(line)
1507 1514 more = self.runsource('\n'.join(self.buffer), self.filename)
1508 1515 if not more:
1509 1516 self.resetbuffer()
1510 1517 return more
1511 1518
1512 1519 def resetbuffer(self):
1513 1520 """Reset the input buffer."""
1514 1521 self.buffer[:] = []
1515 1522
1516 1523 def raw_input(self,prompt='',continue_prompt=False):
1517 1524 """Write a prompt and read a line.
1518 1525
1519 1526 The returned line does not include the trailing newline.
1520 1527 When the user enters the EOF key sequence, EOFError is raised.
1521 1528
1522 1529 Optional inputs:
1523 1530
1524 1531 - prompt(''): a string to be printed to prompt the user.
1525 1532
1526 1533 - continue_prompt(False): whether this line is the first one or a
1527 1534 continuation in a sequence of inputs.
1528 1535 """
1529 1536
1530 1537 line = raw_input_original(prompt)
1531 1538 # Try to be reasonably smart about not re-indenting pasted input more
1532 1539 # than necessary. We do this by trimming out the auto-indent initial
1533 1540 # spaces, if the user's actual input started itself with whitespace.
1534 1541 if self.autoindent:
1535 1542 line2 = line[self.indent_current_nsp:]
1536 1543 if line2[0:1] in (' ','\t'):
1537 1544 line = line2
1538 1545 return self.prefilter(line,continue_prompt)
1539 1546
1540 1547 def split_user_input(self,line):
1541 1548 """Split user input into pre-char, function part and rest."""
1542 1549
1543 1550 lsplit = self.line_split.match(line)
1544 1551 if lsplit is None: # no regexp match returns None
1545 1552 try:
1546 1553 iFun,theRest = line.split(None,1)
1547 1554 except ValueError:
1548 1555 iFun,theRest = line,''
1549 1556 pre = re.match('^(\s*)(.*)',line).groups()[0]
1550 1557 else:
1551 1558 pre,iFun,theRest = lsplit.groups()
1552 1559
1553 1560 #print 'line:<%s>' % line # dbg
1554 1561 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1555 1562 return pre,iFun.strip(),theRest
1556 1563
1557 1564 def _prefilter(self, line, continue_prompt):
1558 1565 """Calls different preprocessors, depending on the form of line."""
1559 1566
1560 1567 # All handlers *must* return a value, even if it's blank ('').
1561 1568
1562 1569 # Lines are NOT logged here. Handlers should process the line as
1563 1570 # needed, update the cache AND log it (so that the input cache array
1564 1571 # stays synced).
1565 1572
1566 1573 # This function is _very_ delicate, and since it's also the one which
1567 1574 # determines IPython's response to user input, it must be as efficient
1568 1575 # as possible. For this reason it has _many_ returns in it, trying
1569 1576 # always to exit as quickly as it can figure out what it needs to do.
1570 1577
1571 1578 # This function is the main responsible for maintaining IPython's
1572 1579 # behavior respectful of Python's semantics. So be _very_ careful if
1573 1580 # making changes to anything here.
1574 1581
1575 1582 #.....................................................................
1576 1583 # Code begins
1577 1584
1578 1585 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1579 1586
1580 1587 # save the line away in case we crash, so the post-mortem handler can
1581 1588 # record it
1582 1589 self._last_input_line = line
1583 1590
1584 1591 #print '***line: <%s>' % line # dbg
1585 1592
1586 1593 # the input history needs to track even empty lines
1587 1594 if not line.strip():
1588 1595 if not continue_prompt:
1589 1596 self.outputcache.prompt_count -= 1
1590 1597 return self.handle_normal(line,continue_prompt)
1591 1598 #return self.handle_normal('',continue_prompt)
1592 1599
1593 1600 # print '***cont',continue_prompt # dbg
1594 1601 # special handlers are only allowed for single line statements
1595 1602 if continue_prompt and not self.rc.multi_line_specials:
1596 1603 return self.handle_normal(line,continue_prompt)
1597 1604
1598 1605 # For the rest, we need the structure of the input
1599 1606 pre,iFun,theRest = self.split_user_input(line)
1600 1607 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1601 1608
1602 1609 # First check for explicit escapes in the last/first character
1603 1610 handler = None
1604 1611 if line[-1] == self.ESC_HELP:
1605 1612 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1606 1613 if handler is None:
1607 1614 # look at the first character of iFun, NOT of line, so we skip
1608 1615 # leading whitespace in multiline input
1609 1616 handler = self.esc_handlers.get(iFun[0:1])
1610 1617 if handler is not None:
1611 1618 return handler(line,continue_prompt,pre,iFun,theRest)
1612 1619 # Emacs ipython-mode tags certain input lines
1613 1620 if line.endswith('# PYTHON-MODE'):
1614 1621 return self.handle_emacs(line,continue_prompt)
1615 1622
1616 1623 # Next, check if we can automatically execute this thing
1617 1624
1618 1625 # Allow ! in multi-line statements if multi_line_specials is on:
1619 1626 if continue_prompt and self.rc.multi_line_specials and \
1620 1627 iFun.startswith(self.ESC_SHELL):
1621 1628 return self.handle_shell_escape(line,continue_prompt,
1622 1629 pre=pre,iFun=iFun,
1623 1630 theRest=theRest)
1624 1631
1625 1632 # Let's try to find if the input line is a magic fn
1626 1633 oinfo = None
1627 1634 if hasattr(self,'magic_'+iFun):
1628 1635 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1629 1636 if oinfo['ismagic']:
1630 1637 # Be careful not to call magics when a variable assignment is
1631 1638 # being made (ls='hi', for example)
1632 1639 if self.rc.automagic and \
1633 1640 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1634 1641 (self.rc.multi_line_specials or not continue_prompt):
1635 1642 return self.handle_magic(line,continue_prompt,
1636 1643 pre,iFun,theRest)
1637 1644 else:
1638 1645 return self.handle_normal(line,continue_prompt)
1639 1646
1640 1647 # If the rest of the line begins with an (in)equality, assginment or
1641 1648 # function call, we should not call _ofind but simply execute it.
1642 1649 # This avoids spurious geattr() accesses on objects upon assignment.
1643 1650 #
1644 1651 # It also allows users to assign to either alias or magic names true
1645 1652 # python variables (the magic/alias systems always take second seat to
1646 1653 # true python code).
1647 1654 if theRest and theRest[0] in '!=()':
1648 1655 return self.handle_normal(line,continue_prompt)
1649 1656
1650 1657 if oinfo is None:
1651 1658 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1652 1659
1653 1660 if not oinfo['found']:
1654 1661 return self.handle_normal(line,continue_prompt)
1655 1662 else:
1656 1663 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1657 1664 if oinfo['isalias']:
1658 1665 return self.handle_alias(line,continue_prompt,
1659 1666 pre,iFun,theRest)
1660 1667
1661 1668 if self.rc.autocall and \
1662 1669 not self.re_exclude_auto.match(theRest) and \
1663 1670 self.re_fun_name.match(iFun) and \
1664 1671 callable(oinfo['obj']) :
1665 1672 #print 'going auto' # dbg
1666 1673 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1667 1674 else:
1668 1675 #print 'was callable?', callable(oinfo['obj']) # dbg
1669 1676 return self.handle_normal(line,continue_prompt)
1670 1677
1671 1678 # If we get here, we have a normal Python line. Log and return.
1672 1679 return self.handle_normal(line,continue_prompt)
1673 1680
1674 1681 def _prefilter_dumb(self, line, continue_prompt):
1675 1682 """simple prefilter function, for debugging"""
1676 1683 return self.handle_normal(line,continue_prompt)
1677 1684
1678 1685 # Set the default prefilter() function (this can be user-overridden)
1679 1686 prefilter = _prefilter
1680 1687
1681 1688 def handle_normal(self,line,continue_prompt=None,
1682 1689 pre=None,iFun=None,theRest=None):
1683 1690 """Handle normal input lines. Use as a template for handlers."""
1684 1691
1685 1692 # With autoindent on, we need some way to exit the input loop, and I
1686 1693 # don't want to force the user to have to backspace all the way to
1687 1694 # clear the line. The rule will be in this case, that either two
1688 1695 # lines of pure whitespace in a row, or a line of pure whitespace but
1689 1696 # of a size different to the indent level, will exit the input loop.
1690 1697 if (continue_prompt and self.autoindent and isspace(line) and
1691 1698 (line != self.indent_current or isspace(self.buffer[-1]))):
1692 1699 line = ''
1693 1700
1694 1701 self.log(line,continue_prompt)
1695 1702 self.update_cache(line)
1696 1703 return line
1697 1704
1698 1705 def handle_alias(self,line,continue_prompt=None,
1699 1706 pre=None,iFun=None,theRest=None):
1700 1707 """Handle alias input lines. """
1701 1708
1702 1709 theRest = esc_quotes(theRest)
1703 1710 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1704 1711 self.log(line_out,continue_prompt)
1705 1712 self.update_cache(line_out)
1706 1713 return line_out
1707 1714
1708 1715 def handle_shell_escape(self, line, continue_prompt=None,
1709 1716 pre=None,iFun=None,theRest=None):
1710 1717 """Execute the line in a shell, empty return value"""
1711 1718
1712 1719 #print 'line in :', `line` # dbg
1713 1720 # Example of a special handler. Others follow a similar pattern.
1714 1721 if continue_prompt: # multi-line statements
1715 1722 if iFun.startswith('!!'):
1716 1723 print 'SyntaxError: !! is not allowed in multiline statements'
1717 1724 return pre
1718 1725 else:
1719 1726 cmd = ("%s %s" % (iFun[1:],theRest)) #.replace('"','\\"')
1720 1727 #line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1721 1728 line_out = '%s%s.system(r"""%s"""[:-1])' % (pre,self.name,cmd + "_")
1722 1729 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1723 1730 else: # single-line input
1724 1731 if line.startswith('!!'):
1725 1732 # rewrite iFun/theRest to properly hold the call to %sx and
1726 1733 # the actual command to be executed, so handle_magic can work
1727 1734 # correctly
1728 1735 theRest = '%s %s' % (iFun[2:],theRest)
1729 1736 iFun = 'sx'
1730 1737 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1731 1738 continue_prompt,pre,iFun,theRest)
1732 1739 else:
1733 1740 #cmd = esc_quotes(line[1:])
1734 1741 cmd=line[1:]
1735 1742 #line_out = '%s.system("%s")' % (self.name,cmd)
1736 1743 line_out = '%s.system(r"""%s"""[:-1])' % (self.name,cmd +"_")
1737 1744 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1738 1745 # update cache/log and return
1739 1746 self.log(line_out,continue_prompt)
1740 1747 self.update_cache(line_out) # readline cache gets normal line
1741 1748 #print 'line out r:', `line_out` # dbg
1742 1749 #print 'line out s:', line_out # dbg
1743 1750 return line_out
1744 1751
1745 1752 def handle_magic(self, line, continue_prompt=None,
1746 1753 pre=None,iFun=None,theRest=None):
1747 1754 """Execute magic functions.
1748 1755
1749 1756 Also log them with a prepended # so the log is clean Python."""
1750 1757
1751 1758 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1752 1759 self.log(cmd,continue_prompt)
1753 1760 self.update_cache(line)
1754 1761 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1755 1762 return cmd
1756 1763
1757 1764 def handle_auto(self, line, continue_prompt=None,
1758 1765 pre=None,iFun=None,theRest=None):
1759 1766 """Hande lines which can be auto-executed, quoting if requested."""
1760 1767
1761 1768 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1762 1769
1763 1770 # This should only be active for single-line input!
1764 1771 if continue_prompt:
1765 1772 return line
1766 1773
1767 1774 if pre == self.ESC_QUOTE:
1768 1775 # Auto-quote splitting on whitespace
1769 1776 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1770 1777 elif pre == self.ESC_QUOTE2:
1771 1778 # Auto-quote whole string
1772 1779 newcmd = '%s("%s")' % (iFun,theRest)
1773 1780 else:
1774 1781 # Auto-paren
1775 1782 if theRest[0:1] in ('=','['):
1776 1783 # Don't autocall in these cases. They can be either
1777 1784 # rebindings of an existing callable's name, or item access
1778 1785 # for an object which is BOTH callable and implements
1779 1786 # __getitem__.
1780 1787 return '%s %s' % (iFun,theRest)
1781 1788 if theRest.endswith(';'):
1782 1789 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1783 1790 else:
1784 1791 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1785 1792
1786 1793 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1787 1794 # log what is now valid Python, not the actual user input (without the
1788 1795 # final newline)
1789 1796 self.log(newcmd,continue_prompt)
1790 1797 return newcmd
1791 1798
1792 1799 def handle_help(self, line, continue_prompt=None,
1793 1800 pre=None,iFun=None,theRest=None):
1794 1801 """Try to get some help for the object.
1795 1802
1796 1803 obj? or ?obj -> basic information.
1797 1804 obj?? or ??obj -> more details.
1798 1805 """
1799 1806
1800 1807 # We need to make sure that we don't process lines which would be
1801 1808 # otherwise valid python, such as "x=1 # what?"
1802 1809 try:
1803 1810 codeop.compile_command(line)
1804 1811 except SyntaxError:
1805 1812 # We should only handle as help stuff which is NOT valid syntax
1806 1813 if line[0]==self.ESC_HELP:
1807 1814 line = line[1:]
1808 1815 elif line[-1]==self.ESC_HELP:
1809 1816 line = line[:-1]
1810 1817 self.log('#?'+line)
1811 1818 self.update_cache(line)
1812 1819 if line:
1813 1820 self.magic_pinfo(line)
1814 1821 else:
1815 1822 page(self.usage,screen_lines=self.rc.screen_length)
1816 1823 return '' # Empty string is needed here!
1817 1824 except:
1818 1825 # Pass any other exceptions through to the normal handler
1819 1826 return self.handle_normal(line,continue_prompt)
1820 1827 else:
1821 1828 # If the code compiles ok, we should handle it normally
1822 1829 return self.handle_normal(line,continue_prompt)
1823 1830
1824 1831 def handle_emacs(self,line,continue_prompt=None,
1825 1832 pre=None,iFun=None,theRest=None):
1826 1833 """Handle input lines marked by python-mode."""
1827 1834
1828 1835 # Currently, nothing is done. Later more functionality can be added
1829 1836 # here if needed.
1830 1837
1831 1838 # The input cache shouldn't be updated
1832 1839
1833 1840 return line
1834 1841
1835 1842 def write(self,data):
1836 1843 """Write a string to the default output"""
1837 1844 Term.cout.write(data)
1838 1845
1839 1846 def write_err(self,data):
1840 1847 """Write a string to the default error output"""
1841 1848 Term.cerr.write(data)
1842 1849
1843 1850 def exit(self):
1844 1851 """Handle interactive exit.
1845 1852
1846 1853 This method sets the exit_now attribute."""
1847 1854
1848 1855 if self.rc.confirm_exit:
1849 1856 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1850 1857 self.exit_now = True
1851 1858 else:
1852 1859 self.exit_now = True
1853 1860 return self.exit_now
1854 1861
1855 1862 def safe_execfile(self,fname,*where,**kw):
1856 1863 fname = os.path.expanduser(fname)
1857 1864
1858 1865 # find things also in current directory
1859 1866 dname = os.path.dirname(fname)
1860 1867 if not sys.path.count(dname):
1861 1868 sys.path.append(dname)
1862 1869
1863 1870 try:
1864 1871 xfile = open(fname)
1865 1872 except:
1866 1873 print >> Term.cerr, \
1867 1874 'Could not open file <%s> for safe execution.' % fname
1868 1875 return None
1869 1876
1870 1877 kw.setdefault('islog',0)
1871 1878 kw.setdefault('quiet',1)
1872 1879 kw.setdefault('exit_ignore',0)
1873 1880 first = xfile.readline()
1874 1881 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1875 1882 xfile.close()
1876 1883 # line by line execution
1877 1884 if first.startswith(_LOGHEAD) or kw['islog']:
1878 1885 print 'Loading log file <%s> one line at a time...' % fname
1879 1886 if kw['quiet']:
1880 1887 stdout_save = sys.stdout
1881 1888 sys.stdout = StringIO.StringIO()
1882 1889 try:
1883 1890 globs,locs = where[0:2]
1884 1891 except:
1885 1892 try:
1886 1893 globs = locs = where[0]
1887 1894 except:
1888 1895 globs = locs = globals()
1889 1896 badblocks = []
1890 1897
1891 1898 # we also need to identify indented blocks of code when replaying
1892 1899 # logs and put them together before passing them to an exec
1893 1900 # statement. This takes a bit of regexp and look-ahead work in the
1894 1901 # file. It's easiest if we swallow the whole thing in memory
1895 1902 # first, and manually walk through the lines list moving the
1896 1903 # counter ourselves.
1897 1904 indent_re = re.compile('\s+\S')
1898 1905 xfile = open(fname)
1899 1906 filelines = xfile.readlines()
1900 1907 xfile.close()
1901 1908 nlines = len(filelines)
1902 1909 lnum = 0
1903 1910 while lnum < nlines:
1904 1911 line = filelines[lnum]
1905 1912 lnum += 1
1906 1913 # don't re-insert logger status info into cache
1907 1914 if line.startswith('#log#'):
1908 1915 continue
1909 1916 elif line.startswith('#%s'% self.ESC_MAGIC):
1910 1917 self.update_cache(line[1:])
1911 1918 line = magic2python(line)
1912 1919 elif line.startswith('#!'):
1913 1920 self.update_cache(line[1:])
1914 1921 else:
1915 1922 # build a block of code (maybe a single line) for execution
1916 1923 block = line
1917 1924 try:
1918 1925 next = filelines[lnum] # lnum has already incremented
1919 1926 except:
1920 1927 next = None
1921 1928 while next and indent_re.match(next):
1922 1929 block += next
1923 1930 lnum += 1
1924 1931 try:
1925 1932 next = filelines[lnum]
1926 1933 except:
1927 1934 next = None
1928 1935 # now execute the block of one or more lines
1929 1936 try:
1930 1937 exec block in globs,locs
1931 1938 self.update_cache(block.rstrip())
1932 1939 except SystemExit:
1933 1940 pass
1934 1941 except:
1935 1942 badblocks.append(block.rstrip())
1936 1943 if kw['quiet']: # restore stdout
1937 1944 sys.stdout.close()
1938 1945 sys.stdout = stdout_save
1939 1946 print 'Finished replaying log file <%s>' % fname
1940 1947 if badblocks:
1941 1948 print >> sys.stderr, ('\nThe following lines/blocks in file '
1942 1949 '<%s> reported errors:' % fname)
1943 1950
1944 1951 for badline in badblocks:
1945 1952 print >> sys.stderr, badline
1946 1953 else: # regular file execution
1947 1954 try:
1948 1955 execfile(fname,*where)
1949 1956 except SyntaxError:
1950 1957 etype, evalue = sys.exc_info()[0:2]
1951 1958 self.SyntaxTB(etype,evalue,[])
1952 1959 warn('Failure executing file: <%s>' % fname)
1953 1960 except SystemExit,status:
1954 1961 if not kw['exit_ignore']:
1955 1962 self.InteractiveTB()
1956 1963 warn('Failure executing file: <%s>' % fname)
1957 1964 except:
1958 1965 self.InteractiveTB()
1959 1966 warn('Failure executing file: <%s>' % fname)
1960 1967
1961 1968 #************************* end of file <iplib.py> *****************************
@@ -1,737 +1,739 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or better.
6 6
7 7 This file contains the main make_IPython() starter function.
8 8
9 $Id: ipmaker.py 963 2005-12-28 19:21:29Z fperez $"""
9 $Id: ipmaker.py 964 2005-12-28 21:03:01Z fperez $"""
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #*****************************************************************************
17 17
18 18 from IPython import Release
19 19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 20 __license__ = Release.license
21 21 __version__ = Release.version
22 22
23 23 credits._Printer__data = """
24 24 Python: %s
25 25
26 26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 27 See http://ipython.scipy.org for more information.""" \
28 28 % credits._Printer__data
29 29
30 30 copyright._Printer__data += """
31 31
32 32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 33 All Rights Reserved."""
34 34
35 35 #****************************************************************************
36 36 # Required modules
37 37
38 38 # From the standard library
39 39 import __main__
40 40 import __builtin__
41 41 import os
42 42 import re
43 43 import sys
44 44 import types
45 45 from pprint import pprint,pformat
46 46
47 47 # Our own
48 48 from IPython import DPyGetOpt
49 49 from IPython.Struct import Struct
50 50 from IPython.OutputTrap import OutputTrap
51 51 from IPython.ConfigLoader import ConfigLoader
52 52 from IPython.iplib import InteractiveShell,qw_lol,import_fail_info
53 53 from IPython.usage import cmd_line_usage,interactive_usage
54 54 from IPython.Prompts import CachedOutput
55 55 from IPython.genutils import *
56 56
57 57 #-----------------------------------------------------------------------------
58 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
59 shell_class=InteractiveShell,embedded=False,**kw):
58 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
59 rc_override=None,shell_class=InteractiveShell,
60 embedded=False,**kw):
60 61 """This is a dump of IPython into a single function.
61 62
62 63 Later it will have to be broken up in a sensible manner.
63 64
64 65 Arguments:
65 66
66 67 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 68 script name, b/c DPyGetOpt strips the first argument only for the real
68 69 sys.argv.
69 70
70 71 - user_ns: a dict to be used as the user's namespace."""
71 72
72 73 #----------------------------------------------------------------------
73 74 # Defaults and initialization
74 75
75 76 # For developer debugging, deactivates crash handler and uses pdb.
76 77 DEVDEBUG = False
77 78
78 79 if argv is None:
79 80 argv = sys.argv
80 81
81 82 # __IP is the main global that lives throughout and represents the whole
82 83 # application. If the user redefines it, all bets are off as to what
83 84 # happens.
84 85
85 86 # __IP is the name of he global which the caller will have accessible as
86 87 # __IP.name. We set its name via the first parameter passed to
87 88 # InteractiveShell:
88 89
89 IP = shell_class('__IP',user_ns=user_ns,embedded=embedded,**kw)
90 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
91 embedded=embedded,**kw)
90 92
91 93 # Put 'help' in the user namespace
92 94 from site import _Helper
93 95 IP.user_ns['help'] = _Helper()
94 96
95 97 if DEVDEBUG:
96 98 # For developer debugging only (global flag)
97 99 from IPython import ultraTB
98 100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
99 101 else:
100 102 # IPython itself shouldn't crash. This will produce a detailed
101 103 # post-mortem if it does
102 104 from IPython import CrashHandler
103 105 sys.excepthook = CrashHandler.CrashHandler(IP)
104 106
105 107 IP.BANNER_PARTS = ['Python %s\n'
106 108 'Type "copyright", "credits" or "license" '
107 109 'for more information.\n'
108 110 % (sys.version.split('\n')[0],),
109 111 "IPython %s -- An enhanced Interactive Python."
110 112 % (__version__,),
111 113 """? -> Introduction to IPython's features.
112 114 %magic -> Information about IPython's 'magic' % functions.
113 115 help -> Python's own help system.
114 116 object? -> Details about 'object'. ?object also works, ?? prints more.
115 117 """ ]
116 118
117 119 IP.usage = interactive_usage
118 120
119 121 # Platform-dependent suffix and directory names. We use _ipython instead
120 122 # of .ipython under win32 b/c there's software that breaks with .named
121 123 # directories on that platform.
122 124 if os.name == 'posix':
123 125 rc_suffix = ''
124 126 ipdir_def = '.ipython'
125 127 else:
126 128 rc_suffix = '.ini'
127 129 ipdir_def = '_ipython'
128 130
129 131 # default directory for configuration
130 132 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
131 133 os.path.join(IP.home_dir,ipdir_def)))
132 134
133 135 # we need the directory where IPython itself is installed
134 136 import IPython
135 137 IPython_dir = os.path.dirname(IPython.__file__)
136 138 del IPython
137 139
138 140 #-------------------------------------------------------------------------
139 141 # Command line handling
140 142
141 143 # Valid command line options (uses DPyGetOpt syntax, like Perl's
142 144 # GetOpt::Long)
143 145
144 146 # Any key not listed here gets deleted even if in the file (like session
145 147 # or profile). That's deliberate, to maintain the rc namespace clean.
146 148
147 149 # Each set of options appears twice: under _conv only the names are
148 150 # listed, indicating which type they must be converted to when reading the
149 151 # ipythonrc file. And under DPyGetOpt they are listed with the regular
150 152 # DPyGetOpt syntax (=s,=i,:f,etc).
151 153
152 154 # Make sure there's a space before each end of line (they get auto-joined!)
153 155 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
154 156 'c=s classic|cl color_info! colors=s confirm_exit! '
155 157 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
156 158 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
157 159 'quick screen_length|sl=i prompts_pad_left=i '
158 160 'logfile|lf=s logplay|lp=s profile|p=s '
159 161 'readline! readline_merge_completions! '
160 162 'readline_omit__names! '
161 163 'rcfile=s separate_in|si=s separate_out|so=s '
162 164 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
163 165 'magic_docstrings system_verbose! '
164 166 'multi_line_specials! '
165 167 'autoedit_syntax!')
166 168
167 169 # Options that can *only* appear at the cmd line (not in rcfiles).
168 170
169 171 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
170 172 # the 'C-c !' command in emacs automatically appends a -i option at the end.
171 173 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
172 174 'gthread! qthread! wthread! pylab! tk!')
173 175
174 176 # Build the actual name list to be used by DPyGetOpt
175 177 opts_names = qw(cmdline_opts) + qw(cmdline_only)
176 178
177 179 # Set sensible command line defaults.
178 180 # This should have everything from cmdline_opts and cmdline_only
179 181 opts_def = Struct(autocall = 1,
180 182 autoedit_syntax = 1,
181 183 autoindent=0,
182 184 automagic = 1,
183 185 banner = 1,
184 186 cache_size = 1000,
185 187 c = '',
186 188 classic = 0,
187 189 colors = 'NoColor',
188 190 color_info = 0,
189 191 confirm_exit = 1,
190 192 debug = 0,
191 193 deep_reload = 0,
192 194 editor = '0',
193 195 help = 0,
194 196 ignore = 0,
195 197 ipythondir = ipythondir,
196 198 log = 0,
197 199 logfile = '',
198 200 logplay = '',
199 201 multi_line_specials = 1,
200 202 messages = 1,
201 203 nosep = 0,
202 204 pdb = 0,
203 205 pprint = 0,
204 206 profile = '',
205 207 prompt_in1 = 'In [\\#]: ',
206 208 prompt_in2 = ' .\\D.: ',
207 209 prompt_out = 'Out[\\#]: ',
208 210 prompts_pad_left = 1,
209 211 quick = 0,
210 212 readline = 1,
211 213 readline_merge_completions = 1,
212 214 readline_omit__names = 0,
213 215 rcfile = 'ipythonrc' + rc_suffix,
214 216 screen_length = 0,
215 217 separate_in = '\n',
216 218 separate_out = '\n',
217 219 separate_out2 = '',
218 220 system_verbose = 0,
219 221 gthread = 0,
220 222 qthread = 0,
221 223 wthread = 0,
222 224 pylab = 0,
223 225 tk = 0,
224 226 upgrade = 0,
225 227 Version = 0,
226 228 xmode = 'Verbose',
227 229 wildcards_case_sensitive = 1,
228 230 magic_docstrings = 0, # undocumented, for doc generation
229 231 )
230 232
231 233 # Things that will *only* appear in rcfiles (not at the command line).
232 234 # Make sure there's a space before each end of line (they get auto-joined!)
233 235 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
234 236 qw_lol: 'import_some ',
235 237 # for things with embedded whitespace:
236 238 list_strings:'execute alias readline_parse_and_bind ',
237 239 # Regular strings need no conversion:
238 240 None:'readline_remove_delims ',
239 241 }
240 242 # Default values for these
241 243 rc_def = Struct(include = [],
242 244 import_mod = [],
243 245 import_all = [],
244 246 import_some = [[]],
245 247 execute = [],
246 248 execfile = [],
247 249 alias = [],
248 250 readline_parse_and_bind = [],
249 251 readline_remove_delims = '',
250 252 )
251 253
252 254 # Build the type conversion dictionary from the above tables:
253 255 typeconv = rcfile_opts.copy()
254 256 typeconv.update(optstr2types(cmdline_opts))
255 257
256 258 # FIXME: the None key appears in both, put that back together by hand. Ugly!
257 259 typeconv[None] += ' ' + rcfile_opts[None]
258 260
259 261 # Remove quotes at ends of all strings (used to protect spaces)
260 262 typeconv[unquote_ends] = typeconv[None]
261 263 del typeconv[None]
262 264
263 265 # Build the list we'll use to make all config decisions with defaults:
264 266 opts_all = opts_def.copy()
265 267 opts_all.update(rc_def)
266 268
267 269 # Build conflict resolver for recursive loading of config files:
268 270 # - preserve means the outermost file maintains the value, it is not
269 271 # overwritten if an included file has the same key.
270 272 # - add_flip applies + to the two values, so it better make sense to add
271 273 # those types of keys. But it flips them first so that things loaded
272 274 # deeper in the inclusion chain have lower precedence.
273 275 conflict = {'preserve': ' '.join([ typeconv[int],
274 276 typeconv[unquote_ends] ]),
275 277 'add_flip': ' '.join([ typeconv[qwflat],
276 278 typeconv[qw_lol],
277 279 typeconv[list_strings] ])
278 280 }
279 281
280 282 # Now actually process the command line
281 283 getopt = DPyGetOpt.DPyGetOpt()
282 284 getopt.setIgnoreCase(0)
283 285
284 286 getopt.parseConfiguration(opts_names)
285 287
286 288 try:
287 289 getopt.processArguments(argv)
288 290 except:
289 291 print cmd_line_usage
290 292 warn('\nError in Arguments: ' + `sys.exc_value`)
291 293 sys.exit(1)
292 294
293 295 # convert the options dict to a struct for much lighter syntax later
294 296 opts = Struct(getopt.optionValues)
295 297 args = getopt.freeValues
296 298
297 299 # this is the struct (which has default values at this point) with which
298 300 # we make all decisions:
299 301 opts_all.update(opts)
300 302
301 303 # Options that force an immediate exit
302 304 if opts_all.help:
303 305 page(cmd_line_usage)
304 306 sys.exit()
305 307
306 308 if opts_all.Version:
307 309 print __version__
308 310 sys.exit()
309 311
310 312 if opts_all.magic_docstrings:
311 313 IP.magic_magic('-latex')
312 314 sys.exit()
313 315
314 316 # Create user config directory if it doesn't exist. This must be done
315 317 # *after* getting the cmd line options.
316 318 if not os.path.isdir(opts_all.ipythondir):
317 319 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
318 320
319 321 # upgrade user config files while preserving a copy of the originals
320 322 if opts_all.upgrade:
321 323 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
322 324
323 325 # check mutually exclusive options in the *original* command line
324 326 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
325 327 qw('classic profile'),qw('classic rcfile')])
326 328
327 329 # default logfilename used when -log is called.
328 330 IP.LOGDEF = 'ipython.log'
329 331
330 332 #---------------------------------------------------------------------------
331 333 # Log replay
332 334
333 335 # if -logplay, we need to 'become' the other session. That basically means
334 336 # replacing the current command line environment with that of the old
335 337 # session and moving on.
336 338
337 339 # this is needed so that later we know we're in session reload mode, as
338 340 # opts_all will get overwritten:
339 341 load_logplay = 0
340 342
341 343 if opts_all.logplay:
342 344 load_logplay = opts_all.logplay
343 345 opts_debug_save = opts_all.debug
344 346 try:
345 347 logplay = open(opts_all.logplay)
346 348 except IOError:
347 349 if opts_all.debug: IP.InteractiveTB()
348 350 warn('Could not open logplay file '+`opts_all.logplay`)
349 351 # restore state as if nothing had happened and move on, but make
350 352 # sure that later we don't try to actually load the session file
351 353 logplay = None
352 354 load_logplay = 0
353 355 del opts_all.logplay
354 356 else:
355 357 try:
356 358 logplay.readline()
357 359 logplay.readline();
358 360 # this reloads that session's command line
359 361 cmd = logplay.readline()[6:]
360 362 exec cmd
361 363 # restore the true debug flag given so that the process of
362 364 # session loading itself can be monitored.
363 365 opts.debug = opts_debug_save
364 366 # save the logplay flag so later we don't overwrite the log
365 367 opts.logplay = load_logplay
366 368 # now we must update our own structure with defaults
367 369 opts_all.update(opts)
368 370 # now load args
369 371 cmd = logplay.readline()[6:]
370 372 exec cmd
371 373 logplay.close()
372 374 except:
373 375 logplay.close()
374 376 if opts_all.debug: IP.InteractiveTB()
375 377 warn("Logplay file lacking full configuration information.\n"
376 378 "I'll try to read it, but some things may not work.")
377 379
378 380 #-------------------------------------------------------------------------
379 381 # set up output traps: catch all output from files, being run, modules
380 382 # loaded, etc. Then give it to the user in a clean form at the end.
381 383
382 384 msg_out = 'Output messages. '
383 385 msg_err = 'Error messages. '
384 386 msg_sep = '\n'
385 387 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
386 388 msg_err,msg_sep,debug,
387 389 quiet_out=1),
388 390 user_exec = OutputTrap('User File Execution',msg_out,
389 391 msg_err,msg_sep,debug),
390 392 logplay = OutputTrap('Log Loader',msg_out,
391 393 msg_err,msg_sep,debug),
392 394 summary = ''
393 395 )
394 396
395 397 #-------------------------------------------------------------------------
396 398 # Process user ipythonrc-type configuration files
397 399
398 400 # turn on output trapping and log to msg.config
399 401 # remember that with debug on, trapping is actually disabled
400 402 msg.config.trap_all()
401 403
402 404 # look for rcfile in current or default directory
403 405 try:
404 406 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
405 407 except IOError:
406 408 if opts_all.debug: IP.InteractiveTB()
407 409 warn('Configuration file %s not found. Ignoring request.'
408 410 % (opts_all.rcfile) )
409 411
410 412 # 'profiles' are a shorthand notation for config filenames
411 413 if opts_all.profile:
412 414 try:
413 415 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
414 416 + rc_suffix,
415 417 opts_all.ipythondir)
416 418 except IOError:
417 419 if opts_all.debug: IP.InteractiveTB()
418 420 opts.profile = '' # remove profile from options if invalid
419 421 warn('Profile configuration file %s not found. Ignoring request.'
420 422 % (opts_all.profile) )
421 423
422 424 # load the config file
423 425 rcfiledata = None
424 426 if opts_all.quick:
425 427 print 'Launching IPython in quick mode. No config file read.'
426 428 elif opts_all.classic:
427 429 print 'Launching IPython in classic mode. No config file read.'
428 430 elif opts_all.rcfile:
429 431 try:
430 432 cfg_loader = ConfigLoader(conflict)
431 433 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
432 434 'include',opts_all.ipythondir,
433 435 purge = 1,
434 436 unique = conflict['preserve'])
435 437 except:
436 438 IP.InteractiveTB()
437 439 warn('Problems loading configuration file '+
438 440 `opts_all.rcfile`+
439 441 '\nStarting with default -bare bones- configuration.')
440 442 else:
441 443 warn('No valid configuration file found in either currrent directory\n'+
442 444 'or in the IPython config. directory: '+`opts_all.ipythondir`+
443 445 '\nProceeding with internal defaults.')
444 446
445 447 #------------------------------------------------------------------------
446 448 # Set exception handlers in mode requested by user.
447 449 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
448 450 IP.magic_xmode(opts_all.xmode)
449 451 otrap.release_out()
450 452
451 453 #------------------------------------------------------------------------
452 454 # Execute user config
453 455
454 456 # Create a valid config structure with the right precedence order:
455 457 # defaults < rcfile < command line. This needs to be in the instance, so
456 458 # that method calls below that rely on it find it.
457 459 IP.rc = rc_def.copy()
458 460
459 461 # Work with a local alias inside this routine to avoid unnecessary
460 462 # attribute lookups.
461 463 IP_rc = IP.rc
462 464
463 465 IP_rc.update(opts_def)
464 466 if rcfiledata:
465 467 # now we can update
466 468 IP_rc.update(rcfiledata)
467 469 IP_rc.update(opts)
468 470 IP_rc.update(rc_override)
469 471
470 472 # Store the original cmd line for reference:
471 473 IP_rc.opts = opts
472 474 IP_rc.args = args
473 475
474 476 # create a *runtime* Struct like rc for holding parameters which may be
475 477 # created and/or modified by runtime user extensions.
476 478 IP.runtime_rc = Struct()
477 479
478 480 # from this point on, all config should be handled through IP_rc,
479 481 # opts* shouldn't be used anymore.
480 482
481 483 # add personal .ipython dir to sys.path so that users can put things in
482 484 # there for customization
483 485 sys.path.append(IP_rc.ipythondir)
484 486 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
485 487
486 488 # update IP_rc with some special things that need manual
487 489 # tweaks. Basically options which affect other options. I guess this
488 490 # should just be written so that options are fully orthogonal and we
489 491 # wouldn't worry about this stuff!
490 492
491 493 if IP_rc.classic:
492 494 IP_rc.quick = 1
493 495 IP_rc.cache_size = 0
494 496 IP_rc.pprint = 0
495 497 IP_rc.prompt_in1 = '>>> '
496 498 IP_rc.prompt_in2 = '... '
497 499 IP_rc.prompt_out = ''
498 500 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
499 501 IP_rc.colors = 'NoColor'
500 502 IP_rc.xmode = 'Plain'
501 503
502 504 # configure readline
503 505 # Define the history file for saving commands in between sessions
504 506 if IP_rc.profile:
505 507 histfname = 'history-%s' % IP_rc.profile
506 508 else:
507 509 histfname = 'history'
508 510 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
509 511
510 512 # update exception handlers with rc file status
511 513 otrap.trap_out() # I don't want these messages ever.
512 514 IP.magic_xmode(IP_rc.xmode)
513 515 otrap.release_out()
514 516
515 517 # activate logging if requested and not reloading a log
516 518 if IP_rc.logplay:
517 519 IP.magic_logstart(IP_rc.logplay + ' append')
518 520 elif IP_rc.logfile:
519 521 IP.magic_logstart(IP_rc.logfile)
520 522 elif IP_rc.log:
521 523 IP.magic_logstart()
522 524
523 525 # find user editor so that it we don't have to look it up constantly
524 526 if IP_rc.editor.strip()=='0':
525 527 try:
526 528 ed = os.environ['EDITOR']
527 529 except KeyError:
528 530 if os.name == 'posix':
529 531 ed = 'vi' # the only one guaranteed to be there!
530 532 else:
531 533 ed = 'notepad' # same in Windows!
532 534 IP_rc.editor = ed
533 535
534 536 # Keep track of whether this is an embedded instance or not (useful for
535 537 # post-mortems).
536 538 IP_rc.embedded = IP.embedded
537 539
538 540 # Recursive reload
539 541 try:
540 542 from IPython import deep_reload
541 543 if IP_rc.deep_reload:
542 544 __builtin__.reload = deep_reload.reload
543 545 else:
544 546 __builtin__.dreload = deep_reload.reload
545 547 del deep_reload
546 548 except ImportError:
547 549 pass
548 550
549 551 # Save the current state of our namespace so that the interactive shell
550 552 # can later know which variables have been created by us from config files
551 553 # and loading. This way, loading a file (in any way) is treated just like
552 554 # defining things on the command line, and %who works as expected.
553 555
554 556 # DON'T do anything that affects the namespace beyond this point!
555 557 IP.internal_ns.update(__main__.__dict__)
556 558
557 559 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
558 560
559 561 # Now run through the different sections of the users's config
560 562 if IP_rc.debug:
561 563 print 'Trying to execute the following configuration structure:'
562 564 print '(Things listed first are deeper in the inclusion tree and get'
563 565 print 'loaded first).\n'
564 566 pprint(IP_rc.__dict__)
565 567
566 568 for mod in IP_rc.import_mod:
567 569 try:
568 570 exec 'import '+mod in IP.user_ns
569 571 except :
570 572 IP.InteractiveTB()
571 573 import_fail_info(mod)
572 574
573 575 for mod_fn in IP_rc.import_some:
574 576 if mod_fn == []: break
575 577 mod,fn = mod_fn[0],','.join(mod_fn[1:])
576 578 try:
577 579 exec 'from '+mod+' import '+fn in IP.user_ns
578 580 except :
579 581 IP.InteractiveTB()
580 582 import_fail_info(mod,fn)
581 583
582 584 for mod in IP_rc.import_all:
583 585 try:
584 586 exec 'from '+mod+' import *' in IP.user_ns
585 587 except :
586 588 IP.InteractiveTB()
587 589 import_fail_info(mod)
588 590
589 591 for code in IP_rc.execute:
590 592 try:
591 593 exec code in IP.user_ns
592 594 except:
593 595 IP.InteractiveTB()
594 596 warn('Failure executing code: ' + `code`)
595 597
596 598 # Execute the files the user wants in ipythonrc
597 599 for file in IP_rc.execfile:
598 600 try:
599 601 file = filefind(file,sys.path+[IPython_dir])
600 602 except IOError:
601 603 warn(itpl('File $file not found. Skipping it.'))
602 604 else:
603 605 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
604 606
605 607 # release stdout and stderr and save config log into a global summary
606 608 msg.config.release_all()
607 609 if IP_rc.messages:
608 610 msg.summary += msg.config.summary_all()
609 611
610 612 #------------------------------------------------------------------------
611 613 # Setup interactive session
612 614
613 615 # Now we should be fully configured. We can then execute files or load
614 616 # things only needed for interactive use. Then we'll open the shell.
615 617
616 618 # Take a snapshot of the user namespace before opening the shell. That way
617 619 # we'll be able to identify which things were interactively defined and
618 620 # which were defined through config files.
619 621 IP.user_config_ns = IP.user_ns.copy()
620 622
621 623 # Force reading a file as if it were a session log. Slower but safer.
622 624 if load_logplay:
623 625 print 'Replaying log...'
624 626 try:
625 627 if IP_rc.debug:
626 628 logplay_quiet = 0
627 629 else:
628 630 logplay_quiet = 1
629 631
630 632 msg.logplay.trap_all()
631 633 IP.safe_execfile(load_logplay,IP.user_ns,
632 634 islog = 1, quiet = logplay_quiet)
633 635 msg.logplay.release_all()
634 636 if IP_rc.messages:
635 637 msg.summary += msg.logplay.summary_all()
636 638 except:
637 639 warn('Problems replaying logfile %s.' % load_logplay)
638 640 IP.InteractiveTB()
639 641
640 642 # Load remaining files in command line
641 643 msg.user_exec.trap_all()
642 644
643 645 # Do NOT execute files named in the command line as scripts to be loaded
644 646 # by embedded instances. Doing so has the potential for an infinite
645 647 # recursion if there are exceptions thrown in the process.
646 648
647 649 # XXX FIXME: the execution of user files should be moved out to after
648 650 # ipython is fully initialized, just as if they were run via %run at the
649 651 # ipython prompt. This would also give them the benefit of ipython's
650 652 # nice tracebacks.
651 653
652 654 if not embedded and IP_rc.args:
653 655 name_save = IP.user_ns['__name__']
654 656 IP.user_ns['__name__'] = '__main__'
655 657 try:
656 658 # Set our own excepthook in case the user code tries to call it
657 659 # directly. This prevents triggering the IPython crash handler.
658 660 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
659 661 for run in args:
660 662 IP.safe_execfile(run,IP.user_ns)
661 663 finally:
662 664 # Reset our crash handler in place
663 665 sys.excepthook = old_excepthook
664 666
665 667 IP.user_ns['__name__'] = name_save
666 668
667 669 msg.user_exec.release_all()
668 670 if IP_rc.messages:
669 671 msg.summary += msg.user_exec.summary_all()
670 672
671 673 # since we can't specify a null string on the cmd line, 0 is the equivalent:
672 674 if IP_rc.nosep:
673 675 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
674 676 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
675 677 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
676 678 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
677 679 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
678 680 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
679 681 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
680 682
681 683 # Determine how many lines at the bottom of the screen are needed for
682 684 # showing prompts, so we can know wheter long strings are to be printed or
683 685 # paged:
684 686 num_lines_bot = IP_rc.separate_in.count('\n')+1
685 687 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
686 688 # Initialize cache, set in/out prompts and printing system
687 689 IP.outputcache = CachedOutput(IP_rc.cache_size,
688 690 IP_rc.pprint,
689 691 input_sep = IP_rc.separate_in,
690 692 output_sep = IP_rc.separate_out,
691 693 output_sep2 = IP_rc.separate_out2,
692 694 ps1 = IP_rc.prompt_in1,
693 695 ps2 = IP_rc.prompt_in2,
694 696 ps_out = IP_rc.prompt_out,
695 697 user_ns = IP.user_ns,
696 698 input_hist = IP.input_hist,
697 699 pad_left = IP_rc.prompts_pad_left)
698 700
699 701 # user may have over-ridden the default print hook:
700 702 try:
701 703 IP.outputcache.__class__.display = IP.hooks.display
702 704 except AttributeError:
703 705 pass
704 706
705 707 # Set calling of pdb on exceptions
706 708 IP.InteractiveTB.call_pdb = IP_rc.pdb
707 709
708 710 # I don't like assigning globally to sys, because it means when embedding
709 711 # instances, each embedded instance overrides the previous choice. But
710 712 # sys.displayhook seems to be called internally by exec, so I don't see a
711 713 # way around it.
712 714 sys.displayhook = IP.outputcache
713 715
714 716 # we need to know globally if we're caching i/o or not
715 717 IP.do_full_cache = IP.outputcache.do_full_cache
716 718
717 719 # configure startup banner
718 720 if IP_rc.c: # regular python doesn't print the banner with -c
719 721 IP_rc.banner = 0
720 722 if IP_rc.banner:
721 723 BANN_P = IP.BANNER_PARTS
722 724 else:
723 725 BANN_P = []
724 726
725 727 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
726 728
727 729 # add message log (possibly empty)
728 730 if msg.summary: BANN_P.append(msg.summary)
729 731 # Final banner is a string
730 732 IP.BANNER = '\n'.join(BANN_P)
731 733
732 734 # Finalize the IPython instance. This assumes the rc structure is fully
733 735 # in place.
734 736 IP.post_config_initialization()
735 737
736 738 return IP
737 739 #************************ end of file <ipmaker.py> **************************
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now