##// END OF EJS Templates
Minor fixes in genutils, and a BIG fix for threading. I _think_ I got...
fperez -
Show More
@@ -1,881 +1,861 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 802 2005-09-06 03:49:12Z fperez $"""
7 $Id: Shell.py 874 2005-09-20 20:13:04Z fperez $"""
8 8
9 9 #*****************************************************************************
10 10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #*****************************************************************************
15 15
16 16 from IPython import Release
17 17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 18 __license__ = Release.license
19 19
20 20 # Code begins
21 21 import __main__
22 22 import __builtin__
23 23 import sys
24 24 import os
25 25 import code
26 26 import threading
27 27 import signal
28 28
29 29 import IPython
30 30 from IPython.iplib import InteractiveShell
31 31 from IPython.ipmaker import make_IPython
32 32 from IPython.genutils import Term,warn,error,flag_calls
33 33 from IPython.Struct import Struct
34 34 from IPython.Magic import Magic
35 35 from IPython import ultraTB
36 36
37 # global flag to pass around information about Ctrl-C without exceptions
38 KBINT = False
39
40 37 # global flag to turn on/off Tk support.
41 38 USE_TK = False
42 39
43 40 #-----------------------------------------------------------------------------
44 41 # This class is trivial now, but I want to have it in to publish a clean
45 42 # interface. Later when the internals are reorganized, code that uses this
46 43 # shouldn't have to change.
47 44
48 45 class IPShell:
49 46 """Create an IPython instance."""
50 47
51 48 def __init__(self,argv=None,user_ns=None,debug=1,
52 49 shell_class=InteractiveShell):
53 50 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
54 51 shell_class=shell_class)
55 52
56 53 def mainloop(self,sys_exit=0,banner=None):
57 54 self.IP.mainloop(banner)
58 55 if sys_exit:
59 56 sys.exit()
60 57
61 58 #-----------------------------------------------------------------------------
62 59 class IPShellEmbed:
63 60 """Allow embedding an IPython shell into a running program.
64 61
65 62 Instances of this class are callable, with the __call__ method being an
66 63 alias to the embed() method of an InteractiveShell instance.
67 64
68 65 Usage (see also the example-embed.py file for a running example):
69 66
70 67 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
71 68
72 69 - argv: list containing valid command-line options for IPython, as they
73 70 would appear in sys.argv[1:].
74 71
75 72 For example, the following command-line options:
76 73
77 74 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
78 75
79 76 would be passed in the argv list as:
80 77
81 78 ['-prompt_in1','Input <\\#>','-colors','LightBG']
82 79
83 80 - banner: string which gets printed every time the interpreter starts.
84 81
85 82 - exit_msg: string which gets printed every time the interpreter exits.
86 83
87 84 - rc_override: a dict or Struct of configuration options such as those
88 85 used by IPython. These options are read from your ~/.ipython/ipythonrc
89 86 file when the Shell object is created. Passing an explicit rc_override
90 87 dict with any options you want allows you to override those values at
91 88 creation time without having to modify the file. This way you can create
92 89 embeddable instances configured in any way you want without editing any
93 90 global files (thus keeping your interactive IPython configuration
94 91 unchanged).
95 92
96 93 Then the ipshell instance can be called anywhere inside your code:
97 94
98 95 ipshell(header='') -> Opens up an IPython shell.
99 96
100 97 - header: string printed by the IPython shell upon startup. This can let
101 98 you know where in your code you are when dropping into the shell. Note
102 99 that 'banner' gets prepended to all calls, so header is used for
103 100 location-specific information.
104 101
105 102 For more details, see the __call__ method below.
106 103
107 104 When the IPython shell is exited with Ctrl-D, normal program execution
108 105 resumes.
109 106
110 107 This functionality was inspired by a posting on comp.lang.python by cmkl
111 108 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
112 109 by the IDL stop/continue commands."""
113 110
114 111 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
115 112 """Note that argv here is a string, NOT a list."""
116 113 self.set_banner(banner)
117 114 self.set_exit_msg(exit_msg)
118 115 self.set_dummy_mode(0)
119 116
120 117 # sys.displayhook is a global, we need to save the user's original
121 118 # Don't rely on __displayhook__, as the user may have changed that.
122 119 self.sys_displayhook_ori = sys.displayhook
123 120
124 121 # save readline completer status
125 122 try:
126 123 #print 'Save completer',sys.ipcompleter # dbg
127 124 self.sys_ipcompleter_ori = sys.ipcompleter
128 125 except:
129 126 pass # not nested with IPython
130 127
131 128 # FIXME. Passing user_ns breaks namespace handling.
132 129 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 130 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
134 131
135 132 self.IP.name_space_init()
136 133 # mark this as an embedded instance so we know if we get a crash
137 134 # post-mortem
138 135 self.IP.rc.embedded = 1
139 136 # copy our own displayhook also
140 137 self.sys_displayhook_embed = sys.displayhook
141 138 # and leave the system's display hook clean
142 139 sys.displayhook = self.sys_displayhook_ori
143 140 # don't use the ipython crash handler so that user exceptions aren't
144 141 # trapped
145 142 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
146 143 mode = self.IP.rc.xmode,
147 144 call_pdb = self.IP.rc.pdb)
148 145 self.restore_system_completer()
149 146
150 147 def restore_system_completer(self):
151 148 """Restores the readline completer which was in place.
152 149
153 150 This allows embedded IPython within IPython not to disrupt the
154 151 parent's completion.
155 152 """
156 153
157 154 try:
158 155 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
159 156 sys.ipcompleter = self.sys_ipcompleter_ori
160 157 except:
161 158 pass
162 159
163 160 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
164 161 """Activate the interactive interpreter.
165 162
166 163 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
167 164 the interpreter shell with the given local and global namespaces, and
168 165 optionally print a header string at startup.
169 166
170 167 The shell can be globally activated/deactivated using the
171 168 set/get_dummy_mode methods. This allows you to turn off a shell used
172 169 for debugging globally.
173 170
174 171 However, *each* time you call the shell you can override the current
175 172 state of dummy_mode with the optional keyword parameter 'dummy'. For
176 173 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
177 174 can still have a specific call work by making it as IPShell(dummy=0).
178 175
179 176 The optional keyword parameter dummy controls whether the call
180 177 actually does anything. """
181 178
182 179 # Allow the dummy parameter to override the global __dummy_mode
183 180 if dummy or (dummy != 0 and self.__dummy_mode):
184 181 return
185 182
186 183 # Set global subsystems (display,completions) to our values
187 184 sys.displayhook = self.sys_displayhook_embed
188 185 if self.IP.has_readline:
189 186 self.IP.readline.set_completer(self.IP.Completer.complete)
190 187
191 188 if self.banner and header:
192 189 format = '%s\n%s\n'
193 190 else:
194 191 format = '%s%s\n'
195 192 banner = format % (self.banner,header)
196 193
197 194 # Call the embedding code with a stack depth of 1 so it can skip over
198 195 # our call and get the original caller's namespaces.
199 196 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
200 197
201 198 if self.exit_msg:
202 199 print self.exit_msg
203 200
204 201 # Restore global systems (display, completion)
205 202 sys.displayhook = self.sys_displayhook_ori
206 203 self.restore_system_completer()
207 204
208 205 def set_dummy_mode(self,dummy):
209 206 """Sets the embeddable shell's dummy mode parameter.
210 207
211 208 set_dummy_mode(dummy): dummy = 0 or 1.
212 209
213 210 This parameter is persistent and makes calls to the embeddable shell
214 211 silently return without performing any action. This allows you to
215 212 globally activate or deactivate a shell you're using with a single call.
216 213
217 214 If you need to manually"""
218 215
219 216 if dummy not in [0,1]:
220 217 raise ValueError,'dummy parameter must be 0 or 1'
221 218 self.__dummy_mode = dummy
222 219
223 220 def get_dummy_mode(self):
224 221 """Return the current value of the dummy mode parameter.
225 222 """
226 223 return self.__dummy_mode
227 224
228 225 def set_banner(self,banner):
229 226 """Sets the global banner.
230 227
231 228 This banner gets prepended to every header printed when the shell
232 229 instance is called."""
233 230
234 231 self.banner = banner
235 232
236 233 def set_exit_msg(self,exit_msg):
237 234 """Sets the global exit_msg.
238 235
239 236 This exit message gets printed upon exiting every time the embedded
240 237 shell is called. It is None by default. """
241 238
242 239 self.exit_msg = exit_msg
243 240
244 241 #-----------------------------------------------------------------------------
245 242 def sigint_handler (signum,stack_frame):
246 243 """Sigint handler for threaded apps.
247
248 This is a horrible hack to pass information about SIGINT _without_ using
249 exceptions, since I haven't been able to properly manage cross-thread
250 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
251 that's my understanding from a c.l.py thread where this was discussed)."""
252
253 global KBINT
254
255 print '\nKeyboardInterrupt - Press <Enter> to continue.',
256 Term.cout.flush()
257 # Set global flag so that runsource can know that Ctrl-C was hit
258 KBINT = True
244 """
245 raise KeyboardInterrupt
259 246
260 247 class MTInteractiveShell(InteractiveShell):
261 248 """Simple multi-threaded shell."""
262 249
263 250 # Threading strategy taken from:
264 251 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
265 252 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
266 253 # from the pygtk mailing list, to avoid lockups with system calls.
267 254
268 255 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
269 256 user_ns = None, banner2='',**kw):
270 257 """Similar to the normal InteractiveShell, but with threading control"""
271 258
272 259 IPython.iplib.InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2)
273 260
274 261 # Locking control variable
275 262 self.thread_ready = threading.Condition()
276 263
277 264 # Stuff to do at closing time
278 265 self._kill = False
279 266 on_kill = kw.get('on_kill')
280 267 if on_kill is None:
281 268 on_kill = []
282 269 # Check that all things to kill are callable:
283 270 for t in on_kill:
284 271 if not callable(t):
285 272 raise TypeError,'on_kill must be a list of callables'
286 273 self.on_kill = on_kill
287 274
288 275 def runsource(self, source, filename="<input>", symbol="single"):
289 276 """Compile and run some source in the interpreter.
290 277
291 278 Modified version of code.py's runsource(), to handle threading issues.
292 279 See the original for full docstring details."""
293
294 global KBINT
295
296 # If Ctrl-C was typed, we reset the flag and return right away
297 if KBINT:
298 KBINT = False
299 return False
300 280
301 281 try:
302 282 code = self.compile(source, filename, symbol)
303 283 except (OverflowError, SyntaxError, ValueError):
304 284 # Case 1
305 285 self.showsyntaxerror(filename)
306 286 return False
307 287
308 288 if code is None:
309 289 # Case 2
310 290 return True
311 291
312 292 # Case 3
313 293 # Store code in self, so the execution thread can handle it
314 294 self.thread_ready.acquire()
315 295 self.code_to_run = code
316 296 self.thread_ready.wait() # Wait until processed in timeout interval
317 297 self.thread_ready.release()
318 298
319 299 return False
320 300
321 301 def runcode(self):
322 302 """Execute a code object.
323 303
324 304 Multithreaded wrapper around IPython's runcode()."""
325 305
326 306 # lock thread-protected stuff
327 307 self.thread_ready.acquire()
328 308
329 309 # Install sigint handler
330 310 try:
331 311 signal.signal(signal.SIGINT, sigint_handler)
332 312 except SystemError:
333 313 # This happens under Windows, which seems to have all sorts
334 314 # of problems with signal handling. Oh well...
335 315 pass
336 316
337 317 if self._kill:
338 318 print >>Term.cout, 'Closing threads...',
339 319 Term.cout.flush()
340 320 for tokill in self.on_kill:
341 321 tokill()
342 322 print >>Term.cout, 'Done.'
343 323
344 324 # Run pending code by calling parent class
345 325 if self.code_to_run is not None:
346 326 self.thread_ready.notify()
347 327 InteractiveShell.runcode(self,self.code_to_run)
348 328
349 329 # We're done with thread-protected variables
350 330 self.thread_ready.release()
351 331 # This MUST return true for gtk threading to work
352 332 return True
353 333
354 334 def kill (self):
355 335 """Kill the thread, returning when it has been shut down."""
356 336 self.thread_ready.acquire()
357 337 self._kill = True
358 338 self.thread_ready.release()
359 339
360 340 class MatplotlibShellBase:
361 341 """Mixin class to provide the necessary modifications to regular IPython
362 342 shell classes for matplotlib support.
363 343
364 344 Given Python's MRO, this should be used as the FIRST class in the
365 345 inheritance hierarchy, so that it overrides the relevant methods."""
366 346
367 347 def _matplotlib_config(self,name):
368 348 """Return various items needed to setup the user's shell with matplotlib"""
369 349
370 350 # Initialize matplotlib to interactive mode always
371 351 import matplotlib
372 352 from matplotlib import backends
373 353 matplotlib.interactive(True)
374 354
375 355 def use(arg):
376 356 """IPython wrapper for matplotlib's backend switcher.
377 357
378 358 In interactive use, we can not allow switching to a different
379 359 interactive backend, since thread conflicts will most likely crash
380 360 the python interpreter. This routine does a safety check first,
381 361 and refuses to perform a dangerous switch. It still allows
382 362 switching to non-interactive backends."""
383 363
384 364 if arg in backends.interactive_bk and arg != self.mpl_backend:
385 365 m=('invalid matplotlib backend switch.\n'
386 366 'This script attempted to switch to the interactive '
387 367 'backend: `%s`\n'
388 368 'Your current choice of interactive backend is: `%s`\n\n'
389 369 'Switching interactive matplotlib backends at runtime\n'
390 370 'would crash the python interpreter, '
391 371 'and IPython has blocked it.\n\n'
392 372 'You need to either change your choice of matplotlib backend\n'
393 373 'by editing your .matplotlibrc file, or run this script as a \n'
394 374 'standalone file from the command line, not using IPython.\n' %
395 375 (arg,self.mpl_backend) )
396 376 raise RuntimeError, m
397 377 else:
398 378 self.mpl_use(arg)
399 379 self.mpl_use._called = True
400 380
401 381 self.matplotlib = matplotlib
402 382 self.mpl_backend = matplotlib.rcParams['backend']
403 383
404 384 # we also need to block switching of interactive backends by use()
405 385 self.mpl_use = matplotlib.use
406 386 self.mpl_use._called = False
407 387 # overwrite the original matplotlib.use with our wrapper
408 388 matplotlib.use = use
409 389
410 390
411 391 # This must be imported last in the matplotlib series, after
412 392 # backend/interactivity choices have been made
413 393 try:
414 394 import matplotlib.pylab as pylab
415 395 self.pylab = pylab
416 396 self.pylab_name = 'pylab'
417 397 except ImportError:
418 398 import matplotlib.matlab as matlab
419 399 self.pylab = matlab
420 400 self.pylab_name = 'matlab'
421 401
422 402 self.pylab.show._needmain = False
423 403 # We need to detect at runtime whether show() is called by the user.
424 404 # For this, we wrap it into a decorator which adds a 'called' flag.
425 405 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
426 406
427 407 # Build a user namespace initialized with matplotlib/matlab features.
428 408 user_ns = {'__name__':'__main__',
429 409 '__builtins__' : __builtin__ }
430 410
431 411 # Be careful not to remove the final \n in the code string below, or
432 412 # things will break badly with py22 (I think it's a python bug, 2.3 is
433 413 # OK).
434 414 pname = self.pylab_name # Python can't interpolate dotted var names
435 415 exec ("import matplotlib\n"
436 416 "import matplotlib.%(pname)s as %(pname)s\n"
437 417 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
438 418
439 419 # Build matplotlib info banner
440 420 b="""
441 421 Welcome to pylab, a matplotlib-based Python environment.
442 422 For more information, type 'help(pylab)'.
443 423 """
444 424 return user_ns,b
445 425
446 426 def mplot_exec(self,fname,*where,**kw):
447 427 """Execute a matplotlib script.
448 428
449 429 This is a call to execfile(), but wrapped in safeties to properly
450 430 handle interactive rendering and backend switching."""
451 431
452 432 #print '*** Matplotlib runner ***' # dbg
453 433 # turn off rendering until end of script
454 434 isInteractive = self.matplotlib.rcParams['interactive']
455 435 self.matplotlib.interactive(False)
456 436 self.safe_execfile(fname,*where,**kw)
457 437 self.matplotlib.interactive(isInteractive)
458 438 # make rendering call now, if the user tried to do it
459 439 if self.pylab.draw_if_interactive.called:
460 440 self.pylab.draw()
461 441 self.pylab.draw_if_interactive.called = False
462 442
463 443 # if a backend switch was performed, reverse it now
464 444 if self.mpl_use._called:
465 445 self.matplotlib.rcParams['backend'] = self.mpl_backend
466 446
467 447 def magic_run(self,parameter_s=''):
468 448 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
469 449
470 450 # Fix the docstring so users see the original as well
471 451 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
472 452 "\n *** Modified %run for Matplotlib,"
473 453 " with proper interactive handling ***")
474 454
475 455 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
476 456 # and multithreaded. Note that these are meant for internal use, the IPShell*
477 457 # classes below are the ones meant for public consumption.
478 458
479 459 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
480 460 """Single-threaded shell with matplotlib support."""
481 461
482 462 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
483 463 user_ns = None, **kw):
484 464 user_ns,b2 = self._matplotlib_config(name)
485 465 InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
486 466
487 467 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
488 468 """Multi-threaded shell with matplotlib support."""
489 469
490 470 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
491 471 user_ns = None, **kw):
492 472 user_ns,b2 = self._matplotlib_config(name)
493 473 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
494 474
495 475 #-----------------------------------------------------------------------------
496 476 # Utility functions for the different GUI enabled IPShell* classes.
497 477
498 478 def get_tk():
499 479 """Tries to import Tkinter and returns a withdrawn Tkinter root
500 480 window. If Tkinter is already imported or not available, this
501 481 returns None. This function calls `hijack_tk` underneath.
502 482 """
503 483 if not USE_TK or sys.modules.has_key('Tkinter'):
504 484 return None
505 485 else:
506 486 try:
507 487 import Tkinter
508 488 except ImportError:
509 489 return None
510 490 else:
511 491 hijack_tk()
512 492 r = Tkinter.Tk()
513 493 r.withdraw()
514 494 return r
515 495
516 496 def hijack_tk():
517 497 """Modifies Tkinter's mainloop with a dummy so when a module calls
518 498 mainloop, it does not block.
519 499
520 500 """
521 501 def misc_mainloop(self, n=0):
522 502 pass
523 503 def tkinter_mainloop(n=0):
524 504 pass
525 505
526 506 import Tkinter
527 507 Tkinter.Misc.mainloop = misc_mainloop
528 508 Tkinter.mainloop = tkinter_mainloop
529 509
530 510 def update_tk(tk):
531 511 """Updates the Tkinter event loop. This is typically called from
532 512 the respective WX or GTK mainloops.
533 513 """
534 514 if tk:
535 515 tk.update()
536 516
537 517 def hijack_wx():
538 518 """Modifies wxPython's MainLoop with a dummy so user code does not
539 519 block IPython. The hijacked mainloop function is returned.
540 520 """
541 521 def dummy_mainloop(*args, **kw):
542 522 pass
543 523 import wxPython
544 524 ver = wxPython.__version__
545 525 orig_mainloop = None
546 526 if ver[:3] >= '2.5':
547 527 import wx
548 528 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
549 529 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
550 530 else: raise AttributeError('Could not find wx core module')
551 531 orig_mainloop = core.PyApp_MainLoop
552 532 core.PyApp_MainLoop = dummy_mainloop
553 533 elif ver[:3] == '2.4':
554 534 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
555 535 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
556 536 else:
557 537 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
558 538 return orig_mainloop
559 539
560 540 def hijack_gtk():
561 541 """Modifies pyGTK's mainloop with a dummy so user code does not
562 542 block IPython. This function returns the original `gtk.mainloop`
563 543 function that has been hijacked.
564 544 """
565 545 def dummy_mainloop(*args, **kw):
566 546 pass
567 547 import gtk
568 548 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
569 549 else: orig_mainloop = gtk.mainloop
570 550 gtk.mainloop = dummy_mainloop
571 551 gtk.main = dummy_mainloop
572 552 return orig_mainloop
573 553
574 554 #-----------------------------------------------------------------------------
575 555 # The IPShell* classes below are the ones meant to be run by external code as
576 556 # IPython instances. Note that unless a specific threading strategy is
577 557 # desired, the factory function start() below should be used instead (it
578 558 # selects the proper threaded class).
579 559
580 560 class IPShellGTK(threading.Thread):
581 561 """Run a gtk mainloop() in a separate thread.
582 562
583 563 Python commands can be passed to the thread where they will be executed.
584 564 This is implemented by periodically checking for passed code using a
585 565 GTK timeout callback."""
586 566
587 567 TIMEOUT = 100 # Millisecond interval between timeouts.
588 568
589 569 def __init__(self,argv=None,user_ns=None,debug=1,
590 570 shell_class=MTInteractiveShell):
591 571
592 572 import gtk
593 573
594 574 self.gtk = gtk
595 575 self.gtk_mainloop = hijack_gtk()
596 576
597 577 # Allows us to use both Tk and GTK.
598 578 self.tk = get_tk()
599 579
600 580 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
601 581 else: mainquit = self.gtk.mainquit
602 582
603 583 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
604 584 shell_class=shell_class,
605 585 on_kill=[mainquit])
606 586 threading.Thread.__init__(self)
607 587
608 588 def run(self):
609 589 self.IP.mainloop()
610 590 self.IP.kill()
611 591
612 592 def mainloop(self):
613 593
614 594 if self.gtk.pygtk_version >= (2,4,0):
615 595 import gobject
616 596 gobject.timeout_add(self.TIMEOUT, self.on_timer)
617 597 else:
618 598 self.gtk.timeout_add(self.TIMEOUT, self.on_timer)
619 599
620 600 if sys.platform != 'win32':
621 601 try:
622 602 if self.gtk.gtk_version[0] >= 2:
623 603 self.gtk.threads_init()
624 604 except AttributeError:
625 605 pass
626 606 except RuntimeError:
627 607 error('Your pyGTK likely has not been compiled with '
628 608 'threading support.\n'
629 609 'The exception printout is below.\n'
630 610 'You can either rebuild pyGTK with threads, or '
631 611 'try using \n'
632 612 'matplotlib with a different backend (like Tk or WX).\n'
633 613 'Note that matplotlib will most likely not work in its '
634 614 'current state!')
635 615 self.IP.InteractiveTB()
636 616 self.start()
637 617 self.gtk.threads_enter()
638 618 self.gtk_mainloop()
639 619 self.gtk.threads_leave()
640 620 self.join()
641 621
642 622 def on_timer(self):
643 623 update_tk(self.tk)
644 624 return self.IP.runcode()
645 625
646 626
647 627 class IPShellWX(threading.Thread):
648 628 """Run a wx mainloop() in a separate thread.
649 629
650 630 Python commands can be passed to the thread where they will be executed.
651 631 This is implemented by periodically checking for passed code using a
652 632 GTK timeout callback."""
653 633
654 634 TIMEOUT = 100 # Millisecond interval between timeouts.
655 635
656 636 def __init__(self,argv=None,user_ns=None,debug=1,
657 637 shell_class=MTInteractiveShell):
658 638
659 639 import wxPython.wx as wx
660 640
661 641 threading.Thread.__init__(self)
662 642 self.wx = wx
663 643 self.wx_mainloop = hijack_wx()
664 644
665 645 # Allows us to use both Tk and GTK.
666 646 self.tk = get_tk()
667 647
668 648 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
669 649 shell_class=shell_class,
670 650 on_kill=[self.wxexit])
671 651 self.app = None
672 652
673 653 def wxexit(self, *args):
674 654 if self.app is not None:
675 655 self.app.agent.timer.Stop()
676 656 self.app.ExitMainLoop()
677 657
678 658 def run(self):
679 659 self.IP.mainloop()
680 660 self.IP.kill()
681 661
682 662 def mainloop(self):
683 663
684 664 self.start()
685 665
686 666 class TimerAgent(self.wx.wxMiniFrame):
687 667 wx = self.wx
688 668 IP = self.IP
689 669 tk = self.tk
690 670 def __init__(self, parent, interval):
691 671 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
692 672 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
693 673 size=(100, 100),style=style)
694 674 self.Show(False)
695 675 self.interval = interval
696 676 self.timerId = self.wx.wxNewId()
697 677
698 678 def StartWork(self):
699 679 self.timer = self.wx.wxTimer(self, self.timerId)
700 680 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
701 681 self.timer.Start(self.interval)
702 682
703 683 def OnTimer(self, event):
704 684 update_tk(self.tk)
705 685 self.IP.runcode()
706 686
707 687 class App(self.wx.wxApp):
708 688 wx = self.wx
709 689 TIMEOUT = self.TIMEOUT
710 690 def OnInit(self):
711 691 'Create the main window and insert the custom frame'
712 692 self.agent = TimerAgent(None, self.TIMEOUT)
713 693 self.agent.Show(self.wx.false)
714 694 self.agent.StartWork()
715 695 return self.wx.true
716 696
717 697 self.app = App(redirect=False)
718 698 self.wx_mainloop(self.app)
719 699 self.join()
720 700
721 701
722 702 class IPShellQt(threading.Thread):
723 703 """Run a Qt event loop in a separate thread.
724 704
725 705 Python commands can be passed to the thread where they will be executed.
726 706 This is implemented by periodically checking for passed code using a
727 707 Qt timer / slot."""
728 708
729 709 TIMEOUT = 100 # Millisecond interval between timeouts.
730 710
731 711 def __init__(self,argv=None,user_ns=None,debug=0,
732 712 shell_class=MTInteractiveShell):
733 713
734 714 import qt
735 715
736 716 class newQApplication:
737 717 def __init__( self ):
738 718 self.QApplication = qt.QApplication
739 719
740 720 def __call__( *args, **kwargs ):
741 721 return qt.qApp
742 722
743 723 def exec_loop( *args, **kwargs ):
744 724 pass
745 725
746 726 def __getattr__( self, name ):
747 727 return getattr( self.QApplication, name )
748 728
749 729 qt.QApplication = newQApplication()
750 730
751 731 # Allows us to use both Tk and QT.
752 732 self.tk = get_tk()
753 733
754 734 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
755 735 shell_class=shell_class,
756 736 on_kill=[qt.qApp.exit])
757 737
758 738 threading.Thread.__init__(self)
759 739
760 740 def run(self):
761 741 #sys.excepthook = self.IP.excepthook # dbg
762 742 self.IP.mainloop()
763 743 self.IP.kill()
764 744
765 745 def mainloop(self):
766 746 import qt, sys
767 747 if qt.QApplication.startingUp():
768 748 a = qt.QApplication.QApplication( sys.argv )
769 749 self.timer = qt.QTimer()
770 750 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
771 751
772 752 self.start()
773 753 self.timer.start( self.TIMEOUT, True )
774 754 while True:
775 755 if self.IP._kill: break
776 756 qt.qApp.exec_loop()
777 757 self.join()
778 758
779 759 def on_timer(self):
780 760 update_tk(self.tk)
781 761 result = self.IP.runcode()
782 762 self.timer.start( self.TIMEOUT, True )
783 763 return result
784 764
785 765 # A set of matplotlib public IPython shell classes, for single-threaded
786 766 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
787 767 class IPShellMatplotlib(IPShell):
788 768 """Subclass IPShell with MatplotlibShell as the internal shell.
789 769
790 770 Single-threaded class, meant for the Tk* and FLTK* backends.
791 771
792 772 Having this on a separate class simplifies the external driver code."""
793 773
794 774 def __init__(self,argv=None,user_ns=None,debug=1):
795 775 IPShell.__init__(self,argv,user_ns,debug,shell_class=MatplotlibShell)
796 776
797 777 class IPShellMatplotlibGTK(IPShellGTK):
798 778 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
799 779
800 780 Multi-threaded class, meant for the GTK* backends."""
801 781
802 782 def __init__(self,argv=None,user_ns=None,debug=1):
803 783 IPShellGTK.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
804 784
805 785 class IPShellMatplotlibWX(IPShellWX):
806 786 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
807 787
808 788 Multi-threaded class, meant for the WX* backends."""
809 789
810 790 def __init__(self,argv=None,user_ns=None,debug=1):
811 791 IPShellWX.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
812 792
813 793 class IPShellMatplotlibQt(IPShellQt):
814 794 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
815 795
816 796 Multi-threaded class, meant for the Qt* backends."""
817 797
818 798 def __init__(self,argv=None,user_ns=None,debug=1):
819 799 IPShellQt.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
820 800
821 801 #-----------------------------------------------------------------------------
822 802 # Factory functions to actually start the proper thread-aware shell
823 803
824 804 def _matplotlib_shell_class():
825 805 """Factory function to handle shell class selection for matplotlib.
826 806
827 807 The proper shell class to use depends on the matplotlib backend, since
828 808 each backend requires a different threading strategy."""
829 809
830 810 try:
831 811 import matplotlib
832 812 except ImportError:
833 813 error('matplotlib could NOT be imported! Starting normal IPython.')
834 814 sh_class = IPShell
835 815 else:
836 816 backend = matplotlib.rcParams['backend']
837 817 if backend.startswith('GTK'):
838 818 sh_class = IPShellMatplotlibGTK
839 819 elif backend.startswith('WX'):
840 820 sh_class = IPShellMatplotlibWX
841 821 elif backend.startswith('Qt'):
842 822 sh_class = IPShellMatplotlibQt
843 823 else:
844 824 sh_class = IPShellMatplotlib
845 825 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
846 826 return sh_class
847 827
848 828 # This is the one which should be called by external code.
849 829 def start():
850 830 """Return a running shell instance, dealing with threading options.
851 831
852 832 This is a factory function which will instantiate the proper IPython shell
853 833 based on the user's threading choice. Such a selector is needed because
854 834 different GUI toolkits require different thread handling details."""
855 835
856 836 global USE_TK
857 837 # Crude sys.argv hack to extract the threading options.
858 838 if len(sys.argv) > 1:
859 839 if len(sys.argv) > 2:
860 840 arg2 = sys.argv[2]
861 841 if arg2.endswith('-tk'):
862 842 USE_TK = True
863 843 arg1 = sys.argv[1]
864 844 if arg1.endswith('-gthread'):
865 845 shell = IPShellGTK
866 846 elif arg1.endswith( '-qthread' ):
867 847 shell = IPShellQt
868 848 elif arg1.endswith('-wthread'):
869 849 shell = IPShellWX
870 850 elif arg1.endswith('-pylab'):
871 851 shell = _matplotlib_shell_class()
872 852 else:
873 853 shell = IPShell
874 854 else:
875 855 shell = IPShell
876 856 return shell()
877 857
878 858 # Some aliases for backwards compatibility
879 859 IPythonShell = IPShell
880 860 IPythonShellEmbed = IPShellEmbed
881 861 #************************ End of file <Shell.py> ***************************
@@ -1,1521 +1,1530 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 General purpose utilities.
4 4
5 5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 6 these things are also convenient when working at the command line.
7 7
8 $Id: genutils.py 703 2005-08-16 17:34:44Z fperez $"""
8 $Id: genutils.py 874 2005-09-20 20:13:04Z fperez $"""
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16
17 17 from __future__ import generators # 2.2 compatibility
18 18
19 19 from IPython import Release
20 20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 21 __license__ = Release.license
22 22
23 23 #****************************************************************************
24 24 # required modules
25 25 import __main__
26 26 import types,commands,time,sys,os,re,shutil
27 27 import tempfile
28 28 from IPython.Itpl import Itpl,itpl,printpl
29 29 from IPython import DPyGetOpt
30 30
31 31 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
32 32 # 2.2-friendly
33 33 try:
34 34 basestring
35 35 except NameError:
36 36 import types
37 37 basestring = (types.StringType, types.UnicodeType)
38 38 True = 1==1
39 39 False = 1==0
40 40
41 41 def enumerate(obj):
42 42 i = -1
43 43 for item in obj:
44 44 i += 1
45 45 yield i, item
46 46
47 47 # add these to the builtin namespace, so that all modules find them
48 48 import __builtin__
49 49 __builtin__.basestring = basestring
50 50 __builtin__.True = True
51 51 __builtin__.False = False
52 52 __builtin__.enumerate = enumerate
53 53
54 54 #****************************************************************************
55 55 # Exceptions
56 56 class Error(Exception):
57 57 """Base class for exceptions in this module."""
58 58 pass
59 59
60 60 #----------------------------------------------------------------------------
61 61 class IOStream:
62 62 def __init__(self,stream,fallback):
63 63 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
64 64 stream = fallback
65 65 self.stream = stream
66 66 self._swrite = stream.write
67 67 self.flush = stream.flush
68 68
69 69 def write(self,data):
70 70 try:
71 71 self._swrite(data)
72 72 except:
73 73 try:
74 74 # print handles some unicode issues which may trip a plain
75 75 # write() call. Attempt to emulate write() by using a
76 76 # trailing comma
77 77 print >> self.stream, data,
78 78 except:
79 79 # if we get here, something is seriously broken.
80 80 print >> sys.stderr, \
81 81 'ERROR - failed to write data to stream:', stream
82 82
83 83 class IOTerm:
84 84 """ Term holds the file or file-like objects for handling I/O operations.
85 85
86 86 These are normally just sys.stdin, sys.stdout and sys.stderr but for
87 87 Windows they can can replaced to allow editing the strings before they are
88 88 displayed."""
89 89
90 90 # In the future, having IPython channel all its I/O operations through
91 91 # this class will make it easier to embed it into other environments which
92 92 # are not a normal terminal (such as a GUI-based shell)
93 93 def __init__(self,cin=None,cout=None,cerr=None):
94 94 self.cin = IOStream(cin,sys.stdin)
95 95 self.cout = IOStream(cout,sys.stdout)
96 96 self.cerr = IOStream(cerr,sys.stderr)
97 97
98 98 # Global variable to be used for all I/O
99 99 Term = IOTerm()
100 100
101 101 # Windows-specific code to load Gary Bishop's readline and configure it
102 102 # automatically for the users
103 103 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
104 104 # windows. Cygwin returns 'cygwin' for sys.platform.
105 105 if os.name == 'nt':
106 106 try:
107 107 import readline
108 108 except ImportError:
109 109 pass
110 110 else:
111 111 try:
112 112 _out = readline.GetOutputFile()
113 113 except AttributeError:
114 114 pass
115 115 else:
116 116 # Remake Term to use the readline i/o facilities
117 117 Term = IOTerm(cout=_out,cerr=_out)
118 118 del _out
119 119
120 120 #****************************************************************************
121 121 # Generic warning/error printer, used by everything else
122 122 def warn(msg,level=2,exit_val=1):
123 123 """Standard warning printer. Gives formatting consistency.
124 124
125 125 Output is sent to Term.cerr (sys.stderr by default).
126 126
127 127 Options:
128 128
129 129 -level(2): allows finer control:
130 130 0 -> Do nothing, dummy function.
131 131 1 -> Print message.
132 132 2 -> Print 'WARNING:' + message. (Default level).
133 133 3 -> Print 'ERROR:' + message.
134 134 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
135 135
136 136 -exit_val (1): exit value returned by sys.exit() for a level 4
137 137 warning. Ignored for all other levels."""
138 138
139 139 if level>0:
140 140 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
141 141 print >> Term.cerr, '%s%s' % (header[level],msg)
142 142 if level == 4:
143 143 print >> Term.cerr,'Exiting.\n'
144 144 sys.exit(exit_val)
145 145
146 146 def info(msg):
147 147 """Equivalent to warn(msg,level=1)."""
148 148
149 149 warn(msg,level=1)
150 150
151 151 def error(msg):
152 152 """Equivalent to warn(msg,level=3)."""
153 153
154 154 warn(msg,level=3)
155 155
156 156 def fatal(msg,exit_val=1):
157 157 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
158 158
159 159 warn(msg,exit_val=exit_val,level=4)
160 160
161 161 #----------------------------------------------------------------------------
162 162 StringTypes = types.StringTypes
163 163
164 164 # Basic timing functionality
165 165
166 166 # If possible (Unix), use the resource module instead of time.clock()
167 167 try:
168 168 import resource
169 169 def clock():
170 170 """clock() -> floating point number
171 171
172 172 Return the CPU time in seconds (user time only, system time is
173 173 ignored) since the start of the process. This is done via a call to
174 174 resource.getrusage, so it avoids the wraparound problems in
175 175 time.clock()."""
176 176
177 177 return resource.getrusage(resource.RUSAGE_SELF)[0]
178 178
179 179 def clock2():
180 180 """clock2() -> (t_user,t_system)
181 181
182 182 Similar to clock(), but return a tuple of user/system times."""
183 183 return resource.getrusage(resource.RUSAGE_SELF)[:2]
184 184
185 185 except ImportError:
186 186 clock = time.clock
187 187 def clock2():
188 188 """Under windows, system CPU time can't be measured.
189 189
190 190 This just returns clock() and zero."""
191 191 return time.clock(),0.0
192 192
193 193 def timings_out(reps,func,*args,**kw):
194 194 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
195 195
196 196 Execute a function reps times, return a tuple with the elapsed total
197 197 CPU time in seconds, the time per call and the function's output.
198 198
199 199 Under Unix, the return value is the sum of user+system time consumed by
200 200 the process, computed via the resource module. This prevents problems
201 201 related to the wraparound effect which the time.clock() function has.
202 202
203 203 Under Windows the return value is in wall clock seconds. See the
204 204 documentation for the time module for more details."""
205 205
206 206 reps = int(reps)
207 207 assert reps >=1, 'reps must be >= 1'
208 208 if reps==1:
209 209 start = clock()
210 210 out = func(*args,**kw)
211 211 tot_time = clock()-start
212 212 else:
213 213 rng = xrange(reps-1) # the last time is executed separately to store output
214 214 start = clock()
215 215 for dummy in rng: func(*args,**kw)
216 216 out = func(*args,**kw) # one last time
217 217 tot_time = clock()-start
218 218 av_time = tot_time / reps
219 219 return tot_time,av_time,out
220 220
221 221 def timings(reps,func,*args,**kw):
222 222 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
223 223
224 224 Execute a function reps times, return a tuple with the elapsed total CPU
225 225 time in seconds and the time per call. These are just the first two values
226 226 in timings_out()."""
227 227
228 228 return timings_out(reps,func,*args,**kw)[0:2]
229 229
230 230 def timing(func,*args,**kw):
231 231 """timing(func,*args,**kw) -> t_total
232 232
233 233 Execute a function once, return the elapsed total CPU time in
234 234 seconds. This is just the first value in timings_out()."""
235 235
236 236 return timings_out(1,func,*args,**kw)[0]
237 237
238 238 #****************************************************************************
239 239 # file and system
240 240
241 241 def system(cmd,verbose=0,debug=0,header=''):
242 242 """Execute a system command, return its exit status.
243 243
244 244 Options:
245 245
246 246 - verbose (0): print the command to be executed.
247 247
248 248 - debug (0): only print, do not actually execute.
249 249
250 250 - header (''): Header to print on screen prior to the executed command (it
251 251 is only prepended to the command, no newlines are added).
252 252
253 253 Note: a stateful version of this function is available through the
254 254 SystemExec class."""
255 255
256 256 stat = 0
257 257 if verbose or debug: print header+cmd
258 258 sys.stdout.flush()
259 259 if not debug: stat = os.system(cmd)
260 260 return stat
261 261
262 262 def shell(cmd,verbose=0,debug=0,header=''):
263 263 """Execute a command in the system shell, always return None.
264 264
265 265 Options:
266 266
267 267 - verbose (0): print the command to be executed.
268 268
269 269 - debug (0): only print, do not actually execute.
270 270
271 271 - header (''): Header to print on screen prior to the executed command (it
272 272 is only prepended to the command, no newlines are added).
273 273
274 274 Note: this is similar to genutils.system(), but it returns None so it can
275 275 be conveniently used in interactive loops without getting the return value
276 276 (typically 0) printed many times."""
277 277
278 278 stat = 0
279 279 if verbose or debug: print header+cmd
280 280 # flush stdout so we don't mangle python's buffering
281 281 sys.stdout.flush()
282 282 if not debug:
283 283 os.system(cmd)
284 284
285 285 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
286 286 """Dummy substitute for perl's backquotes.
287 287
288 288 Executes a command and returns the output.
289 289
290 290 Accepts the same arguments as system(), plus:
291 291
292 292 - split(0): if true, the output is returned as a list split on newlines.
293 293
294 294 Note: a stateful version of this function is available through the
295 295 SystemExec class."""
296 296
297 297 if verbose or debug: print header+cmd
298 298 if not debug:
299 299 output = commands.getoutput(cmd)
300 300 if split:
301 301 return output.split('\n')
302 302 else:
303 303 return output
304 304
305 305 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
306 306 """Return (standard output,standard error) of executing cmd in a shell.
307 307
308 308 Accepts the same arguments as system(), plus:
309 309
310 310 - split(0): if true, each of stdout/err is returned as a list split on
311 311 newlines.
312 312
313 313 Note: a stateful version of this function is available through the
314 314 SystemExec class."""
315 315
316 316 if verbose or debug: print header+cmd
317 317 if not cmd:
318 318 if split:
319 319 return [],[]
320 320 else:
321 321 return '',''
322 322 if not debug:
323 323 pin,pout,perr = os.popen3(cmd)
324 324 tout = pout.read().rstrip()
325 325 terr = perr.read().rstrip()
326 326 pin.close()
327 327 pout.close()
328 328 perr.close()
329 329 if split:
330 330 return tout.split('\n'),terr.split('\n')
331 331 else:
332 332 return tout,terr
333 333
334 334 # for compatibility with older naming conventions
335 335 xsys = system
336 336 bq = getoutput
337 337
338 338 class SystemExec:
339 339 """Access the system and getoutput functions through a stateful interface.
340 340
341 341 Note: here we refer to the system and getoutput functions from this
342 342 library, not the ones from the standard python library.
343 343
344 344 This class offers the system and getoutput functions as methods, but the
345 345 verbose, debug and header parameters can be set for the instance (at
346 346 creation time or later) so that they don't need to be specified on each
347 347 call.
348 348
349 349 For efficiency reasons, there's no way to override the parameters on a
350 350 per-call basis other than by setting instance attributes. If you need
351 351 local overrides, it's best to directly call system() or getoutput().
352 352
353 353 The following names are provided as alternate options:
354 354 - xsys: alias to system
355 355 - bq: alias to getoutput
356 356
357 357 An instance can then be created as:
358 358 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
359 359
360 360 And used as:
361 361 >>> sysexec.xsys('pwd')
362 362 >>> dirlist = sysexec.bq('ls -l')
363 363 """
364 364
365 365 def __init__(self,verbose=0,debug=0,header='',split=0):
366 366 """Specify the instance's values for verbose, debug and header."""
367 367 setattr_list(self,'verbose debug header split')
368 368
369 369 def system(self,cmd):
370 370 """Stateful interface to system(), with the same keyword parameters."""
371 371
372 372 system(cmd,self.verbose,self.debug,self.header)
373 373
374 374 def shell(self,cmd):
375 375 """Stateful interface to shell(), with the same keyword parameters."""
376 376
377 377 shell(cmd,self.verbose,self.debug,self.header)
378 378
379 379 xsys = system # alias
380 380
381 381 def getoutput(self,cmd):
382 382 """Stateful interface to getoutput()."""
383 383
384 384 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
385 385
386 386 def getoutputerror(self,cmd):
387 387 """Stateful interface to getoutputerror()."""
388 388
389 389 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
390 390
391 391 bq = getoutput # alias
392 392
393 393 #-----------------------------------------------------------------------------
394 394 def mutex_opts(dict,ex_op):
395 395 """Check for presence of mutually exclusive keys in a dict.
396 396
397 397 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
398 398 for op1,op2 in ex_op:
399 399 if op1 in dict and op2 in dict:
400 400 raise ValueError,'\n*** ERROR in Arguments *** '\
401 401 'Options '+op1+' and '+op2+' are mutually exclusive.'
402 402
403 403 #-----------------------------------------------------------------------------
404 404 def filefind(fname,alt_dirs = None):
405 405 """Return the given filename either in the current directory, if it
406 406 exists, or in a specified list of directories.
407 407
408 408 ~ expansion is done on all file and directory names.
409 409
410 410 Upon an unsuccessful search, raise an IOError exception."""
411 411
412 412 if alt_dirs is None:
413 413 try:
414 414 alt_dirs = get_home_dir()
415 415 except HomeDirError:
416 416 alt_dirs = os.getcwd()
417 417 search = [fname] + list_strings(alt_dirs)
418 418 search = map(os.path.expanduser,search)
419 419 #print 'search list for',fname,'list:',search # dbg
420 420 fname = search[0]
421 421 if os.path.isfile(fname):
422 422 return fname
423 423 for direc in search[1:]:
424 424 testname = os.path.join(direc,fname)
425 425 #print 'testname',testname # dbg
426 426 if os.path.isfile(testname):
427 427 return testname
428 428 raise IOError,'File' + `fname` + \
429 429 ' not found in current or supplied directories:' + `alt_dirs`
430 430
431 431 #----------------------------------------------------------------------------
432 432 def target_outdated(target,deps):
433 433 """Determine whether a target is out of date.
434 434
435 435 target_outdated(target,deps) -> 1/0
436 436
437 437 deps: list of filenames which MUST exist.
438 438 target: single filename which may or may not exist.
439 439
440 440 If target doesn't exist or is older than any file listed in deps, return
441 441 true, otherwise return false.
442 442 """
443 443 try:
444 444 target_time = os.path.getmtime(target)
445 445 except os.error:
446 446 return 1
447 447 for dep in deps:
448 448 dep_time = os.path.getmtime(dep)
449 449 if dep_time > target_time:
450 450 #print "For target",target,"Dep failed:",dep # dbg
451 451 #print "times (dep,tar):",dep_time,target_time # dbg
452 452 return 1
453 453 return 0
454 454
455 455 #-----------------------------------------------------------------------------
456 456 def target_update(target,deps,cmd):
457 457 """Update a target with a given command given a list of dependencies.
458 458
459 459 target_update(target,deps,cmd) -> runs cmd if target is outdated.
460 460
461 461 This is just a wrapper around target_outdated() which calls the given
462 462 command if target is outdated."""
463 463
464 464 if target_outdated(target,deps):
465 465 xsys(cmd)
466 466
467 467 #----------------------------------------------------------------------------
468 468 def unquote_ends(istr):
469 469 """Remove a single pair of quotes from the endpoints of a string."""
470 470
471 471 if not istr:
472 472 return istr
473 473 if (istr[0]=="'" and istr[-1]=="'") or \
474 474 (istr[0]=='"' and istr[-1]=='"'):
475 475 return istr[1:-1]
476 476 else:
477 477 return istr
478 478
479 479 #----------------------------------------------------------------------------
480 480 def process_cmdline(argv,names=[],defaults={},usage=''):
481 481 """ Process command-line options and arguments.
482 482
483 483 Arguments:
484 484
485 485 - argv: list of arguments, typically sys.argv.
486 486
487 487 - names: list of option names. See DPyGetOpt docs for details on options
488 488 syntax.
489 489
490 490 - defaults: dict of default values.
491 491
492 492 - usage: optional usage notice to print if a wrong argument is passed.
493 493
494 494 Return a dict of options and a list of free arguments."""
495 495
496 496 getopt = DPyGetOpt.DPyGetOpt()
497 497 getopt.setIgnoreCase(0)
498 498 getopt.parseConfiguration(names)
499 499
500 500 try:
501 501 getopt.processArguments(argv)
502 502 except:
503 503 print usage
504 504 warn(`sys.exc_value`,level=4)
505 505
506 506 defaults.update(getopt.optionValues)
507 507 args = getopt.freeValues
508 508
509 509 return defaults,args
510 510
511 511 #----------------------------------------------------------------------------
512 512 def optstr2types(ostr):
513 513 """Convert a string of option names to a dict of type mappings.
514 514
515 515 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
516 516
517 517 This is used to get the types of all the options in a string formatted
518 518 with the conventions of DPyGetOpt. The 'type' None is used for options
519 519 which are strings (they need no further conversion). This function's main
520 520 use is to get a typemap for use with read_dict().
521 521 """
522 522
523 523 typeconv = {None:'',int:'',float:''}
524 524 typemap = {'s':None,'i':int,'f':float}
525 525 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
526 526
527 527 for w in ostr.split():
528 528 oname,alias,otype = opt_re.match(w).groups()
529 529 if otype == '' or alias == '!': # simple switches are integers too
530 530 otype = 'i'
531 531 typeconv[typemap[otype]] += oname + ' '
532 532 return typeconv
533 533
534 534 #----------------------------------------------------------------------------
535 535 def read_dict(filename,type_conv=None,**opt):
536 536
537 537 """Read a dictionary of key=value pairs from an input file, optionally
538 538 performing conversions on the resulting values.
539 539
540 540 read_dict(filename,type_conv,**opt) -> dict
541 541
542 542 Only one value per line is accepted, the format should be
543 543 # optional comments are ignored
544 544 key value\n
545 545
546 546 Args:
547 547
548 548 - type_conv: A dictionary specifying which keys need to be converted to
549 549 which types. By default all keys are read as strings. This dictionary
550 550 should have as its keys valid conversion functions for strings
551 551 (int,long,float,complex, or your own). The value for each key
552 552 (converter) should be a whitespace separated string containing the names
553 553 of all the entries in the file to be converted using that function. For
554 554 keys to be left alone, use None as the conversion function (only needed
555 555 with purge=1, see below).
556 556
557 557 - opt: dictionary with extra options as below (default in parens)
558 558
559 559 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
560 560 of the dictionary to be returned. If purge is going to be used, the
561 561 set of keys to be left as strings also has to be explicitly specified
562 562 using the (non-existent) conversion function None.
563 563
564 564 fs(None): field separator. This is the key/value separator to be used
565 565 when parsing the file. The None default means any whitespace [behavior
566 566 of string.split()].
567 567
568 568 strip(0): if 1, strip string values of leading/trailinig whitespace.
569 569
570 570 warn(1): warning level if requested keys are not found in file.
571 571 - 0: silently ignore.
572 572 - 1: inform but proceed.
573 573 - 2: raise KeyError exception.
574 574
575 575 no_empty(0): if 1, remove keys with whitespace strings as a value.
576 576
577 577 unique([]): list of keys (or space separated string) which can't be
578 578 repeated. If one such key is found in the file, each new instance
579 579 overwrites the previous one. For keys not listed here, the behavior is
580 580 to make a list of all appearances.
581 581
582 582 Example:
583 583 If the input file test.ini has:
584 584 i 3
585 585 x 4.5
586 586 y 5.5
587 587 s hi ho
588 588 Then:
589 589
590 590 >>> type_conv={int:'i',float:'x',None:'s'}
591 591 >>> read_dict('test.ini')
592 592 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
593 593 >>> read_dict('test.ini',type_conv)
594 594 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
595 595 >>> read_dict('test.ini',type_conv,purge=1)
596 596 {'i': 3, 's': 'hi ho', 'x': 4.5}
597 597 """
598 598
599 599 # starting config
600 600 opt.setdefault('purge',0)
601 601 opt.setdefault('fs',None) # field sep defaults to any whitespace
602 602 opt.setdefault('strip',0)
603 603 opt.setdefault('warn',1)
604 604 opt.setdefault('no_empty',0)
605 605 opt.setdefault('unique','')
606 606 if type(opt['unique']) in StringTypes:
607 607 unique_keys = qw(opt['unique'])
608 608 elif type(opt['unique']) in (types.TupleType,types.ListType):
609 609 unique_keys = opt['unique']
610 610 else:
611 611 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
612 612
613 613 dict = {}
614 614 # first read in table of values as strings
615 615 file = open(filename,'r')
616 616 for line in file.readlines():
617 617 line = line.strip()
618 618 if len(line) and line[0]=='#': continue
619 619 if len(line)>0:
620 620 lsplit = line.split(opt['fs'],1)
621 621 try:
622 622 key,val = lsplit
623 623 except ValueError:
624 624 key,val = lsplit[0],''
625 625 key = key.strip()
626 626 if opt['strip']: val = val.strip()
627 627 if val == "''" or val == '""': val = ''
628 628 if opt['no_empty'] and (val=='' or val.isspace()):
629 629 continue
630 630 # if a key is found more than once in the file, build a list
631 631 # unless it's in the 'unique' list. In that case, last found in file
632 632 # takes precedence. User beware.
633 633 try:
634 634 if dict[key] and key in unique_keys:
635 635 dict[key] = val
636 636 elif type(dict[key]) is types.ListType:
637 637 dict[key].append(val)
638 638 else:
639 639 dict[key] = [dict[key],val]
640 640 except KeyError:
641 641 dict[key] = val
642 642 # purge if requested
643 643 if opt['purge']:
644 644 accepted_keys = qwflat(type_conv.values())
645 645 for key in dict.keys():
646 646 if key in accepted_keys: continue
647 647 del(dict[key])
648 648 # now convert if requested
649 649 if type_conv==None: return dict
650 650 conversions = type_conv.keys()
651 651 try: conversions.remove(None)
652 652 except: pass
653 653 for convert in conversions:
654 654 for val in qw(type_conv[convert]):
655 655 try:
656 656 dict[val] = convert(dict[val])
657 657 except KeyError,e:
658 658 if opt['warn'] == 0:
659 659 pass
660 660 elif opt['warn'] == 1:
661 661 print >>sys.stderr, 'Warning: key',val,\
662 662 'not found in file',filename
663 663 elif opt['warn'] == 2:
664 664 raise KeyError,e
665 665 else:
666 666 raise ValueError,'Warning level must be 0,1 or 2'
667 667
668 668 return dict
669 669
670 670 #----------------------------------------------------------------------------
671 671 def flag_calls(func):
672 672 """Wrap a function to detect and flag when it gets called.
673 673
674 674 This is a decorator which takes a function and wraps it in a function with
675 675 a 'called' attribute. wrapper.called is initialized to False.
676 676
677 677 The wrapper.called attribute is set to False right before each call to the
678 678 wrapped function, so if the call fails it remains False. After the call
679 679 completes, wrapper.called is set to True and the output is returned.
680 680
681 681 Testing for truth in wrapper.called allows you to determine if a call to
682 682 func() was attempted and succeeded."""
683 683
684 684 def wrapper(*args,**kw):
685 685 wrapper.called = False
686 686 out = func(*args,**kw)
687 687 wrapper.called = True
688 688 return out
689 689
690 690 wrapper.called = False
691 691 wrapper.__doc__ = func.__doc__
692 692 return wrapper
693 693
694 694 #----------------------------------------------------------------------------
695 695 class HomeDirError(Error):
696 696 pass
697 697
698 698 def get_home_dir():
699 699 """Return the closest possible equivalent to a 'home' directory.
700 700
701 701 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
702 702
703 703 Currently only Posix and NT are implemented, a HomeDirError exception is
704 704 raised for all other OSes. """
705 705
706 706 isdir = os.path.isdir
707 707 env = os.environ
708 708 try:
709 709 homedir = env['HOME']
710 710 if not isdir(homedir):
711 711 # in case a user stuck some string which does NOT resolve to a
712 712 # valid path, it's as good as if we hadn't foud it
713 713 raise KeyError
714 714 return homedir
715 715 except KeyError:
716 716 if os.name == 'posix':
717 717 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
718 718 elif os.name == 'nt':
719 719 # For some strange reason, win9x returns 'nt' for os.name.
720 720 try:
721 721 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
722 722 if not isdir(homedir):
723 723 homedir = os.path.join(env['USERPROFILE'])
724 724 if not isdir(homedir):
725 725 raise HomeDirError
726 726 return homedir
727 727 except:
728 728 try:
729 729 # Use the registry to get the 'My Documents' folder.
730 730 import _winreg as wreg
731 731 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
732 732 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
733 733 homedir = wreg.QueryValueEx(key,'Personal')[0]
734 734 key.Close()
735 if not isdir(homedir):
736 e = ('Invalid "Personal" folder registry key '
737 'typically "My Documents".\n'
738 'Value: %s\n'
739 'This is not a valid directory on your system.' %
740 homedir)
741 raise HomeDirError(e)
735 742 return homedir
743 except HomeDirError:
744 raise
736 745 except:
737 746 return 'C:\\'
738 747 elif os.name == 'dos':
739 748 # Desperate, may do absurd things in classic MacOS. May work under DOS.
740 749 return 'C:\\'
741 750 else:
742 751 raise HomeDirError,'support for your operating system not implemented.'
743 752
744 753 #****************************************************************************
745 754 # strings and text
746 755
747 756 class LSString(str):
748 757 """String derivative with a special access attributes.
749 758
750 759 These are normal strings, but with the special attributes:
751 760
752 761 .l (or .list) : value as list (split on newlines).
753 762 .n (or .nlstr): original value (the string itself).
754 763 .s (or .spstr): value as whitespace-separated string.
755 764
756 765 Any values which require transformations are computed only once and
757 766 cached.
758 767
759 768 Such strings are very useful to efficiently interact with the shell, which
760 769 typically only understands whitespace-separated options for commands."""
761 770
762 771 def get_list(self):
763 772 try:
764 773 return self.__list
765 774 except AttributeError:
766 775 self.__list = self.split('\n')
767 776 return self.__list
768 777
769 778 l = list = property(get_list)
770 779
771 780 def get_spstr(self):
772 781 try:
773 782 return self.__spstr
774 783 except AttributeError:
775 784 self.__spstr = self.replace('\n',' ')
776 785 return self.__spstr
777 786
778 787 s = spstr = property(get_spstr)
779 788
780 789 def get_nlstr(self):
781 790 return self
782 791
783 792 n = nlstr = property(get_nlstr)
784 793
785 794 class SList(list):
786 795 """List derivative with a special access attributes.
787 796
788 797 These are normal lists, but with the special attributes:
789 798
790 799 .l (or .list) : value as list (the list itself).
791 800 .n (or .nlstr): value as a string, joined on newlines.
792 801 .s (or .spstr): value as a string, joined on spaces.
793 802
794 803 Any values which require transformations are computed only once and
795 804 cached."""
796 805
797 806 def get_list(self):
798 807 return self
799 808
800 809 l = list = property(get_list)
801 810
802 811 def get_spstr(self):
803 812 try:
804 813 return self.__spstr
805 814 except AttributeError:
806 815 self.__spstr = ' '.join(self)
807 816 return self.__spstr
808 817
809 818 s = spstr = property(get_spstr)
810 819
811 820 def get_nlstr(self):
812 821 try:
813 822 return self.__nlstr
814 823 except AttributeError:
815 824 self.__nlstr = '\n'.join(self)
816 825 return self.__nlstr
817 826
818 827 n = nlstr = property(get_nlstr)
819 828
820 829 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
821 830 """Take multiple lines of input.
822 831
823 832 A list with each line of input as a separate element is returned when a
824 833 termination string is entered (defaults to a single '.'). Input can also
825 834 terminate via EOF (^D in Unix, ^Z-RET in Windows).
826 835
827 836 Lines of input which end in \\ are joined into single entries (and a
828 837 secondary continuation prompt is issued as long as the user terminates
829 838 lines with \\). This allows entering very long strings which are still
830 839 meant to be treated as single entities.
831 840 """
832 841
833 842 try:
834 843 if header:
835 844 header += '\n'
836 845 lines = [raw_input(header + ps1)]
837 846 except EOFError:
838 847 return []
839 848 terminate = [terminate_str]
840 849 try:
841 850 while lines[-1:] != terminate:
842 851 new_line = raw_input(ps1)
843 852 while new_line.endswith('\\'):
844 853 new_line = new_line[:-1] + raw_input(ps2)
845 854 lines.append(new_line)
846 855
847 856 return lines[:-1] # don't return the termination command
848 857 except EOFError:
849 858 print
850 859 return lines
851 860
852 861 #----------------------------------------------------------------------------
853 862 def raw_input_ext(prompt='', ps2='... '):
854 863 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
855 864
856 865 line = raw_input(prompt)
857 866 while line.endswith('\\'):
858 867 line = line[:-1] + raw_input(ps2)
859 868 return line
860 869
861 870 #----------------------------------------------------------------------------
862 871 def ask_yes_no(prompt,default=None):
863 872 """Asks a question and returns an integer 1/0 (y/n) answer.
864 873
865 874 If default is given (one of 'y','n'), it is used if the user input is
866 875 empty. Otherwise the question is repeated until an answer is given.
867 876 If EOF occurs 20 times consecutively, the default answer is assumed,
868 877 or if there is no default, an exception is raised to prevent infinite
869 878 loops.
870 879
871 880 Valid answers are: y/yes/n/no (match is not case sensitive)."""
872 881
873 882 answers = {'y':1,'n':0,'yes':1,'no':0}
874 883 ans = None
875 884 eofs, max_eofs = 0, 20
876 885 while ans not in answers.keys():
877 886 try:
878 887 ans = raw_input(prompt+' ').lower()
879 888 if not ans: # response was an empty string
880 889 ans = default
881 890 eofs = 0
882 891 except (EOFError,KeyboardInterrupt):
883 892 eofs = eofs + 1
884 893 if eofs >= max_eofs:
885 894 if default in answers.keys():
886 895 ans = default
887 896 else:
888 897 raise
889 898
890 899 return answers[ans]
891 900
892 901 #----------------------------------------------------------------------------
893 902 class EvalDict:
894 903 """
895 904 Emulate a dict which evaluates its contents in the caller's frame.
896 905
897 906 Usage:
898 907 >>>number = 19
899 908 >>>text = "python"
900 909 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
901 910 """
902 911
903 912 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
904 913 # modified (shorter) version of:
905 914 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
906 915 # Skip Montanaro (skip@pobox.com).
907 916
908 917 def __getitem__(self, name):
909 918 frame = sys._getframe(1)
910 919 return eval(name, frame.f_globals, frame.f_locals)
911 920
912 921 EvalString = EvalDict # for backwards compatibility
913 922 #----------------------------------------------------------------------------
914 923 def qw(words,flat=0,sep=None,maxsplit=-1):
915 924 """Similar to Perl's qw() operator, but with some more options.
916 925
917 926 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
918 927
919 928 words can also be a list itself, and with flat=1, the output will be
920 929 recursively flattened. Examples:
921 930
922 931 >>> qw('1 2')
923 932 ['1', '2']
924 933 >>> qw(['a b','1 2',['m n','p q']])
925 934 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
926 935 >>> qw(['a b','1 2',['m n','p q']],flat=1)
927 936 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
928 937
929 938 if type(words) in StringTypes:
930 939 return [word.strip() for word in words.split(sep,maxsplit)
931 940 if word and not word.isspace() ]
932 941 if flat:
933 942 return flatten(map(qw,words,[1]*len(words)))
934 943 return map(qw,words)
935 944
936 945 #----------------------------------------------------------------------------
937 946 def qwflat(words,sep=None,maxsplit=-1):
938 947 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
939 948 return qw(words,1,sep,maxsplit)
940 949
941 950 #-----------------------------------------------------------------------------
942 951 def list_strings(arg):
943 952 """Always return a list of strings, given a string or list of strings
944 953 as input."""
945 954
946 955 if type(arg) in StringTypes: return [arg]
947 956 else: return arg
948 957
949 958 #----------------------------------------------------------------------------
950 959 def grep(pat,list,case=1):
951 960 """Simple minded grep-like function.
952 961 grep(pat,list) returns occurrences of pat in list, None on failure.
953 962
954 963 It only does simple string matching, with no support for regexps. Use the
955 964 option case=0 for case-insensitive matching."""
956 965
957 966 # This is pretty crude. At least it should implement copying only references
958 967 # to the original data in case it's big. Now it copies the data for output.
959 968 out=[]
960 969 if case:
961 970 for term in list:
962 971 if term.find(pat)>-1: out.append(term)
963 972 else:
964 973 lpat=pat.lower()
965 974 for term in list:
966 975 if term.lower().find(lpat)>-1: out.append(term)
967 976
968 977 if len(out): return out
969 978 else: return None
970 979
971 980 #----------------------------------------------------------------------------
972 981 def dgrep(pat,*opts):
973 982 """Return grep() on dir()+dir(__builtins__).
974 983
975 984 A very common use of grep() when working interactively."""
976 985
977 986 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
978 987
979 988 #----------------------------------------------------------------------------
980 989 def idgrep(pat):
981 990 """Case-insensitive dgrep()"""
982 991
983 992 return dgrep(pat,0)
984 993
985 994 #----------------------------------------------------------------------------
986 995 def igrep(pat,list):
987 996 """Synonym for case-insensitive grep."""
988 997
989 998 return grep(pat,list,case=0)
990 999
991 1000 #----------------------------------------------------------------------------
992 1001 def indent(str,nspaces=4,ntabs=0):
993 1002 """Indent a string a given number of spaces or tabstops.
994 1003
995 1004 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
996 1005 """
997 1006 if str is None:
998 1007 return
999 1008 ind = '\t'*ntabs+' '*nspaces
1000 1009 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1001 1010 if outstr.endswith(os.linesep+ind):
1002 1011 return outstr[:-len(ind)]
1003 1012 else:
1004 1013 return outstr
1005 1014
1006 1015 #-----------------------------------------------------------------------------
1007 1016 def native_line_ends(filename,backup=1):
1008 1017 """Convert (in-place) a file to line-ends native to the current OS.
1009 1018
1010 1019 If the optional backup argument is given as false, no backup of the
1011 1020 original file is left. """
1012 1021
1013 1022 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1014 1023
1015 1024 bak_filename = filename + backup_suffixes[os.name]
1016 1025
1017 1026 original = open(filename).read()
1018 1027 shutil.copy2(filename,bak_filename)
1019 1028 try:
1020 1029 new = open(filename,'wb')
1021 1030 new.write(os.linesep.join(original.splitlines()))
1022 1031 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1023 1032 new.close()
1024 1033 except:
1025 1034 os.rename(bak_filename,filename)
1026 1035 if not backup:
1027 1036 try:
1028 1037 os.remove(bak_filename)
1029 1038 except:
1030 1039 pass
1031 1040
1032 1041 #----------------------------------------------------------------------------
1033 1042 def get_pager_cmd(pager_cmd = None):
1034 1043 """Return a pager command.
1035 1044
1036 1045 Makes some attempts at finding an OS-correct one."""
1037 1046
1038 1047 if os.name == 'posix':
1039 1048 default_pager_cmd = 'less -r' # -r for color control sequences
1040 1049 elif os.name in ['nt','dos']:
1041 1050 default_pager_cmd = 'type'
1042 1051
1043 1052 if pager_cmd is None:
1044 1053 try:
1045 1054 pager_cmd = os.environ['PAGER']
1046 1055 except:
1047 1056 pager_cmd = default_pager_cmd
1048 1057 return pager_cmd
1049 1058
1050 1059 #-----------------------------------------------------------------------------
1051 1060 def get_pager_start(pager,start):
1052 1061 """Return the string for paging files with an offset.
1053 1062
1054 1063 This is the '+N' argument which less and more (under Unix) accept.
1055 1064 """
1056 1065
1057 1066 if pager in ['less','more']:
1058 1067 if start:
1059 1068 start_string = '+' + str(start)
1060 1069 else:
1061 1070 start_string = ''
1062 1071 else:
1063 1072 start_string = ''
1064 1073 return start_string
1065 1074
1066 1075 #----------------------------------------------------------------------------
1067 1076 def page_dumb(strng,start=0,screen_lines=25):
1068 1077 """Very dumb 'pager' in Python, for when nothing else works.
1069 1078
1070 1079 Only moves forward, same interface as page(), except for pager_cmd and
1071 1080 mode."""
1072 1081
1073 1082 out_ln = strng.splitlines()[start:]
1074 1083 screens = chop(out_ln,screen_lines-1)
1075 1084 if len(screens) == 1:
1076 1085 print >>Term.cout, os.linesep.join(screens[0])
1077 1086 else:
1078 1087 for scr in screens[0:-1]:
1079 1088 print >>Term.cout, os.linesep.join(scr)
1080 1089 ans = raw_input('---Return to continue, q to quit--- ')
1081 1090 if ans.lower().startswith('q'):
1082 1091 return
1083 1092 print >>Term.cout, os.linesep.join(screens[-1])
1084 1093
1085 1094 #----------------------------------------------------------------------------
1086 1095 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1087 1096 """Print a string, piping through a pager after a certain length.
1088 1097
1089 1098 The screen_lines parameter specifies the number of *usable* lines of your
1090 1099 terminal screen (total lines minus lines you need to reserve to show other
1091 1100 information).
1092 1101
1093 1102 If you set screen_lines to a number <=0, page() will try to auto-determine
1094 1103 your screen size and will only use up to (screen_size+screen_lines) for
1095 1104 printing, paging after that. That is, if you want auto-detection but need
1096 1105 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1097 1106 auto-detection without any lines reserved simply use screen_lines = 0.
1098 1107
1099 1108 If a string won't fit in the allowed lines, it is sent through the
1100 1109 specified pager command. If none given, look for PAGER in the environment,
1101 1110 and ultimately default to less.
1102 1111
1103 1112 If no system pager works, the string is sent through a 'dumb pager'
1104 1113 written in python, very simplistic.
1105 1114 """
1106 1115
1107 1116 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1108 1117 TERM = os.environ.get('TERM','dumb')
1109 1118 if TERM in ['dumb','emacs'] and os.name != 'nt':
1110 1119 print strng
1111 1120 return
1112 1121 # chop off the topmost part of the string we don't want to see
1113 1122 str_lines = strng.split(os.linesep)[start:]
1114 1123 str_toprint = os.linesep.join(str_lines)
1115 1124 num_newlines = len(str_lines)
1116 1125 len_str = len(str_toprint)
1117 1126
1118 1127 # Dumb heuristics to guesstimate number of on-screen lines the string
1119 1128 # takes. Very basic, but good enough for docstrings in reasonable
1120 1129 # terminals. If someone later feels like refining it, it's not hard.
1121 1130 numlines = max(num_newlines,int(len_str/80)+1)
1122 1131
1123 1132 screen_lines_def = 25 # default value if we can't auto-determine
1124 1133
1125 1134 # auto-determine screen size
1126 1135 if screen_lines <= 0:
1127 1136 if TERM=='xterm':
1128 1137 try:
1129 1138 import curses
1130 1139 if hasattr(curses,'initscr'):
1131 1140 use_curses = 1
1132 1141 else:
1133 1142 use_curses = 0
1134 1143 except ImportError:
1135 1144 use_curses = 0
1136 1145 else:
1137 1146 # curses causes problems on many terminals other than xterm.
1138 1147 use_curses = 0
1139 1148 if use_curses:
1140 1149 scr = curses.initscr()
1141 1150 screen_lines_real,screen_cols = scr.getmaxyx()
1142 1151 curses.endwin()
1143 1152 screen_lines += screen_lines_real
1144 1153 #print '***Screen size:',screen_lines_real,'lines x',\
1145 1154 #screen_cols,'columns.' # dbg
1146 1155 else:
1147 1156 screen_lines += screen_lines_def
1148 1157
1149 1158 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1150 1159 if numlines <= screen_lines :
1151 1160 #print '*** normal print' # dbg
1152 1161 print >>Term.cout, str_toprint
1153 1162 else:
1154 1163 # Try to open pager and default to internal one if that fails.
1155 1164 # All failure modes are tagged as 'retval=1', to match the return
1156 1165 # value of a failed system command. If any intermediate attempt
1157 1166 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1158 1167 pager_cmd = get_pager_cmd(pager_cmd)
1159 1168 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1160 1169 if os.name == 'nt':
1161 1170 if pager_cmd.startswith('type'):
1162 1171 # The default WinXP 'type' command is failing on complex strings.
1163 1172 retval = 1
1164 1173 else:
1165 1174 tmpname = tempfile.mktemp('.txt')
1166 1175 tmpfile = file(tmpname,'wt')
1167 1176 tmpfile.write(strng)
1168 1177 tmpfile.close()
1169 1178 cmd = "%s < %s" % (pager_cmd,tmpname)
1170 1179 if os.system(cmd):
1171 1180 retval = 1
1172 1181 else:
1173 1182 retval = None
1174 1183 os.remove(tmpname)
1175 1184 else:
1176 1185 try:
1177 1186 retval = None
1178 1187 # if I use popen4, things hang. No idea why.
1179 1188 #pager,shell_out = os.popen4(pager_cmd)
1180 1189 pager = os.popen(pager_cmd,'w')
1181 1190 pager.write(strng)
1182 1191 pager.close()
1183 1192 retval = pager.close() # success returns None
1184 1193 except IOError,msg: # broken pipe when user quits
1185 1194 if msg.args == (32,'Broken pipe'):
1186 1195 retval = None
1187 1196 else:
1188 1197 retval = 1
1189 1198 except OSError:
1190 1199 # Other strange problems, sometimes seen in Win2k/cygwin
1191 1200 retval = 1
1192 1201 if retval is not None:
1193 1202 page_dumb(strng,screen_lines=screen_lines)
1194 1203
1195 1204 #----------------------------------------------------------------------------
1196 1205 def page_file(fname,start = 0, pager_cmd = None):
1197 1206 """Page a file, using an optional pager command and starting line.
1198 1207 """
1199 1208
1200 1209 pager_cmd = get_pager_cmd(pager_cmd)
1201 1210 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1202 1211
1203 1212 try:
1204 1213 if os.environ['TERM'] in ['emacs','dumb']:
1205 1214 raise EnvironmentError
1206 1215 xsys(pager_cmd + ' ' + fname)
1207 1216 except:
1208 1217 try:
1209 1218 if start > 0:
1210 1219 start -= 1
1211 1220 page(open(fname).read(),start)
1212 1221 except:
1213 1222 print 'Unable to show file',`fname`
1214 1223
1215 1224 #----------------------------------------------------------------------------
1216 1225 def snip_print(str,width = 75,print_full = 0,header = ''):
1217 1226 """Print a string snipping the midsection to fit in width.
1218 1227
1219 1228 print_full: mode control:
1220 1229 - 0: only snip long strings
1221 1230 - 1: send to page() directly.
1222 1231 - 2: snip long strings and ask for full length viewing with page()
1223 1232 Return 1 if snipping was necessary, 0 otherwise."""
1224 1233
1225 1234 if print_full == 1:
1226 1235 page(header+str)
1227 1236 return 0
1228 1237
1229 1238 print header,
1230 1239 if len(str) < width:
1231 1240 print str
1232 1241 snip = 0
1233 1242 else:
1234 1243 whalf = int((width -5)/2)
1235 1244 print str[:whalf] + ' <...> ' + str[-whalf:]
1236 1245 snip = 1
1237 1246 if snip and print_full == 2:
1238 1247 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1239 1248 page(str)
1240 1249 return snip
1241 1250
1242 1251 #****************************************************************************
1243 1252 # lists, dicts and structures
1244 1253
1245 1254 def belong(candidates,checklist):
1246 1255 """Check whether a list of items appear in a given list of options.
1247 1256
1248 1257 Returns a list of 1 and 0, one for each candidate given."""
1249 1258
1250 1259 return [x in checklist for x in candidates]
1251 1260
1252 1261 #----------------------------------------------------------------------------
1253 1262 def uniq_stable(elems):
1254 1263 """uniq_stable(elems) -> list
1255 1264
1256 1265 Return from an iterable, a list of all the unique elements in the input,
1257 1266 but maintaining the order in which they first appear.
1258 1267
1259 1268 A naive solution to this problem which just makes a dictionary with the
1260 1269 elements as keys fails to respect the stability condition, since
1261 1270 dictionaries are unsorted by nature.
1262 1271
1263 1272 Note: All elements in the input must be valid dictionary keys for this
1264 1273 routine to work, as it internally uses a dictionary for efficiency
1265 1274 reasons."""
1266 1275
1267 1276 unique = []
1268 1277 unique_dict = {}
1269 1278 for nn in elems:
1270 1279 if nn not in unique_dict:
1271 1280 unique.append(nn)
1272 1281 unique_dict[nn] = None
1273 1282 return unique
1274 1283
1275 1284 #----------------------------------------------------------------------------
1276 1285 class NLprinter:
1277 1286 """Print an arbitrarily nested list, indicating index numbers.
1278 1287
1279 1288 An instance of this class called nlprint is available and callable as a
1280 1289 function.
1281 1290
1282 1291 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1283 1292 and using 'sep' to separate the index from the value. """
1284 1293
1285 1294 def __init__(self):
1286 1295 self.depth = 0
1287 1296
1288 1297 def __call__(self,lst,pos='',**kw):
1289 1298 """Prints the nested list numbering levels."""
1290 1299 kw.setdefault('indent',' ')
1291 1300 kw.setdefault('sep',': ')
1292 1301 kw.setdefault('start',0)
1293 1302 kw.setdefault('stop',len(lst))
1294 1303 # we need to remove start and stop from kw so they don't propagate
1295 1304 # into a recursive call for a nested list.
1296 1305 start = kw['start']; del kw['start']
1297 1306 stop = kw['stop']; del kw['stop']
1298 1307 if self.depth == 0 and 'header' in kw.keys():
1299 1308 print kw['header']
1300 1309
1301 1310 for idx in range(start,stop):
1302 1311 elem = lst[idx]
1303 1312 if type(elem)==type([]):
1304 1313 self.depth += 1
1305 1314 self.__call__(elem,itpl('$pos$idx,'),**kw)
1306 1315 self.depth -= 1
1307 1316 else:
1308 1317 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1309 1318
1310 1319 nlprint = NLprinter()
1311 1320 #----------------------------------------------------------------------------
1312 1321 def all_belong(candidates,checklist):
1313 1322 """Check whether a list of items ALL appear in a given list of options.
1314 1323
1315 1324 Returns a single 1 or 0 value."""
1316 1325
1317 1326 return 1-(0 in [x in checklist for x in candidates])
1318 1327
1319 1328 #----------------------------------------------------------------------------
1320 1329 def sort_compare(lst1,lst2,inplace = 1):
1321 1330 """Sort and compare two lists.
1322 1331
1323 1332 By default it does it in place, thus modifying the lists. Use inplace = 0
1324 1333 to avoid that (at the cost of temporary copy creation)."""
1325 1334 if not inplace:
1326 1335 lst1 = lst1[:]
1327 1336 lst2 = lst2[:]
1328 1337 lst1.sort(); lst2.sort()
1329 1338 return lst1 == lst2
1330 1339
1331 1340 #----------------------------------------------------------------------------
1332 1341 def mkdict(**kwargs):
1333 1342 """Return a dict from a keyword list.
1334 1343
1335 1344 It's just syntactic sugar for making ditcionary creation more convenient:
1336 1345 # the standard way
1337 1346 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1338 1347 # a cleaner way
1339 1348 >>>data = dict(red=1, green=2, blue=3)
1340 1349
1341 1350 If you need more than this, look at the Struct() class."""
1342 1351
1343 1352 return kwargs
1344 1353
1345 1354 #----------------------------------------------------------------------------
1346 1355 def list2dict(lst):
1347 1356 """Takes a list of (key,value) pairs and turns it into a dict."""
1348 1357
1349 1358 dic = {}
1350 1359 for k,v in lst: dic[k] = v
1351 1360 return dic
1352 1361
1353 1362 #----------------------------------------------------------------------------
1354 1363 def list2dict2(lst,default=''):
1355 1364 """Takes a list and turns it into a dict.
1356 1365 Much slower than list2dict, but more versatile. This version can take
1357 1366 lists with sublists of arbitrary length (including sclars)."""
1358 1367
1359 1368 dic = {}
1360 1369 for elem in lst:
1361 1370 if type(elem) in (types.ListType,types.TupleType):
1362 1371 size = len(elem)
1363 1372 if size == 0:
1364 1373 pass
1365 1374 elif size == 1:
1366 1375 dic[elem] = default
1367 1376 else:
1368 1377 k,v = elem[0], elem[1:]
1369 1378 if len(v) == 1: v = v[0]
1370 1379 dic[k] = v
1371 1380 else:
1372 1381 dic[elem] = default
1373 1382 return dic
1374 1383
1375 1384 #----------------------------------------------------------------------------
1376 1385 def flatten(seq):
1377 1386 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1378 1387
1379 1388 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1380 1389
1381 1390 # if the x=0 isn't made, a *global* variable x is left over after calling
1382 1391 # this function, with the value of the last element in the return
1383 1392 # list. This does seem like a bug big time to me.
1384 1393
1385 1394 # the problem is fixed with the x=0, which seems to force the creation of
1386 1395 # a local name
1387 1396
1388 1397 x = 0
1389 1398 return [x for subseq in seq for x in subseq]
1390 1399
1391 1400 #----------------------------------------------------------------------------
1392 1401 def get_slice(seq,start=0,stop=None,step=1):
1393 1402 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1394 1403 if stop == None:
1395 1404 stop = len(seq)
1396 1405 item = lambda i: seq[i]
1397 1406 return map(item,xrange(start,stop,step))
1398 1407
1399 1408 #----------------------------------------------------------------------------
1400 1409 def chop(seq,size):
1401 1410 """Chop a sequence into chunks of the given size."""
1402 1411 chunk = lambda i: seq[i:i+size]
1403 1412 return map(chunk,xrange(0,len(seq),size))
1404 1413
1405 1414 #----------------------------------------------------------------------------
1406 1415 def with(object, **args):
1407 1416 """Set multiple attributes for an object, similar to Pascal's with.
1408 1417
1409 1418 Example:
1410 1419 with(jim,
1411 1420 born = 1960,
1412 1421 haircolour = 'Brown',
1413 1422 eyecolour = 'Green')
1414 1423
1415 1424 Credit: Greg Ewing, in
1416 1425 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1417 1426
1418 1427 object.__dict__.update(args)
1419 1428
1420 1429 #----------------------------------------------------------------------------
1421 1430 def setattr_list(obj,alist,nspace = None):
1422 1431 """Set a list of attributes for an object taken from a namespace.
1423 1432
1424 1433 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1425 1434 alist with their values taken from nspace, which must be a dict (something
1426 1435 like locals() will often do) If nspace isn't given, locals() of the
1427 1436 *caller* is used, so in most cases you can omit it.
1428 1437
1429 1438 Note that alist can be given as a string, which will be automatically
1430 1439 split into a list on whitespace. If given as a list, it must be a list of
1431 1440 *strings* (the variable names themselves), not of variables."""
1432 1441
1433 1442 # this grabs the local variables from the *previous* call frame -- that is
1434 1443 # the locals from the function that called setattr_list().
1435 1444 # - snipped from weave.inline()
1436 1445 if nspace is None:
1437 1446 call_frame = sys._getframe().f_back
1438 1447 nspace = call_frame.f_locals
1439 1448
1440 1449 if type(alist) in StringTypes:
1441 1450 alist = alist.split()
1442 1451 for attr in alist:
1443 1452 val = eval(attr,nspace)
1444 1453 setattr(obj,attr,val)
1445 1454
1446 1455 #----------------------------------------------------------------------------
1447 1456 def getattr_list(obj,alist,*args):
1448 1457 """getattr_list(obj,alist[, default]) -> attribute list.
1449 1458
1450 1459 Get a list of named attributes for an object. When a default argument is
1451 1460 given, it is returned when the attribute doesn't exist; without it, an
1452 1461 exception is raised in that case.
1453 1462
1454 1463 Note that alist can be given as a string, which will be automatically
1455 1464 split into a list on whitespace. If given as a list, it must be a list of
1456 1465 *strings* (the variable names themselves), not of variables."""
1457 1466
1458 1467 if type(alist) in StringTypes:
1459 1468 alist = alist.split()
1460 1469 if args:
1461 1470 if len(args)==1:
1462 1471 default = args[0]
1463 1472 return map(lambda attr: getattr(obj,attr,default),alist)
1464 1473 else:
1465 1474 raise ValueError,'getattr_list() takes only one optional argument'
1466 1475 else:
1467 1476 return map(lambda attr: getattr(obj,attr),alist)
1468 1477
1469 1478 #----------------------------------------------------------------------------
1470 1479 def map_method(method,object_list,*argseq,**kw):
1471 1480 """map_method(method,object_list,*args,**kw) -> list
1472 1481
1473 1482 Return a list of the results of applying the methods to the items of the
1474 1483 argument sequence(s). If more than one sequence is given, the method is
1475 1484 called with an argument list consisting of the corresponding item of each
1476 1485 sequence. All sequences must be of the same length.
1477 1486
1478 1487 Keyword arguments are passed verbatim to all objects called.
1479 1488
1480 1489 This is Python code, so it's not nearly as fast as the builtin map()."""
1481 1490
1482 1491 out_list = []
1483 1492 idx = 0
1484 1493 for object in object_list:
1485 1494 try:
1486 1495 handler = getattr(object, method)
1487 1496 except AttributeError:
1488 1497 out_list.append(None)
1489 1498 else:
1490 1499 if argseq:
1491 1500 args = map(lambda lst:lst[idx],argseq)
1492 1501 #print 'ob',object,'hand',handler,'ar',args # dbg
1493 1502 out_list.append(handler(args,**kw))
1494 1503 else:
1495 1504 out_list.append(handler(**kw))
1496 1505 idx += 1
1497 1506 return out_list
1498 1507
1499 1508 #----------------------------------------------------------------------------
1500 1509 # Proposed popitem() extension, written as a method
1501 1510
1502 1511 class NotGiven: pass
1503 1512
1504 1513 def popkey(dct,key,default=NotGiven):
1505 1514 """Return dct[key] and delete dct[key].
1506 1515
1507 1516 If default is given, return it if dct[key] doesn't exist, otherwise raise
1508 1517 KeyError. """
1509 1518
1510 1519 try:
1511 1520 val = dct[key]
1512 1521 except KeyError:
1513 1522 if default is NotGiven:
1514 1523 raise
1515 1524 else:
1516 1525 return default
1517 1526 else:
1518 1527 del dct[key]
1519 1528 return val
1520 1529 #*************************** end of file <genutils.py> **********************
1521 1530
@@ -1,2047 +1,2047 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 807 2005-09-07 01:55:33Z fperez $
9 $Id: iplib.py 874 2005-09-20 20:13:04Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, much of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. The Python License (sec. 2) allows for this, but it's always
23 23 # nice to acknowledge credit where credit is due.
24 24 #*****************************************************************************
25 25
26 26 #****************************************************************************
27 27 # Modules and globals
28 28
29 29 from __future__ import generators # for 2.2 backwards-compatibility
30 30
31 31 from IPython import Release
32 32 __author__ = '%s <%s>\n%s <%s>' % \
33 33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 34 __license__ = Release.license
35 35 __version__ = Release.version
36 36
37 37 # Python standard modules
38 38 import __main__
39 39 import __builtin__
40 40 import exceptions
41 41 import keyword
42 42 import new
43 43 import os, sys, shutil
44 44 import code, glob, types, re
45 45 import string, StringIO
46 46 import inspect, pydoc
47 47 import bdb, pdb
48 48 import UserList # don't subclass list so this works with Python2.1
49 49 from pprint import pprint, pformat
50 50 import cPickle as pickle
51 51 import traceback
52 52
53 53 # IPython's own modules
54 54 import IPython
55 55 from IPython import OInspect,PyColorize,ultraTB
56 56 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
57 57 from IPython.Logger import Logger
58 58 from IPython.Magic import Magic,magic2python,shlex_split
59 59 from IPython.usage import cmd_line_usage,interactive_usage
60 60 from IPython.Struct import Struct
61 61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 62 from IPython.FakeModule import FakeModule
63 63 from IPython.background_jobs import BackgroundJobManager
64 64 from IPython.genutils import *
65 65
66 66 # Global pointer to the running
67 67
68 68 # store the builtin raw_input globally, and use this always, in case user code
69 69 # overwrites it (like wx.py.PyShell does)
70 70 raw_input_original = raw_input
71 71
72 72 #****************************************************************************
73 73 # Some utility function definitions
74 74
75 75 class Bunch: pass
76 76
77 77 def esc_quotes(strng):
78 78 """Return the input string with single and double quotes escaped out"""
79 79
80 80 return strng.replace('"','\\"').replace("'","\\'")
81 81
82 82 def import_fail_info(mod_name,fns=None):
83 83 """Inform load failure for a module."""
84 84
85 85 if fns == None:
86 86 warn("Loading of %s failed.\n" % (mod_name,))
87 87 else:
88 88 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
89 89
90 90 def qw_lol(indata):
91 91 """qw_lol('a b') -> [['a','b']],
92 92 otherwise it's just a call to qw().
93 93
94 94 We need this to make sure the modules_some keys *always* end up as a
95 95 list of lists."""
96 96
97 97 if type(indata) in StringTypes:
98 98 return [qw(indata)]
99 99 else:
100 100 return qw(indata)
101 101
102 102 def ipmagic(arg_s):
103 103 """Call a magic function by name.
104 104
105 105 Input: a string containing the name of the magic function to call and any
106 106 additional arguments to be passed to the magic.
107 107
108 108 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
109 109 prompt:
110 110
111 111 In[1]: %name -opt foo bar
112 112
113 113 To call a magic without arguments, simply use ipmagic('name').
114 114
115 115 This provides a proper Python function to call IPython's magics in any
116 116 valid Python code you can type at the interpreter, including loops and
117 117 compound statements. It is added by IPython to the Python builtin
118 118 namespace upon initialization."""
119 119
120 120 args = arg_s.split(' ',1)
121 121 magic_name = args[0]
122 122 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
123 123 magic_name = magic_name[1:]
124 124 try:
125 125 magic_args = args[1]
126 126 except IndexError:
127 127 magic_args = ''
128 128 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
129 129 if fn is None:
130 130 error("Magic function `%s` not found." % magic_name)
131 131 else:
132 132 magic_args = __IPYTHON__.var_expand(magic_args)
133 133 return fn(magic_args)
134 134
135 135 def ipalias(arg_s):
136 136 """Call an alias by name.
137 137
138 138 Input: a string containing the name of the alias to call and any
139 139 additional arguments to be passed to the magic.
140 140
141 141 ipalias('name -opt foo bar') is equivalent to typing at the ipython
142 142 prompt:
143 143
144 144 In[1]: name -opt foo bar
145 145
146 146 To call an alias without arguments, simply use ipalias('name').
147 147
148 148 This provides a proper Python function to call IPython's aliases in any
149 149 valid Python code you can type at the interpreter, including loops and
150 150 compound statements. It is added by IPython to the Python builtin
151 151 namespace upon initialization."""
152 152
153 153 args = arg_s.split(' ',1)
154 154 alias_name = args[0]
155 155 try:
156 156 alias_args = args[1]
157 157 except IndexError:
158 158 alias_args = ''
159 159 if alias_name in __IPYTHON__.alias_table:
160 160 __IPYTHON__.call_alias(alias_name,alias_args)
161 161 else:
162 162 error("Alias `%s` not found." % alias_name)
163 163
164 164 #-----------------------------------------------------------------------------
165 165 # Local use classes
166 166 try:
167 167 from IPython import FlexCompleter
168 168
169 169 class MagicCompleter(FlexCompleter.Completer):
170 170 """Extension of the completer class to work on %-prefixed lines."""
171 171
172 172 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
173 173 """MagicCompleter() -> completer
174 174
175 175 Return a completer object suitable for use by the readline library
176 176 via readline.set_completer().
177 177
178 178 Inputs:
179 179
180 180 - shell: a pointer to the ipython shell itself. This is needed
181 181 because this completer knows about magic functions, and those can
182 182 only be accessed via the ipython instance.
183 183
184 184 - namespace: an optional dict where completions are performed.
185 185
186 186 - The optional omit__names parameter sets the completer to omit the
187 187 'magic' names (__magicname__) for python objects unless the text
188 188 to be completed explicitly starts with one or more underscores.
189 189
190 190 - If alias_table is supplied, it should be a dictionary of aliases
191 191 to complete. """
192 192
193 193 FlexCompleter.Completer.__init__(self,namespace)
194 194 self.magic_prefix = shell.name+'.magic_'
195 195 self.magic_escape = shell.ESC_MAGIC
196 196 self.readline = FlexCompleter.readline
197 197 delims = self.readline.get_completer_delims()
198 198 delims = delims.replace(self.magic_escape,'')
199 199 self.readline.set_completer_delims(delims)
200 200 self.get_line_buffer = self.readline.get_line_buffer
201 201 self.omit__names = omit__names
202 202 self.merge_completions = shell.rc.readline_merge_completions
203 203
204 204 if alias_table is None:
205 205 alias_table = {}
206 206 self.alias_table = alias_table
207 207 # Regexp to split filenames with spaces in them
208 208 self.space_name_re = re.compile(r'([^\\] )')
209 209 # Hold a local ref. to glob.glob for speed
210 210 self.glob = glob.glob
211 211 # Special handling of backslashes needed in win32 platforms
212 212 if sys.platform == "win32":
213 213 self.clean_glob = self._clean_glob_win32
214 214 else:
215 215 self.clean_glob = self._clean_glob
216 216 self.matchers = [self.python_matches,
217 217 self.file_matches,
218 218 self.alias_matches,
219 219 self.python_func_kw_matches]
220 220
221 221 # Code contributed by Alex Schmolck, for ipython/emacs integration
222 222 def all_completions(self, text):
223 223 """Return all possible completions for the benefit of emacs."""
224 224
225 225 completions = []
226 226 try:
227 227 for i in xrange(sys.maxint):
228 228 res = self.complete(text, i)
229 229
230 230 if not res: break
231 231
232 232 completions.append(res)
233 233 #XXX workaround for ``notDefined.<tab>``
234 234 except NameError:
235 235 pass
236 236 return completions
237 237 # /end Alex Schmolck code.
238 238
239 239 def _clean_glob(self,text):
240 240 return self.glob("%s*" % text)
241 241
242 242 def _clean_glob_win32(self,text):
243 243 return [f.replace("\\","/")
244 244 for f in self.glob("%s*" % text)]
245 245
246 246 def file_matches(self, text):
247 247 """Match filneames, expanding ~USER type strings.
248 248
249 249 Most of the seemingly convoluted logic in this completer is an
250 250 attempt to handle filenames with spaces in them. And yet it's not
251 251 quite perfect, because Python's readline doesn't expose all of the
252 252 GNU readline details needed for this to be done correctly.
253 253
254 254 For a filename with a space in it, the printed completions will be
255 255 only the parts after what's already been typed (instead of the
256 256 full completions, as is normally done). I don't think with the
257 257 current (as of Python 2.3) Python readline it's possible to do
258 258 better."""
259 259
260 260 #print 'Completer->file_matches: <%s>' % text # dbg
261 261
262 262 # chars that require escaping with backslash - i.e. chars
263 263 # that readline treats incorrectly as delimiters, but we
264 264 # don't want to treat as delimiters in filename matching
265 265 # when escaped with backslash
266 266
267 267 protectables = ' ()[]{}'
268 268
269 269 def protect_filename(s):
270 270 return "".join([(ch in protectables and '\\' + ch or ch)
271 271 for ch in s])
272 272
273 273 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
274 274 open_quotes = 0 # track strings with open quotes
275 275 try:
276 276 lsplit = shlex_split(lbuf)[-1]
277 277 except ValueError:
278 278 # typically an unmatched ", or backslash without escaped char.
279 279 if lbuf.count('"')==1:
280 280 open_quotes = 1
281 281 lsplit = lbuf.split('"')[-1]
282 282 elif lbuf.count("'")==1:
283 283 open_quotes = 1
284 284 lsplit = lbuf.split("'")[-1]
285 285 else:
286 286 return None
287 287 except IndexError:
288 288 # tab pressed on empty line
289 289 lsplit = ""
290 290
291 291 if lsplit != protect_filename(lsplit):
292 292 # if protectables are found, do matching on the whole escaped
293 293 # name
294 294 has_protectables = 1
295 295 text0,text = text,lsplit
296 296 else:
297 297 has_protectables = 0
298 298 text = os.path.expanduser(text)
299 299
300 300 if text == "":
301 301 return [protect_filename(f) for f in self.glob("*")]
302 302
303 303 m0 = self.clean_glob(text.replace('\\',''))
304 304 if has_protectables:
305 305 # If we had protectables, we need to revert our changes to the
306 306 # beginning of filename so that we don't double-write the part
307 307 # of the filename we have so far
308 308 len_lsplit = len(lsplit)
309 309 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
310 310 else:
311 311 if open_quotes:
312 312 # if we have a string with an open quote, we don't need to
313 313 # protect the names at all (and we _shouldn't_, as it
314 314 # would cause bugs when the filesystem call is made).
315 315 matches = m0
316 316 else:
317 317 matches = [protect_filename(f) for f in m0]
318 318 if len(matches) == 1 and os.path.isdir(matches[0]):
319 319 # Takes care of links to directories also. Use '/'
320 320 # explicitly, even under Windows, so that name completions
321 321 # don't end up escaped.
322 322 matches[0] += '/'
323 323 return matches
324 324
325 325 def alias_matches(self, text):
326 326 """Match internal system aliases"""
327 327 #print 'Completer->alias_matches:',text # dbg
328 328 text = os.path.expanduser(text)
329 329 aliases = self.alias_table.keys()
330 330 if text == "":
331 331 return aliases
332 332 else:
333 333 return [alias for alias in aliases if alias.startswith(text)]
334 334
335 335 def python_matches(self,text):
336 336 """Match attributes or global python names"""
337 337 #print 'Completer->python_matches' # dbg
338 338 if "." in text:
339 339 try:
340 340 matches = self.attr_matches(text)
341 341 if text.endswith('.') and self.omit__names:
342 342 if self.omit__names == 1:
343 343 # true if txt is _not_ a __ name, false otherwise:
344 344 no__name = (lambda txt:
345 345 re.match(r'.*\.__.*?__',txt) is None)
346 346 else:
347 347 # true if txt is _not_ a _ name, false otherwise:
348 348 no__name = (lambda txt:
349 349 re.match(r'.*\._.*?',txt) is None)
350 350 matches = filter(no__name, matches)
351 351 except NameError:
352 352 # catches <undefined attributes>.<tab>
353 353 matches = []
354 354 else:
355 355 matches = self.global_matches(text)
356 356 # this is so completion finds magics when automagic is on:
357 357 if matches == [] and not text.startswith(os.sep):
358 358 matches = self.attr_matches(self.magic_prefix+text)
359 359 return matches
360 360
361 361 def _default_arguments(self, obj):
362 362 """Return the list of default arguments of obj if it is callable,
363 363 or empty list otherwise."""
364 364
365 365 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
366 366 # for classes, check for __init__,__new__
367 367 if inspect.isclass(obj):
368 368 obj = (getattr(obj,'__init__',None) or
369 369 getattr(obj,'__new__',None))
370 370 # for all others, check if they are __call__able
371 371 elif hasattr(obj, '__call__'):
372 372 obj = obj.__call__
373 373 # XXX: is there a way to handle the builtins ?
374 374 try:
375 375 args,_,_1,defaults = inspect.getargspec(obj)
376 376 if defaults:
377 377 return args[-len(defaults):]
378 378 except TypeError: pass
379 379 return []
380 380
381 381 def python_func_kw_matches(self,text):
382 382 """Match named parameters (kwargs) of the last open function"""
383 383
384 384 if "." in text: # a parameter cannot be dotted
385 385 return []
386 386 try: regexp = self.__funcParamsRegex
387 387 except AttributeError:
388 388 regexp = self.__funcParamsRegex = re.compile(r'''
389 389 '.*?' | # single quoted strings or
390 390 ".*?" | # double quoted strings or
391 391 \w+ | # identifier
392 392 \S # other characters
393 393 ''', re.VERBOSE | re.DOTALL)
394 394 # 1. find the nearest identifier that comes before an unclosed
395 395 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
396 396 tokens = regexp.findall(self.get_line_buffer())
397 397 tokens.reverse()
398 398 iterTokens = iter(tokens); openPar = 0
399 399 for token in iterTokens:
400 400 if token == ')':
401 401 openPar -= 1
402 402 elif token == '(':
403 403 openPar += 1
404 404 if openPar > 0:
405 405 # found the last unclosed parenthesis
406 406 break
407 407 else:
408 408 return []
409 409 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
410 410 ids = []
411 411 isId = re.compile(r'\w+$').match
412 412 while True:
413 413 try:
414 414 ids.append(iterTokens.next())
415 415 if not isId(ids[-1]):
416 416 ids.pop(); break
417 417 if not iterTokens.next() == '.':
418 418 break
419 419 except StopIteration:
420 420 break
421 421 # lookup the candidate callable matches either using global_matches
422 422 # or attr_matches for dotted names
423 423 if len(ids) == 1:
424 424 callableMatches = self.global_matches(ids[0])
425 425 else:
426 426 callableMatches = self.attr_matches('.'.join(ids[::-1]))
427 427 argMatches = []
428 428 for callableMatch in callableMatches:
429 429 try: namedArgs = self._default_arguments(eval(callableMatch,
430 430 self.namespace))
431 431 except: continue
432 432 for namedArg in namedArgs:
433 433 if namedArg.startswith(text):
434 434 argMatches.append("%s=" %namedArg)
435 435 return argMatches
436 436
437 437 def complete(self, text, state):
438 438 """Return the next possible completion for 'text'.
439 439
440 440 This is called successively with state == 0, 1, 2, ... until it
441 441 returns None. The completion should begin with 'text'. """
442 442
443 443 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
444 444 magic_escape = self.magic_escape
445 445 magic_prefix = self.magic_prefix
446 446
447 447 try:
448 448 if text.startswith(magic_escape):
449 449 text = text.replace(magic_escape,magic_prefix)
450 450 elif text.startswith('~'):
451 451 text = os.path.expanduser(text)
452 452 if state == 0:
453 453 # Extend the list of completions with the results of each
454 454 # matcher, so we return results to the user from all
455 455 # namespaces.
456 456 if self.merge_completions:
457 457 self.matches = []
458 458 for matcher in self.matchers:
459 459 self.matches.extend(matcher(text))
460 460 else:
461 461 for matcher in self.matchers:
462 462 self.matches = matcher(text)
463 463 if self.matches:
464 464 break
465 465
466 466 try:
467 467 return self.matches[state].replace(magic_prefix,magic_escape)
468 468 except IndexError:
469 469 return None
470 470 except:
471 471 # If completion fails, don't annoy the user.
472 472 pass
473 473
474 474 except ImportError:
475 475 pass # no readline support
476 476
477 477 except KeyError:
478 478 pass # Windows doesn't set TERM, it doesn't matter
479 479
480 480
481 481 class InputList(UserList.UserList):
482 482 """Class to store user input.
483 483
484 484 It's basically a list, but slices return a string instead of a list, thus
485 485 allowing things like (assuming 'In' is an instance):
486 486
487 487 exec In[4:7]
488 488
489 489 or
490 490
491 491 exec In[5:9] + In[14] + In[21:25]"""
492 492
493 493 def __getslice__(self,i,j):
494 494 return ''.join(UserList.UserList.__getslice__(self,i,j))
495 495
496 496 #****************************************************************************
497 497 # Local use exceptions
498 498 class SpaceInInput(exceptions.Exception):
499 499 pass
500 500
501 501 #****************************************************************************
502 502 # Main IPython class
503 503
504 504 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
505 505 """An enhanced console for Python."""
506 506
507 507 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
508 508 user_ns = None,banner2='',
509 509 custom_exceptions=((),None)):
510 510
511 511 # Put a reference to self in builtins so that any form of embedded or
512 512 # imported code can test for being inside IPython.
513 513 __builtin__.__IPYTHON__ = self
514 514
515 515 # And load into builtins ipmagic/ipalias as well
516 516 __builtin__.ipmagic = ipmagic
517 517 __builtin__.ipalias = ipalias
518 518
519 519 # Add to __builtin__ other parts of IPython's public API
520 520 __builtin__.ip_set_hook = self.set_hook
521 521
522 522 # Keep in the builtins a flag for when IPython is active. We set it
523 523 # with setdefault so that multiple nested IPythons don't clobber one
524 524 # another. Each will increase its value by one upon being activated,
525 525 # which also gives us a way to determine the nesting level.
526 526 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
527 527
528 528 # Inform the user of ipython's fast exit magics.
529 529 _exit = ' Use %Exit or %Quit to exit without confirmation.'
530 530 __builtin__.exit += _exit
531 531 __builtin__.quit += _exit
532 532
533 533 # Create the namespace where the user will operate:
534 534
535 535 # FIXME. For some strange reason, __builtins__ is showing up at user
536 536 # level as a dict instead of a module. This is a manual fix, but I
537 537 # should really track down where the problem is coming from. Alex
538 538 # Schmolck reported this problem first.
539 539
540 540 # A useful post by Alex Martelli on this topic:
541 541 # Re: inconsistent value from __builtins__
542 542 # Von: Alex Martelli <aleaxit@yahoo.com>
543 543 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
544 544 # Gruppen: comp.lang.python
545 545 # Referenzen: 1
546 546
547 547 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
548 548 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
549 549 # > <type 'dict'>
550 550 # > >>> print type(__builtins__)
551 551 # > <type 'module'>
552 552 # > Is this difference in return value intentional?
553 553
554 554 # Well, it's documented that '__builtins__' can be either a dictionary
555 555 # or a module, and it's been that way for a long time. Whether it's
556 556 # intentional (or sensible), I don't know. In any case, the idea is that
557 557 # if you need to access the built-in namespace directly, you should start
558 558 # with "import __builtin__" (note, no 's') which will definitely give you
559 559 # a module. Yeah, it's somewhatΒ confusing:-(.
560 560
561 561 if user_ns is None:
562 562 # Set __name__ to __main__ to better match the behavior of the
563 563 # normal interpreter.
564 564 self.user_ns = {'__name__' :'__main__',
565 565 '__builtins__' : __builtin__,
566 566 }
567 567 else:
568 568 self.user_ns = user_ns
569 569
570 570 # The user namespace MUST have a pointer to the shell itself.
571 571 self.user_ns[name] = self
572 572
573 573 # We need to insert into sys.modules something that looks like a
574 574 # module but which accesses the IPython namespace, for shelve and
575 575 # pickle to work interactively. Normally they rely on getting
576 576 # everything out of __main__, but for embedding purposes each IPython
577 577 # instance has its own private namespace, so we can't go shoving
578 578 # everything into __main__.
579 579
580 580 try:
581 581 main_name = self.user_ns['__name__']
582 582 except KeyError:
583 583 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
584 584 else:
585 585 #print "pickle hack in place" # dbg
586 586 sys.modules[main_name] = FakeModule(self.user_ns)
587 587
588 588 # List of input with multi-line handling.
589 589 # Fill its zero entry, user counter starts at 1
590 590 self.input_hist = InputList(['\n'])
591 591
592 592 # list of visited directories
593 593 try:
594 594 self.dir_hist = [os.getcwd()]
595 595 except IOError, e:
596 596 self.dir_hist = []
597 597
598 598 # dict of output history
599 599 self.output_hist = {}
600 600
601 601 # dict of names to be treated as system aliases. Each entry in the
602 602 # alias table must be a 2-tuple of the form (N,name), where N is the
603 603 # number of positional arguments of the alias.
604 604 self.alias_table = {}
605 605
606 606 # dict of things NOT to alias (keywords, builtins and some special magics)
607 607 no_alias = {}
608 608 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
609 609 for key in keyword.kwlist + no_alias_magics:
610 610 no_alias[key] = 1
611 611 no_alias.update(__builtin__.__dict__)
612 612 self.no_alias = no_alias
613 613
614 614
615 615 # make global variables for user access to these
616 616 self.user_ns['_ih'] = self.input_hist
617 617 self.user_ns['_oh'] = self.output_hist
618 618 self.user_ns['_dh'] = self.dir_hist
619 619
620 620 # user aliases to input and output histories
621 621 self.user_ns['In'] = self.input_hist
622 622 self.user_ns['Out'] = self.output_hist
623 623
624 624 # Store the actual shell's name
625 625 self.name = name
626 626
627 627 # Object variable to store code object waiting execution. This is
628 628 # used mainly by the multithreaded shells, but it can come in handy in
629 629 # other situations. No need to use a Queue here, since it's a single
630 630 # item which gets cleared once run.
631 631 self.code_to_run = None
632 632
633 633 # Job manager (for jobs run as background threads)
634 634 self.jobs = BackgroundJobManager()
635 635 # Put the job manager into builtins so it's always there.
636 636 __builtin__.jobs = self.jobs
637 637
638 638 # escapes for automatic behavior on the command line
639 639 self.ESC_SHELL = '!'
640 640 self.ESC_HELP = '?'
641 641 self.ESC_MAGIC = '%'
642 642 self.ESC_QUOTE = ','
643 643 self.ESC_QUOTE2 = ';'
644 644 self.ESC_PAREN = '/'
645 645
646 646 # And their associated handlers
647 647 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
648 648 self.ESC_QUOTE:self.handle_auto,
649 649 self.ESC_QUOTE2:self.handle_auto,
650 650 self.ESC_MAGIC:self.handle_magic,
651 651 self.ESC_HELP:self.handle_help,
652 652 self.ESC_SHELL:self.handle_shell_escape,
653 653 }
654 654
655 655 # class initializations
656 656 code.InteractiveConsole.__init__(self,locals = self.user_ns)
657 657 Logger.__init__(self,log_ns = self.user_ns)
658 658 Magic.__init__(self,self)
659 659
660 660 # an ugly hack to get a pointer to the shell, so I can start writing
661 661 # magic code via this pointer instead of the current mixin salad.
662 662 Magic.set_shell(self,self)
663 663
664 664 # hooks holds pointers used for user-side customizations
665 665 self.hooks = Struct()
666 666
667 667 # Set all default hooks, defined in the IPython.hooks module.
668 668 hooks = IPython.hooks
669 669 for hook_name in hooks.__all__:
670 670 self.set_hook(hook_name,getattr(hooks,hook_name))
671 671
672 672 # Flag to mark unconditional exit
673 673 self.exit_now = False
674 674
675 675 self.usage_min = """\
676 676 An enhanced console for Python.
677 677 Some of its features are:
678 678 - Readline support if the readline library is present.
679 679 - Tab completion in the local namespace.
680 680 - Logging of input, see command-line options.
681 681 - System shell escape via ! , eg !ls.
682 682 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
683 683 - Keeps track of locally defined variables via %who, %whos.
684 684 - Show object information with a ? eg ?x or x? (use ?? for more info).
685 685 """
686 686 if usage: self.usage = usage
687 687 else: self.usage = self.usage_min
688 688
689 689 # Storage
690 690 self.rc = rc # This will hold all configuration information
691 691 self.inputcache = []
692 692 self._boundcache = []
693 693 self.pager = 'less'
694 694 # temporary files used for various purposes. Deleted at exit.
695 695 self.tempfiles = []
696 696
697 697 # Keep track of readline usage (later set by init_readline)
698 698 self.has_readline = 0
699 699
700 700 # for pushd/popd management
701 701 try:
702 702 self.home_dir = get_home_dir()
703 703 except HomeDirError,msg:
704 704 fatal(msg)
705 705
706 706 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
707 707
708 708 # Functions to call the underlying shell.
709 709
710 710 # utility to expand user variables via Itpl
711 711 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
712 712 self.user_ns))
713 713 # The first is similar to os.system, but it doesn't return a value,
714 714 # and it allows interpolation of variables in the user's namespace.
715 715 self.system = lambda cmd: shell(self.var_expand(cmd),
716 716 header='IPython system call: ',
717 717 verbose=self.rc.system_verbose)
718 718 # These are for getoutput and getoutputerror:
719 719 self.getoutput = lambda cmd: \
720 720 getoutput(self.var_expand(cmd),
721 721 header='IPython system call: ',
722 722 verbose=self.rc.system_verbose)
723 723 self.getoutputerror = lambda cmd: \
724 724 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
725 725 self.user_ns)),
726 726 header='IPython system call: ',
727 727 verbose=self.rc.system_verbose)
728 728
729 729 # RegExp for splitting line contents into pre-char//first
730 730 # word-method//rest. For clarity, each group in on one line.
731 731
732 732 # WARNING: update the regexp if the above escapes are changed, as they
733 733 # are hardwired in.
734 734
735 735 # Don't get carried away with trying to make the autocalling catch too
736 736 # much: it's better to be conservative rather than to trigger hidden
737 737 # evals() somewhere and end up causing side effects.
738 738
739 739 self.line_split = re.compile(r'^([\s*,;/])'
740 740 r'([\?\w\.]+\w*\s*)'
741 741 r'(\(?.*$)')
742 742
743 743 # Original re, keep around for a while in case changes break something
744 744 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
745 745 # r'(\s*[\?\w\.]+\w*\s*)'
746 746 # r'(\(?.*$)')
747 747
748 748 # RegExp to identify potential function names
749 749 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
750 750 # RegExp to exclude strings with this start from autocalling
751 751 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
752 752 # try to catch also methods for stuff in lists/tuples/dicts: off
753 753 # (experimental). For this to work, the line_split regexp would need
754 754 # to be modified so it wouldn't break things at '['. That line is
755 755 # nasty enough that I shouldn't change it until I can test it _well_.
756 756 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
757 757
758 758 # keep track of where we started running (mainly for crash post-mortem)
759 759 self.starting_dir = os.getcwd()
760 760
761 761 # Attributes for Logger mixin class, make defaults here
762 762 self._dolog = 0
763 763 self.LOG = ''
764 764 self.LOGDEF = '.InteractiveShell.log'
765 765 self.LOGMODE = 'over'
766 766 self.LOGHEAD = Itpl(
767 767 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
768 768 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
769 769 #log# opts = $self.rc.opts
770 770 #log# args = $self.rc.args
771 771 #log# It is safe to make manual edits below here.
772 772 #log#-----------------------------------------------------------------------
773 773 """)
774 774 # Various switches which can be set
775 775 self.CACHELENGTH = 5000 # this is cheap, it's just text
776 776 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
777 777 self.banner2 = banner2
778 778
779 779 # TraceBack handlers:
780 780 # Need two, one for syntax errors and one for other exceptions.
781 781 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
782 782 # This one is initialized with an offset, meaning we always want to
783 783 # remove the topmost item in the traceback, which is our own internal
784 784 # code. Valid modes: ['Plain','Context','Verbose']
785 785 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
786 786 color_scheme='NoColor',
787 787 tb_offset = 1)
788 788 # and add any custom exception handlers the user may have specified
789 789 self.set_custom_exc(*custom_exceptions)
790 790
791 791 # Object inspector
792 792 ins_colors = OInspect.InspectColors
793 793 code_colors = PyColorize.ANSICodeColors
794 794 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
795 795 self.autoindent = 0
796 796
797 797 # Make some aliases automatically
798 798 # Prepare list of shell aliases to auto-define
799 799 if os.name == 'posix':
800 800 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
801 801 'mv mv -i','rm rm -i','cp cp -i',
802 802 'cat cat','less less','clear clear',
803 803 # a better ls
804 804 'ls ls -F',
805 805 # long ls
806 806 'll ls -lF',
807 807 # color ls
808 808 'lc ls -F -o --color',
809 809 # ls normal files only
810 810 'lf ls -F -o --color %l | grep ^-',
811 811 # ls symbolic links
812 812 'lk ls -F -o --color %l | grep ^l',
813 813 # directories or links to directories,
814 814 'ldir ls -F -o --color %l | grep /$',
815 815 # things which are executable
816 816 'lx ls -F -o --color %l | grep ^-..x',
817 817 )
818 818 elif os.name in ['nt','dos']:
819 819 auto_alias = ('dir dir /on', 'ls dir /on',
820 820 'ddir dir /ad /on', 'ldir dir /ad /on',
821 821 'mkdir mkdir','rmdir rmdir','echo echo',
822 822 'ren ren','cls cls','copy copy')
823 823 else:
824 824 auto_alias = ()
825 825 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
826 826 # Call the actual (public) initializer
827 827 self.init_auto_alias()
828 828 # end __init__
829 829
830 830 def set_hook(self,name,hook):
831 831 """set_hook(name,hook) -> sets an internal IPython hook.
832 832
833 833 IPython exposes some of its internal API as user-modifiable hooks. By
834 834 resetting one of these hooks, you can modify IPython's behavior to
835 835 call at runtime your own routines."""
836 836
837 837 # At some point in the future, this should validate the hook before it
838 838 # accepts it. Probably at least check that the hook takes the number
839 839 # of args it's supposed to.
840 840 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
841 841
842 842 def set_custom_exc(self,exc_tuple,handler):
843 843 """set_custom_exc(exc_tuple,handler)
844 844
845 845 Set a custom exception handler, which will be called if any of the
846 846 exceptions in exc_tuple occur in the mainloop (specifically, in the
847 847 runcode() method.
848 848
849 849 Inputs:
850 850
851 851 - exc_tuple: a *tuple* of valid exceptions to call the defined
852 852 handler for. It is very important that you use a tuple, and NOT A
853 853 LIST here, because of the way Python's except statement works. If
854 854 you only want to trap a single exception, use a singleton tuple:
855 855
856 856 exc_tuple == (MyCustomException,)
857 857
858 858 - handler: this must be defined as a function with the following
859 859 basic interface: def my_handler(self,etype,value,tb).
860 860
861 861 This will be made into an instance method (via new.instancemethod)
862 862 of IPython itself, and it will be called if any of the exceptions
863 863 listed in the exc_tuple are caught. If the handler is None, an
864 864 internal basic one is used, which just prints basic info.
865 865
866 866 WARNING: by putting in your own exception handler into IPython's main
867 867 execution loop, you run a very good chance of nasty crashes. This
868 868 facility should only be used if you really know what you are doing."""
869 869
870 870 assert type(exc_tuple)==type(()) , \
871 871 "The custom exceptions must be given AS A TUPLE."
872 872
873 873 def dummy_handler(self,etype,value,tb):
874 874 print '*** Simple custom exception handler ***'
875 875 print 'Exception type :',etype
876 876 print 'Exception value:',value
877 877 print 'Traceback :',tb
878 878 print 'Source code :','\n'.join(self.buffer)
879 879
880 880 if handler is None: handler = dummy_handler
881 881
882 882 self.CustomTB = new.instancemethod(handler,self,self.__class__)
883 883 self.custom_exceptions = exc_tuple
884 884
885 885 def set_custom_completer(self,completer,pos=0):
886 886 """set_custom_completer(completer,pos=0)
887 887
888 888 Adds a new custom completer function.
889 889
890 890 The position argument (defaults to 0) is the index in the completers
891 891 list where you want the completer to be inserted."""
892 892
893 893 newcomp = new.instancemethod(completer,self.Completer,
894 894 self.Completer.__class__)
895 895 self.Completer.matchers.insert(pos,newcomp)
896 896
897 897 def complete(self,text):
898 898 """Return a sorted list of all possible completions on text.
899 899
900 900 Inputs:
901 901
902 902 - text: a string of text to be completed on.
903 903
904 904 This is a wrapper around the completion mechanism, similar to what
905 905 readline does at the command line when the TAB key is hit. By
906 906 exposing it as a method, it can be used by other non-readline
907 907 environments (such as GUIs) for text completion.
908 908
909 909 Simple usage example:
910 910
911 911 In [1]: x = 'hello'
912 912
913 913 In [2]: __IP.complete('x.l')
914 914 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
915 915
916 916 complete = self.Completer.complete
917 917 state = 0
918 918 # use a dict so we get unique keys, since ipyhton's multiple
919 919 # completers can return duplicates.
920 920 comps = {}
921 921 while True:
922 922 newcomp = complete(text,state)
923 923 if newcomp is None:
924 924 break
925 925 comps[newcomp] = 1
926 926 state += 1
927 927 outcomps = comps.keys()
928 928 outcomps.sort()
929 929 return outcomps
930 930
931 931 def post_config_initialization(self):
932 932 """Post configuration init method
933 933
934 934 This is called after the configuration files have been processed to
935 935 'finalize' the initialization."""
936 936
937 937 # dynamic data that survives through sessions
938 938 # XXX make the filename a config option?
939 939 persist_base = 'persist'
940 940 if self.rc.profile:
941 941 persist_base += '_%s' % self.rc.profile
942 942 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
943 943
944 944 try:
945 945 self.persist = pickle.load(file(self.persist_fname))
946 946 except:
947 947 self.persist = {}
948 948
949 949 def init_auto_alias(self):
950 950 """Define some aliases automatically.
951 951
952 952 These are ALL parameter-less aliases"""
953 953 for alias,cmd in self.auto_alias:
954 954 self.alias_table[alias] = (0,cmd)
955 955
956 956 def alias_table_validate(self,verbose=0):
957 957 """Update information about the alias table.
958 958
959 959 In particular, make sure no Python keywords/builtins are in it."""
960 960
961 961 no_alias = self.no_alias
962 for k in self.alias_table:
962 for k in self.alias_table.keys():
963 963 if k in no_alias:
964 964 del self.alias_table[k]
965 965 if verbose:
966 966 print ("Deleting alias <%s>, it's a Python "
967 967 "keyword or builtin." % k)
968 968
969 969 def set_autoindent(self,value=None):
970 970 """Set the autoindent flag, checking for readline support.
971 971
972 972 If called with no arguments, it acts as a toggle."""
973 973
974 974 if not self.has_readline:
975 975 if os.name == 'posix':
976 976 warn("The auto-indent feature requires the readline library")
977 977 self.autoindent = 0
978 978 return
979 979 if value is None:
980 980 self.autoindent = not self.autoindent
981 981 else:
982 982 self.autoindent = value
983 983
984 984 def rc_set_toggle(self,rc_field,value=None):
985 985 """Set or toggle a field in IPython's rc config. structure.
986 986
987 987 If called with no arguments, it acts as a toggle.
988 988
989 989 If called with a non-existent field, the resulting AttributeError
990 990 exception will propagate out."""
991 991
992 992 rc_val = getattr(self.rc,rc_field)
993 993 if value is None:
994 994 value = not rc_val
995 995 setattr(self.rc,rc_field,value)
996 996
997 997 def user_setup(self,ipythondir,rc_suffix,mode='install'):
998 998 """Install the user configuration directory.
999 999
1000 1000 Can be called when running for the first time or to upgrade the user's
1001 1001 .ipython/ directory with the mode parameter. Valid modes are 'install'
1002 1002 and 'upgrade'."""
1003 1003
1004 1004 def wait():
1005 1005 try:
1006 1006 raw_input("Please press <RETURN> to start IPython.")
1007 1007 except EOFError:
1008 1008 print >> Term.cout
1009 1009 print '*'*70
1010 1010
1011 1011 cwd = os.getcwd() # remember where we started
1012 1012 glb = glob.glob
1013 1013 print '*'*70
1014 1014 if mode == 'install':
1015 1015 print \
1016 1016 """Welcome to IPython. I will try to create a personal configuration directory
1017 1017 where you can customize many aspects of IPython's functionality in:\n"""
1018 1018 else:
1019 1019 print 'I am going to upgrade your configuration in:'
1020 1020
1021 1021 print ipythondir
1022 1022
1023 1023 rcdirend = os.path.join('IPython','UserConfig')
1024 1024 cfg = lambda d: os.path.join(d,rcdirend)
1025 1025 try:
1026 1026 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1027 1027 except IOError:
1028 1028 warning = """
1029 1029 Installation error. IPython's directory was not found.
1030 1030
1031 1031 Check the following:
1032 1032
1033 1033 The ipython/IPython directory should be in a directory belonging to your
1034 1034 PYTHONPATH environment variable (that is, it should be in a directory
1035 1035 belonging to sys.path). You can copy it explicitly there or just link to it.
1036 1036
1037 1037 IPython will proceed with builtin defaults.
1038 1038 """
1039 1039 warn(warning)
1040 1040 wait()
1041 1041 return
1042 1042
1043 1043 if mode == 'install':
1044 1044 try:
1045 1045 shutil.copytree(rcdir,ipythondir)
1046 1046 os.chdir(ipythondir)
1047 1047 rc_files = glb("ipythonrc*")
1048 1048 for rc_file in rc_files:
1049 1049 os.rename(rc_file,rc_file+rc_suffix)
1050 1050 except:
1051 1051 warning = """
1052 1052
1053 1053 There was a problem with the installation:
1054 1054 %s
1055 1055 Try to correct it or contact the developers if you think it's a bug.
1056 1056 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1057 1057 warn(warning)
1058 1058 wait()
1059 1059 return
1060 1060
1061 1061 elif mode == 'upgrade':
1062 1062 try:
1063 1063 os.chdir(ipythondir)
1064 1064 except:
1065 1065 print """
1066 1066 Can not upgrade: changing to directory %s failed. Details:
1067 1067 %s
1068 1068 """ % (ipythondir,sys.exc_info()[1])
1069 1069 wait()
1070 1070 return
1071 1071 else:
1072 1072 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1073 1073 for new_full_path in sources:
1074 1074 new_filename = os.path.basename(new_full_path)
1075 1075 if new_filename.startswith('ipythonrc'):
1076 1076 new_filename = new_filename + rc_suffix
1077 1077 # The config directory should only contain files, skip any
1078 1078 # directories which may be there (like CVS)
1079 1079 if os.path.isdir(new_full_path):
1080 1080 continue
1081 1081 if os.path.exists(new_filename):
1082 1082 old_file = new_filename+'.old'
1083 1083 if os.path.exists(old_file):
1084 1084 os.remove(old_file)
1085 1085 os.rename(new_filename,old_file)
1086 1086 shutil.copy(new_full_path,new_filename)
1087 1087 else:
1088 1088 raise ValueError,'unrecognized mode for install:',`mode`
1089 1089
1090 1090 # Fix line-endings to those native to each platform in the config
1091 1091 # directory.
1092 1092 try:
1093 1093 os.chdir(ipythondir)
1094 1094 except:
1095 1095 print """
1096 1096 Problem: changing to directory %s failed.
1097 1097 Details:
1098 1098 %s
1099 1099
1100 1100 Some configuration files may have incorrect line endings. This should not
1101 1101 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1102 1102 wait()
1103 1103 else:
1104 1104 for fname in glb('ipythonrc*'):
1105 1105 try:
1106 1106 native_line_ends(fname,backup=0)
1107 1107 except IOError:
1108 1108 pass
1109 1109
1110 1110 if mode == 'install':
1111 1111 print """
1112 1112 Successful installation!
1113 1113
1114 1114 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1115 1115 IPython manual (there are both HTML and PDF versions supplied with the
1116 1116 distribution) to make sure that your system environment is properly configured
1117 1117 to take advantage of IPython's features."""
1118 1118 else:
1119 1119 print """
1120 1120 Successful upgrade!
1121 1121
1122 1122 All files in your directory:
1123 1123 %(ipythondir)s
1124 1124 which would have been overwritten by the upgrade were backed up with a .old
1125 1125 extension. If you had made particular customizations in those files you may
1126 1126 want to merge them back into the new files.""" % locals()
1127 1127 wait()
1128 1128 os.chdir(cwd)
1129 1129 # end user_setup()
1130 1130
1131 1131 def atexit_operations(self):
1132 1132 """This will be executed at the time of exit.
1133 1133
1134 1134 Saving of persistent data should be performed here. """
1135 1135
1136 1136 # input history
1137 1137 self.savehist()
1138 1138
1139 1139 # Cleanup all tempfiles left around
1140 1140 for tfile in self.tempfiles:
1141 1141 try:
1142 1142 os.unlink(tfile)
1143 1143 except OSError:
1144 1144 pass
1145 1145
1146 1146 # save the "persistent data" catch-all dictionary
1147 1147 try:
1148 1148 pickle.dump(self.persist, open(self.persist_fname,"w"))
1149 1149 except:
1150 1150 print "*** ERROR *** persistent data saving failed."
1151 1151
1152 1152 def savehist(self):
1153 1153 """Save input history to a file (via readline library)."""
1154 1154 try:
1155 1155 self.readline.write_history_file(self.histfile)
1156 1156 except:
1157 1157 print 'Unable to save IPython command history to file: ' + \
1158 1158 `self.histfile`
1159 1159
1160 1160 def pre_readline(self):
1161 1161 """readline hook to be used at the start of each line.
1162 1162
1163 1163 Currently it handles auto-indent only."""
1164 1164
1165 1165 self.readline.insert_text(' '* self.readline_indent)
1166 1166
1167 1167 def init_readline(self):
1168 1168 """Command history completion/saving/reloading."""
1169 1169 try:
1170 1170 import readline
1171 1171 self.Completer = MagicCompleter(self,
1172 1172 self.user_ns,
1173 1173 self.rc.readline_omit__names,
1174 1174 self.alias_table)
1175 1175 except ImportError,NameError:
1176 1176 # If FlexCompleter failed to import, MagicCompleter won't be
1177 1177 # defined. This can happen because of a problem with readline
1178 1178 self.has_readline = 0
1179 1179 # no point in bugging windows users with this every time:
1180 1180 if os.name == 'posix':
1181 1181 warn('Readline services not available on this platform.')
1182 1182 else:
1183 1183 import atexit
1184 1184
1185 1185 # Platform-specific configuration
1186 1186 if os.name == 'nt':
1187 1187 # readline under Windows modifies the default exit behavior
1188 1188 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1189 1189 __builtin__.exit = __builtin__.quit = \
1190 1190 ('Use Ctrl-D (i.e. EOF) to exit. '
1191 1191 'Use %Exit or %Quit to exit without confirmation.')
1192 1192 self.readline_startup_hook = readline.set_pre_input_hook
1193 1193 else:
1194 1194 self.readline_startup_hook = readline.set_startup_hook
1195 1195
1196 1196 # Load user's initrc file (readline config)
1197 1197 inputrc_name = os.environ.get('INPUTRC')
1198 1198 if inputrc_name is None:
1199 1199 home_dir = get_home_dir()
1200 1200 if home_dir is not None:
1201 1201 inputrc_name = os.path.join(home_dir,'.inputrc')
1202 1202 if os.path.isfile(inputrc_name):
1203 1203 try:
1204 1204 readline.read_init_file(inputrc_name)
1205 1205 except:
1206 1206 warn('Problems reading readline initialization file <%s>'
1207 1207 % inputrc_name)
1208 1208
1209 1209 self.has_readline = 1
1210 1210 self.readline = readline
1211 1211 self.readline_indent = 0 # for auto-indenting via readline
1212 1212 # save this in sys so embedded copies can restore it properly
1213 1213 sys.ipcompleter = self.Completer.complete
1214 1214 readline.set_completer(self.Completer.complete)
1215 1215
1216 1216 # Configure readline according to user's prefs
1217 1217 for rlcommand in self.rc.readline_parse_and_bind:
1218 1218 readline.parse_and_bind(rlcommand)
1219 1219
1220 1220 # remove some chars from the delimiters list
1221 1221 delims = readline.get_completer_delims()
1222 1222 delims = delims.translate(string._idmap,
1223 1223 self.rc.readline_remove_delims)
1224 1224 readline.set_completer_delims(delims)
1225 1225 # otherwise we end up with a monster history after a while:
1226 1226 readline.set_history_length(1000)
1227 1227 try:
1228 1228 #print '*** Reading readline history' # dbg
1229 1229 readline.read_history_file(self.histfile)
1230 1230 except IOError:
1231 1231 pass # It doesn't exist yet.
1232 1232
1233 1233 atexit.register(self.atexit_operations)
1234 1234 del atexit
1235 1235
1236 1236 # Configure auto-indent for all platforms
1237 1237 self.set_autoindent(self.rc.autoindent)
1238 1238
1239 1239 def showsyntaxerror(self, filename=None):
1240 1240 """Display the syntax error that just occurred.
1241 1241
1242 1242 This doesn't display a stack trace because there isn't one.
1243 1243
1244 1244 If a filename is given, it is stuffed in the exception instead
1245 1245 of what was there before (because Python's parser always uses
1246 1246 "<string>" when reading from a string).
1247 1247 """
1248 1248 type, value, sys.last_traceback = sys.exc_info()
1249 1249 sys.last_type = type
1250 1250 sys.last_value = value
1251 1251 if filename and type is SyntaxError:
1252 1252 # Work hard to stuff the correct filename in the exception
1253 1253 try:
1254 1254 msg, (dummy_filename, lineno, offset, line) = value
1255 1255 except:
1256 1256 # Not the format we expect; leave it alone
1257 1257 pass
1258 1258 else:
1259 1259 # Stuff in the right filename
1260 1260 try:
1261 1261 # Assume SyntaxError is a class exception
1262 1262 value = SyntaxError(msg, (filename, lineno, offset, line))
1263 1263 except:
1264 1264 # If that failed, assume SyntaxError is a string
1265 1265 value = msg, (filename, lineno, offset, line)
1266 1266 self.SyntaxTB(type,value,[])
1267 1267
1268 1268 def debugger(self):
1269 1269 """Call the pdb debugger."""
1270 1270
1271 1271 if not self.rc.pdb:
1272 1272 return
1273 1273 pdb.pm()
1274 1274
1275 1275 def showtraceback(self,exc_tuple = None):
1276 1276 """Display the exception that just occurred."""
1277 1277
1278 1278 # Though this won't be called by syntax errors in the input line,
1279 1279 # there may be SyntaxError cases whith imported code.
1280 1280 if exc_tuple is None:
1281 1281 type, value, tb = sys.exc_info()
1282 1282 else:
1283 1283 type, value, tb = exc_tuple
1284 1284 if type is SyntaxError:
1285 1285 self.showsyntaxerror()
1286 1286 else:
1287 1287 sys.last_type = type
1288 1288 sys.last_value = value
1289 1289 sys.last_traceback = tb
1290 1290 self.InteractiveTB()
1291 1291 if self.InteractiveTB.call_pdb and self.has_readline:
1292 1292 # pdb mucks up readline, fix it back
1293 1293 self.readline.set_completer(self.Completer.complete)
1294 1294
1295 1295 def update_cache(self, line):
1296 1296 """puts line into cache"""
1297 1297 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1298 1298 if len(self.inputcache) >= self.CACHELENGTH:
1299 1299 self.inputcache.pop() # This not :-)
1300 1300
1301 1301 def name_space_init(self):
1302 1302 """Create local namespace."""
1303 1303 # We want this to be a method to facilitate embedded initialization.
1304 1304 code.InteractiveConsole.__init__(self,self.user_ns)
1305 1305
1306 1306 def mainloop(self,banner=None):
1307 1307 """Creates the local namespace and starts the mainloop.
1308 1308
1309 1309 If an optional banner argument is given, it will override the
1310 1310 internally created default banner."""
1311 1311
1312 1312 self.name_space_init()
1313 1313 if self.rc.c: # Emulate Python's -c option
1314 1314 self.exec_init_cmd()
1315 1315 if banner is None:
1316 1316 if self.rc.banner:
1317 1317 banner = self.BANNER+self.banner2
1318 1318 else:
1319 1319 banner = ''
1320 1320 self.interact(banner)
1321 1321
1322 1322 def exec_init_cmd(self):
1323 1323 """Execute a command given at the command line.
1324 1324
1325 1325 This emulates Python's -c option."""
1326 1326
1327 1327 sys.argv = ['-c']
1328 1328 self.push(self.rc.c)
1329 1329
1330 1330 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1331 1331 """Embeds IPython into a running python program.
1332 1332
1333 1333 Input:
1334 1334
1335 1335 - header: An optional header message can be specified.
1336 1336
1337 1337 - local_ns, global_ns: working namespaces. If given as None, the
1338 1338 IPython-initialized one is updated with __main__.__dict__, so that
1339 1339 program variables become visible but user-specific configuration
1340 1340 remains possible.
1341 1341
1342 1342 - stack_depth: specifies how many levels in the stack to go to
1343 1343 looking for namespaces (when local_ns and global_ns are None). This
1344 1344 allows an intermediate caller to make sure that this function gets
1345 1345 the namespace from the intended level in the stack. By default (0)
1346 1346 it will get its locals and globals from the immediate caller.
1347 1347
1348 1348 Warning: it's possible to use this in a program which is being run by
1349 1349 IPython itself (via %run), but some funny things will happen (a few
1350 1350 globals get overwritten). In the future this will be cleaned up, as
1351 1351 there is no fundamental reason why it can't work perfectly."""
1352 1352
1353 1353 # Patch for global embedding to make sure that things don't overwrite
1354 1354 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1355 1355 # FIXME. Test this a bit more carefully (the if.. is new)
1356 1356 if local_ns is None and global_ns is None:
1357 1357 self.user_ns.update(__main__.__dict__)
1358 1358
1359 1359 # Get locals and globals from caller
1360 1360 if local_ns is None or global_ns is None:
1361 1361 call_frame = sys._getframe(stack_depth).f_back
1362 1362
1363 1363 if local_ns is None:
1364 1364 local_ns = call_frame.f_locals
1365 1365 if global_ns is None:
1366 1366 global_ns = call_frame.f_globals
1367 1367
1368 1368 # Update namespaces and fire up interpreter
1369 1369 self.user_ns.update(local_ns)
1370 1370 self.interact(header)
1371 1371
1372 1372 # Remove locals from namespace
1373 1373 for k in local_ns:
1374 1374 del self.user_ns[k]
1375 1375
1376 1376 def interact(self, banner=None):
1377 1377 """Closely emulate the interactive Python console.
1378 1378
1379 1379 The optional banner argument specify the banner to print
1380 1380 before the first interaction; by default it prints a banner
1381 1381 similar to the one printed by the real Python interpreter,
1382 1382 followed by the current class name in parentheses (so as not
1383 1383 to confuse this with the real interpreter -- since it's so
1384 1384 close!).
1385 1385
1386 1386 """
1387 1387 cprt = 'Type "copyright", "credits" or "license" for more information.'
1388 1388 if banner is None:
1389 1389 self.write("Python %s on %s\n%s\n(%s)\n" %
1390 1390 (sys.version, sys.platform, cprt,
1391 1391 self.__class__.__name__))
1392 1392 else:
1393 1393 self.write(banner)
1394 1394
1395 1395 more = 0
1396 1396
1397 1397 # Mark activity in the builtins
1398 1398 __builtin__.__dict__['__IPYTHON__active'] += 1
1399 1399
1400 1400 # exit_now is set by a call to %Exit or %Quit
1401 1401 while not self.exit_now:
1402 1402 try:
1403 1403 if more:
1404 1404 prompt = self.outputcache.prompt2
1405 1405 if self.autoindent:
1406 1406 self.readline_startup_hook(self.pre_readline)
1407 1407 else:
1408 1408 prompt = self.outputcache.prompt1
1409 1409 try:
1410 1410 line = self.raw_input(prompt)
1411 1411 if self.autoindent:
1412 1412 self.readline_startup_hook(None)
1413 1413 except EOFError:
1414 1414 if self.autoindent:
1415 1415 self.readline_startup_hook(None)
1416 1416 self.write("\n")
1417 1417 if self.rc.confirm_exit:
1418 1418 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1419 1419 break
1420 1420 else:
1421 1421 break
1422 1422 else:
1423 1423 more = self.push(line)
1424 1424 # Auto-indent management
1425 1425 if self.autoindent:
1426 1426 if line:
1427 1427 ini_spaces = re.match('^(\s+)',line)
1428 1428 if ini_spaces:
1429 1429 nspaces = ini_spaces.end()
1430 1430 else:
1431 1431 nspaces = 0
1432 1432 self.readline_indent = nspaces
1433 1433
1434 1434 if line[-1] == ':':
1435 1435 self.readline_indent += 4
1436 1436 elif re.match(r'^\s+raise|^\s+return',line):
1437 1437 self.readline_indent -= 4
1438 1438 else:
1439 1439 self.readline_indent = 0
1440 1440
1441 1441 except KeyboardInterrupt:
1442 1442 self.write("\nKeyboardInterrupt\n")
1443 1443 self.resetbuffer()
1444 1444 more = 0
1445 1445 # keep cache in sync with the prompt counter:
1446 1446 self.outputcache.prompt_count -= 1
1447 1447
1448 1448 if self.autoindent:
1449 1449 self.readline_indent = 0
1450 1450
1451 1451 except bdb.BdbQuit:
1452 1452 warn("The Python debugger has exited with a BdbQuit exception.\n"
1453 1453 "Because of how pdb handles the stack, it is impossible\n"
1454 1454 "for IPython to properly format this particular exception.\n"
1455 1455 "IPython will resume normal operation.")
1456 1456
1457 1457 # We are off again...
1458 1458 __builtin__.__dict__['__IPYTHON__active'] -= 1
1459 1459
1460 1460 def excepthook(self, type, value, tb):
1461 1461 """One more defense for GUI apps that call sys.excepthook.
1462 1462
1463 1463 GUI frameworks like wxPython trap exceptions and call
1464 1464 sys.excepthook themselves. I guess this is a feature that
1465 1465 enables them to keep running after exceptions that would
1466 1466 otherwise kill their mainloop. This is a bother for IPython
1467 1467 which excepts to catch all of the program exceptions with a try:
1468 1468 except: statement.
1469 1469
1470 1470 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1471 1471 any app directly invokes sys.excepthook, it will look to the user like
1472 1472 IPython crashed. In order to work around this, we can disable the
1473 1473 CrashHandler and replace it with this excepthook instead, which prints a
1474 1474 regular traceback using our InteractiveTB. In this fashion, apps which
1475 1475 call sys.excepthook will generate a regular-looking exception from
1476 1476 IPython, and the CrashHandler will only be triggered by real IPython
1477 1477 crashes.
1478 1478
1479 1479 This hook should be used sparingly, only in places which are not likely
1480 1480 to be true IPython errors.
1481 1481 """
1482 1482
1483 1483 self.InteractiveTB(type, value, tb, tb_offset=0)
1484 1484 if self.InteractiveTB.call_pdb and self.has_readline:
1485 1485 self.readline.set_completer(self.Completer.complete)
1486 1486
1487 1487 def call_alias(self,alias,rest=''):
1488 1488 """Call an alias given its name and the rest of the line.
1489 1489
1490 1490 This function MUST be given a proper alias, because it doesn't make
1491 1491 any checks when looking up into the alias table. The caller is
1492 1492 responsible for invoking it only with a valid alias."""
1493 1493
1494 1494 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1495 1495 nargs,cmd = self.alias_table[alias]
1496 1496 # Expand the %l special to be the user's input line
1497 1497 if cmd.find('%l') >= 0:
1498 1498 cmd = cmd.replace('%l',rest)
1499 1499 rest = ''
1500 1500 if nargs==0:
1501 1501 # Simple, argument-less aliases
1502 1502 cmd = '%s %s' % (cmd,rest)
1503 1503 else:
1504 1504 # Handle aliases with positional arguments
1505 1505 args = rest.split(None,nargs)
1506 1506 if len(args)< nargs:
1507 1507 error('Alias <%s> requires %s arguments, %s given.' %
1508 1508 (alias,nargs,len(args)))
1509 1509 return
1510 1510 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1511 1511 # Now call the macro, evaluating in the user's namespace
1512 1512 try:
1513 1513 self.system(cmd)
1514 1514 except:
1515 1515 self.showtraceback()
1516 1516
1517 1517 def runlines(self,lines):
1518 1518 """Run a string of one or more lines of source.
1519 1519
1520 1520 This method is capable of running a string containing multiple source
1521 1521 lines, as if they had been entered at the IPython prompt. Since it
1522 1522 exposes IPython's processing machinery, the given strings can contain
1523 1523 magic calls (%magic), special shell access (!cmd), etc."""
1524 1524
1525 1525 # We must start with a clean buffer, in case this is run from an
1526 1526 # interactive IPython session (via a magic, for example).
1527 1527 self.resetbuffer()
1528 1528 lines = lines.split('\n')
1529 1529 more = 0
1530 1530 for line in lines:
1531 1531 # skip blank lines so we don't mess up the prompt counter, but do
1532 1532 # NOT skip even a blank line if we are in a code block (more is
1533 1533 # true)
1534 1534 if line or more:
1535 1535 more = self.push((self.prefilter(line,more)))
1536 1536 # IPython's runsource returns None if there was an error
1537 1537 # compiling the code. This allows us to stop processing right
1538 1538 # away, so the user gets the error message at the right place.
1539 1539 if more is None:
1540 1540 break
1541 1541 # final newline in case the input didn't have it, so that the code
1542 1542 # actually does get executed
1543 1543 if more:
1544 1544 self.push('\n')
1545 1545
1546 1546 def runsource(self, source, filename="<input>", symbol="single"):
1547 1547 """Compile and run some source in the interpreter.
1548 1548
1549 1549 Arguments are as for compile_command().
1550 1550
1551 1551 One several things can happen:
1552 1552
1553 1553 1) The input is incorrect; compile_command() raised an
1554 1554 exception (SyntaxError or OverflowError). A syntax traceback
1555 1555 will be printed by calling the showsyntaxerror() method.
1556 1556
1557 1557 2) The input is incomplete, and more input is required;
1558 1558 compile_command() returned None. Nothing happens.
1559 1559
1560 1560 3) The input is complete; compile_command() returned a code
1561 1561 object. The code is executed by calling self.runcode() (which
1562 1562 also handles run-time exceptions, except for SystemExit).
1563 1563
1564 1564 The return value is:
1565 1565
1566 1566 - True in case 2
1567 1567
1568 1568 - False in the other cases, unless an exception is raised, where
1569 1569 None is returned instead. This can be used by external callers to
1570 1570 know whether to continue feeding input or not.
1571 1571
1572 1572 The return value can be used to decide whether to use sys.ps1 or
1573 1573 sys.ps2 to prompt the next line."""
1574 1574
1575 1575 try:
1576 1576 code = self.compile(source, filename, symbol)
1577 1577 except (OverflowError, SyntaxError, ValueError):
1578 1578 # Case 1
1579 1579 self.showsyntaxerror(filename)
1580 1580 return None
1581 1581
1582 1582 if code is None:
1583 1583 # Case 2
1584 1584 return True
1585 1585
1586 1586 # Case 3
1587 1587 # We store the code object so that threaded shells and
1588 1588 # custom exception handlers can access all this info if needed.
1589 1589 # The source corresponding to this can be obtained from the
1590 1590 # buffer attribute as '\n'.join(self.buffer).
1591 1591 self.code_to_run = code
1592 1592 # now actually execute the code object
1593 1593 if self.runcode(code) == 0:
1594 1594 return False
1595 1595 else:
1596 1596 return None
1597 1597
1598 1598 def runcode(self,code_obj):
1599 1599 """Execute a code object.
1600 1600
1601 1601 When an exception occurs, self.showtraceback() is called to display a
1602 1602 traceback.
1603 1603
1604 1604 Return value: a flag indicating whether the code to be run completed
1605 1605 successfully:
1606 1606
1607 1607 - 0: successful execution.
1608 1608 - 1: an error occurred.
1609 1609 """
1610 1610
1611 1611 # Set our own excepthook in case the user code tries to call it
1612 1612 # directly, so that the IPython crash handler doesn't get triggered
1613 1613 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1614 1614 outflag = 1 # happens in more places, so it's easier as default
1615 1615 try:
1616 1616 try:
1617 1617 exec code_obj in self.locals
1618 1618 finally:
1619 1619 # Reset our crash handler in place
1620 1620 sys.excepthook = old_excepthook
1621 1621 except SystemExit:
1622 1622 self.resetbuffer()
1623 1623 self.showtraceback()
1624 1624 warn( __builtin__.exit,level=1)
1625 1625 except self.custom_exceptions:
1626 1626 etype,value,tb = sys.exc_info()
1627 1627 self.CustomTB(etype,value,tb)
1628 1628 except:
1629 1629 self.showtraceback()
1630 1630 else:
1631 1631 outflag = 0
1632 1632 if code.softspace(sys.stdout, 0):
1633 1633 print
1634 1634 # Flush out code object which has been run (and source)
1635 1635 self.code_to_run = None
1636 1636 return outflag
1637 1637
1638 1638 def raw_input(self, prompt=""):
1639 1639 """Write a prompt and read a line.
1640 1640
1641 1641 The returned line does not include the trailing newline.
1642 1642 When the user enters the EOF key sequence, EOFError is raised.
1643 1643
1644 1644 The base implementation uses the built-in function
1645 1645 raw_input(); a subclass may replace this with a different
1646 1646 implementation.
1647 1647 """
1648 1648 return self.prefilter(raw_input_original(prompt),
1649 1649 prompt==self.outputcache.prompt2)
1650 1650
1651 1651 def split_user_input(self,line):
1652 1652 """Split user input into pre-char, function part and rest."""
1653 1653
1654 1654 lsplit = self.line_split.match(line)
1655 1655 if lsplit is None: # no regexp match returns None
1656 1656 try:
1657 1657 iFun,theRest = line.split(None,1)
1658 1658 except ValueError:
1659 1659 iFun,theRest = line,''
1660 1660 pre = re.match('^(\s*)(.*)',line).groups()[0]
1661 1661 else:
1662 1662 pre,iFun,theRest = lsplit.groups()
1663 1663
1664 1664 #print 'line:<%s>' % line # dbg
1665 1665 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1666 1666 return pre,iFun.strip(),theRest
1667 1667
1668 1668 def _prefilter(self, line, continue_prompt):
1669 1669 """Calls different preprocessors, depending on the form of line."""
1670 1670
1671 1671 # All handlers *must* return a value, even if it's blank ('').
1672 1672
1673 1673 # Lines are NOT logged here. Handlers should process the line as
1674 1674 # needed, update the cache AND log it (so that the input cache array
1675 1675 # stays synced).
1676 1676
1677 1677 # This function is _very_ delicate, and since it's also the one which
1678 1678 # determines IPython's response to user input, it must be as efficient
1679 1679 # as possible. For this reason it has _many_ returns in it, trying
1680 1680 # always to exit as quickly as it can figure out what it needs to do.
1681 1681
1682 1682 # This function is the main responsible for maintaining IPython's
1683 1683 # behavior respectful of Python's semantics. So be _very_ careful if
1684 1684 # making changes to anything here.
1685 1685
1686 1686 #.....................................................................
1687 1687 # Code begins
1688 1688
1689 1689 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1690 1690
1691 1691 # save the line away in case we crash, so the post-mortem handler can
1692 1692 # record it
1693 1693 self._last_input_line = line
1694 1694
1695 1695 #print '***line: <%s>' % line # dbg
1696 1696
1697 1697 # the input history needs to track even empty lines
1698 1698 if not line.strip():
1699 1699 if not continue_prompt:
1700 1700 self.outputcache.prompt_count -= 1
1701 1701 return self.handle_normal('',continue_prompt)
1702 1702
1703 1703 # print '***cont',continue_prompt # dbg
1704 1704 # special handlers are only allowed for single line statements
1705 1705 if continue_prompt and not self.rc.multi_line_specials:
1706 1706 return self.handle_normal(line,continue_prompt)
1707 1707
1708 1708 # For the rest, we need the structure of the input
1709 1709 pre,iFun,theRest = self.split_user_input(line)
1710 1710 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1711 1711
1712 1712 # First check for explicit escapes in the last/first character
1713 1713 handler = None
1714 1714 if line[-1] == self.ESC_HELP:
1715 1715 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1716 1716 if handler is None:
1717 1717 # look at the first character of iFun, NOT of line, so we skip
1718 1718 # leading whitespace in multiline input
1719 1719 handler = self.esc_handlers.get(iFun[0:1])
1720 1720 if handler is not None:
1721 1721 return handler(line,continue_prompt,pre,iFun,theRest)
1722 1722 # Emacs ipython-mode tags certain input lines
1723 1723 if line.endswith('# PYTHON-MODE'):
1724 1724 return self.handle_emacs(line,continue_prompt)
1725 1725
1726 1726 # Next, check if we can automatically execute this thing
1727 1727
1728 1728 # Allow ! in multi-line statements if multi_line_specials is on:
1729 1729 if continue_prompt and self.rc.multi_line_specials and \
1730 1730 iFun.startswith(self.ESC_SHELL):
1731 1731 return self.handle_shell_escape(line,continue_prompt,
1732 1732 pre=pre,iFun=iFun,
1733 1733 theRest=theRest)
1734 1734
1735 1735 # Let's try to find if the input line is a magic fn
1736 1736 oinfo = None
1737 1737 if hasattr(self,'magic_'+iFun):
1738 1738 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1739 1739 if oinfo['ismagic']:
1740 1740 # Be careful not to call magics when a variable assignment is
1741 1741 # being made (ls='hi', for example)
1742 1742 if self.rc.automagic and \
1743 1743 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1744 1744 (self.rc.multi_line_specials or not continue_prompt):
1745 1745 return self.handle_magic(line,continue_prompt,
1746 1746 pre,iFun,theRest)
1747 1747 else:
1748 1748 return self.handle_normal(line,continue_prompt)
1749 1749
1750 1750 # If the rest of the line begins with an (in)equality, assginment or
1751 1751 # function call, we should not call _ofind but simply execute it.
1752 1752 # This avoids spurious geattr() accesses on objects upon assignment.
1753 1753 #
1754 1754 # It also allows users to assign to either alias or magic names true
1755 1755 # python variables (the magic/alias systems always take second seat to
1756 1756 # true python code).
1757 1757 if theRest and theRest[0] in '!=()':
1758 1758 return self.handle_normal(line,continue_prompt)
1759 1759
1760 1760 if oinfo is None:
1761 1761 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1762 1762
1763 1763 if not oinfo['found']:
1764 1764 return self.handle_normal(line,continue_prompt)
1765 1765 else:
1766 1766 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1767 1767 if oinfo['isalias']:
1768 1768 return self.handle_alias(line,continue_prompt,
1769 1769 pre,iFun,theRest)
1770 1770
1771 1771 if self.rc.autocall and \
1772 1772 not self.re_exclude_auto.match(theRest) and \
1773 1773 self.re_fun_name.match(iFun) and \
1774 1774 callable(oinfo['obj']) :
1775 1775 #print 'going auto' # dbg
1776 1776 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1777 1777 else:
1778 1778 #print 'was callable?', callable(oinfo['obj']) # dbg
1779 1779 return self.handle_normal(line,continue_prompt)
1780 1780
1781 1781 # If we get here, we have a normal Python line. Log and return.
1782 1782 return self.handle_normal(line,continue_prompt)
1783 1783
1784 1784 def _prefilter_dumb(self, line, continue_prompt):
1785 1785 """simple prefilter function, for debugging"""
1786 1786 return self.handle_normal(line,continue_prompt)
1787 1787
1788 1788 # Set the default prefilter() function (this can be user-overridden)
1789 1789 prefilter = _prefilter
1790 1790
1791 1791 def handle_normal(self,line,continue_prompt=None,
1792 1792 pre=None,iFun=None,theRest=None):
1793 1793 """Handle normal input lines. Use as a template for handlers."""
1794 1794
1795 1795 self.log(line,continue_prompt)
1796 1796 self.update_cache(line)
1797 1797 return line
1798 1798
1799 1799 def handle_alias(self,line,continue_prompt=None,
1800 1800 pre=None,iFun=None,theRest=None):
1801 1801 """Handle alias input lines. """
1802 1802
1803 1803 theRest = esc_quotes(theRest)
1804 1804 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1805 1805 self.log(line_out,continue_prompt)
1806 1806 self.update_cache(line_out)
1807 1807 return line_out
1808 1808
1809 1809 def handle_shell_escape(self, line, continue_prompt=None,
1810 1810 pre=None,iFun=None,theRest=None):
1811 1811 """Execute the line in a shell, empty return value"""
1812 1812
1813 1813 #print 'line in :', `line` # dbg
1814 1814 # Example of a special handler. Others follow a similar pattern.
1815 1815 if continue_prompt: # multi-line statements
1816 1816 if iFun.startswith('!!'):
1817 1817 print 'SyntaxError: !! is not allowed in multiline statements'
1818 1818 return pre
1819 1819 else:
1820 1820 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1821 1821 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1822 1822 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1823 1823 else: # single-line input
1824 1824 if line.startswith('!!'):
1825 1825 # rewrite iFun/theRest to properly hold the call to %sx and
1826 1826 # the actual command to be executed, so handle_magic can work
1827 1827 # correctly
1828 1828 theRest = '%s %s' % (iFun[2:],theRest)
1829 1829 iFun = 'sx'
1830 1830 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1831 1831 continue_prompt,pre,iFun,theRest)
1832 1832 else:
1833 1833 cmd = esc_quotes(line[1:])
1834 1834 line_out = '%s.system("%s")' % (self.name,cmd)
1835 1835 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1836 1836 # update cache/log and return
1837 1837 self.log(line_out,continue_prompt)
1838 1838 self.update_cache(line_out) # readline cache gets normal line
1839 1839 #print 'line out r:', `line_out` # dbg
1840 1840 #print 'line out s:', line_out # dbg
1841 1841 return line_out
1842 1842
1843 1843 def handle_magic(self, line, continue_prompt=None,
1844 1844 pre=None,iFun=None,theRest=None):
1845 1845 """Execute magic functions.
1846 1846
1847 1847 Also log them with a prepended # so the log is clean Python."""
1848 1848
1849 1849 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1850 1850 self.log(cmd,continue_prompt)
1851 1851 self.update_cache(line)
1852 1852 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1853 1853 return cmd
1854 1854
1855 1855 def handle_auto(self, line, continue_prompt=None,
1856 1856 pre=None,iFun=None,theRest=None):
1857 1857 """Hande lines which can be auto-executed, quoting if requested."""
1858 1858
1859 1859 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1860 1860
1861 1861 # This should only be active for single-line input!
1862 1862 if continue_prompt:
1863 1863 return line
1864 1864
1865 1865 if pre == self.ESC_QUOTE:
1866 1866 # Auto-quote splitting on whitespace
1867 1867 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1868 1868 elif pre == self.ESC_QUOTE2:
1869 1869 # Auto-quote whole string
1870 1870 newcmd = '%s("%s")' % (iFun,theRest)
1871 1871 else:
1872 1872 # Auto-paren
1873 1873 if theRest[0:1] in ('=','['):
1874 1874 # Don't autocall in these cases. They can be either
1875 1875 # rebindings of an existing callable's name, or item access
1876 1876 # for an object which is BOTH callable and implements
1877 1877 # __getitem__.
1878 1878 return '%s %s' % (iFun,theRest)
1879 1879 if theRest.endswith(';'):
1880 1880 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1881 1881 else:
1882 1882 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1883 1883
1884 1884 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1885 1885 # log what is now valid Python, not the actual user input (without the
1886 1886 # final newline)
1887 1887 self.log(newcmd,continue_prompt)
1888 1888 return newcmd
1889 1889
1890 1890 def handle_help(self, line, continue_prompt=None,
1891 1891 pre=None,iFun=None,theRest=None):
1892 1892 """Try to get some help for the object.
1893 1893
1894 1894 obj? or ?obj -> basic information.
1895 1895 obj?? or ??obj -> more details.
1896 1896 """
1897 1897
1898 1898 # We need to make sure that we don't process lines which would be
1899 1899 # otherwise valid python, such as "x=1 # what?"
1900 1900 try:
1901 1901 code.compile_command(line)
1902 1902 except SyntaxError:
1903 1903 # We should only handle as help stuff which is NOT valid syntax
1904 1904 if line[0]==self.ESC_HELP:
1905 1905 line = line[1:]
1906 1906 elif line[-1]==self.ESC_HELP:
1907 1907 line = line[:-1]
1908 1908 self.log('#?'+line)
1909 1909 self.update_cache(line)
1910 1910 if line:
1911 1911 self.magic_pinfo(line)
1912 1912 else:
1913 1913 page(self.usage,screen_lines=self.rc.screen_length)
1914 1914 return '' # Empty string is needed here!
1915 1915 except:
1916 1916 # Pass any other exceptions through to the normal handler
1917 1917 return self.handle_normal(line,continue_prompt)
1918 1918 else:
1919 1919 # If the code compiles ok, we should handle it normally
1920 1920 return self.handle_normal(line,continue_prompt)
1921 1921
1922 1922 def handle_emacs(self,line,continue_prompt=None,
1923 1923 pre=None,iFun=None,theRest=None):
1924 1924 """Handle input lines marked by python-mode."""
1925 1925
1926 1926 # Currently, nothing is done. Later more functionality can be added
1927 1927 # here if needed.
1928 1928
1929 1929 # The input cache shouldn't be updated
1930 1930
1931 1931 return line
1932 1932
1933 1933 def write(self,data):
1934 1934 """Write a string to the default output"""
1935 1935 Term.cout.write(data)
1936 1936
1937 1937 def write_err(self,data):
1938 1938 """Write a string to the default error output"""
1939 1939 Term.cerr.write(data)
1940 1940
1941 1941 def safe_execfile(self,fname,*where,**kw):
1942 1942 fname = os.path.expanduser(fname)
1943 1943
1944 1944 # find things also in current directory
1945 1945 dname = os.path.dirname(fname)
1946 1946 if not sys.path.count(dname):
1947 1947 sys.path.append(dname)
1948 1948
1949 1949 try:
1950 1950 xfile = open(fname)
1951 1951 except:
1952 1952 print >> Term.cerr, \
1953 1953 'Could not open file <%s> for safe execution.' % fname
1954 1954 return None
1955 1955
1956 1956 kw.setdefault('islog',0)
1957 1957 kw.setdefault('quiet',1)
1958 1958 kw.setdefault('exit_ignore',0)
1959 1959 first = xfile.readline()
1960 1960 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1961 1961 xfile.close()
1962 1962 # line by line execution
1963 1963 if first.startswith(_LOGHEAD) or kw['islog']:
1964 1964 print 'Loading log file <%s> one line at a time...' % fname
1965 1965 if kw['quiet']:
1966 1966 stdout_save = sys.stdout
1967 1967 sys.stdout = StringIO.StringIO()
1968 1968 try:
1969 1969 globs,locs = where[0:2]
1970 1970 except:
1971 1971 try:
1972 1972 globs = locs = where[0]
1973 1973 except:
1974 1974 globs = locs = globals()
1975 1975 badblocks = []
1976 1976
1977 1977 # we also need to identify indented blocks of code when replaying
1978 1978 # logs and put them together before passing them to an exec
1979 1979 # statement. This takes a bit of regexp and look-ahead work in the
1980 1980 # file. It's easiest if we swallow the whole thing in memory
1981 1981 # first, and manually walk through the lines list moving the
1982 1982 # counter ourselves.
1983 1983 indent_re = re.compile('\s+\S')
1984 1984 xfile = open(fname)
1985 1985 filelines = xfile.readlines()
1986 1986 xfile.close()
1987 1987 nlines = len(filelines)
1988 1988 lnum = 0
1989 1989 while lnum < nlines:
1990 1990 line = filelines[lnum]
1991 1991 lnum += 1
1992 1992 # don't re-insert logger status info into cache
1993 1993 if line.startswith('#log#'):
1994 1994 continue
1995 1995 elif line.startswith('#%s'% self.ESC_MAGIC):
1996 1996 self.update_cache(line[1:])
1997 1997 line = magic2python(line)
1998 1998 elif line.startswith('#!'):
1999 1999 self.update_cache(line[1:])
2000 2000 else:
2001 2001 # build a block of code (maybe a single line) for execution
2002 2002 block = line
2003 2003 try:
2004 2004 next = filelines[lnum] # lnum has already incremented
2005 2005 except:
2006 2006 next = None
2007 2007 while next and indent_re.match(next):
2008 2008 block += next
2009 2009 lnum += 1
2010 2010 try:
2011 2011 next = filelines[lnum]
2012 2012 except:
2013 2013 next = None
2014 2014 # now execute the block of one or more lines
2015 2015 try:
2016 2016 exec block in globs,locs
2017 2017 self.update_cache(block.rstrip())
2018 2018 except SystemExit:
2019 2019 pass
2020 2020 except:
2021 2021 badblocks.append(block.rstrip())
2022 2022 if kw['quiet']: # restore stdout
2023 2023 sys.stdout.close()
2024 2024 sys.stdout = stdout_save
2025 2025 print 'Finished replaying log file <%s>' % fname
2026 2026 if badblocks:
2027 2027 print >> sys.stderr, \
2028 2028 '\nThe following lines/blocks in file <%s> reported errors:' \
2029 2029 % fname
2030 2030 for badline in badblocks:
2031 2031 print >> sys.stderr, badline
2032 2032 else: # regular file execution
2033 2033 try:
2034 2034 execfile(fname,*where)
2035 2035 except SyntaxError:
2036 2036 etype, evalue = sys.exc_info()[0:2]
2037 2037 self.SyntaxTB(etype,evalue,[])
2038 2038 warn('Failure executing file: <%s>' % fname)
2039 2039 except SystemExit,status:
2040 2040 if not kw['exit_ignore']:
2041 2041 self.InteractiveTB()
2042 2042 warn('Failure executing file: <%s>' % fname)
2043 2043 except:
2044 2044 self.InteractiveTB()
2045 2045 warn('Failure executing file: <%s>' % fname)
2046 2046
2047 2047 #************************* end of file <iplib.py> *****************************
@@ -1,4357 +1,4370 b''
1 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * IPython/Shell.py (sigint_handler): Drastic simplification which
4 also seems to make Ctrl-C work correctly across threads! This is
5 so simple, that I can't beleive I'd missed it before. Needs more
6 testing, though.
7
8 * IPython/genutils.py (get_home_dir): add protection against
9 non-dirs in win32 registry.
10
11 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
12 bug where dict was mutated while iterating (pysh crash).
13
1 14 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
2 15
3 16 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
4 17 spurious newlines added by this routine. After a report by
5 18 F. Mantegazza.
6 19
7 20 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
8 21
9 22 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
10 23 calls. These were a leftover from the GTK 1.x days, and can cause
11 24 problems in certain cases (after a report by John Hunter).
12 25
13 26 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
14 27 os.getcwd() fails at init time. Thanks to patch from David Remahl
15 28 <chmod007 AT mac.com>.
16 29 (InteractiveShell.__init__): prevent certain special magics from
17 30 being shadowed by aliases. Closes
18 31 http://www.scipy.net/roundup/ipython/issue41.
19 32
20 33 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
21 34
22 35 * IPython/iplib.py (InteractiveShell.complete): Added new
23 36 top-level completion method to expose the completion mechanism
24 37 beyond readline-based environments.
25 38
26 39 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
27 40
28 41 * tools/ipsvnc (svnversion): fix svnversion capture.
29 42
30 43 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
31 44 attribute to self, which was missing. Before, it was set by a
32 45 routine which in certain cases wasn't being called, so the
33 46 instance could end up missing the attribute. This caused a crash.
34 47 Closes http://www.scipy.net/roundup/ipython/issue40.
35 48
36 49 2005-08-16 Fernando Perez <fperez@colorado.edu>
37 50
38 51 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
39 52 contains non-string attribute. Closes
40 53 http://www.scipy.net/roundup/ipython/issue38.
41 54
42 55 2005-08-14 Fernando Perez <fperez@colorado.edu>
43 56
44 57 * tools/ipsvnc: Minor improvements, to add changeset info.
45 58
46 59 2005-08-12 Fernando Perez <fperez@colorado.edu>
47 60
48 61 * IPython/iplib.py (runsource): remove self.code_to_run_src
49 62 attribute. I realized this is nothing more than
50 63 '\n'.join(self.buffer), and having the same data in two different
51 64 places is just asking for synchronization bugs. This may impact
52 65 people who have custom exception handlers, so I need to warn
53 66 ipython-dev about it (F. Mantegazza may use them).
54 67
55 68 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
56 69
57 70 * IPython/genutils.py: fix 2.2 compatibility (generators)
58 71
59 72 2005-07-18 Fernando Perez <fperez@colorado.edu>
60 73
61 74 * IPython/genutils.py (get_home_dir): fix to help users with
62 75 invalid $HOME under win32.
63 76
64 77 2005-07-17 Fernando Perez <fperez@colorado.edu>
65 78
66 79 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
67 80 some old hacks and clean up a bit other routines; code should be
68 81 simpler and a bit faster.
69 82
70 83 * IPython/iplib.py (interact): removed some last-resort attempts
71 84 to survive broken stdout/stderr. That code was only making it
72 85 harder to abstract out the i/o (necessary for gui integration),
73 86 and the crashes it could prevent were extremely rare in practice
74 87 (besides being fully user-induced in a pretty violent manner).
75 88
76 89 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
77 90 Nothing major yet, but the code is simpler to read; this should
78 91 make it easier to do more serious modifications in the future.
79 92
80 93 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
81 94 which broke in .15 (thanks to a report by Ville).
82 95
83 96 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
84 97 be quite correct, I know next to nothing about unicode). This
85 98 will allow unicode strings to be used in prompts, amongst other
86 99 cases. It also will prevent ipython from crashing when unicode
87 100 shows up unexpectedly in many places. If ascii encoding fails, we
88 101 assume utf_8. Currently the encoding is not a user-visible
89 102 setting, though it could be made so if there is demand for it.
90 103
91 104 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
92 105
93 106 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
94 107
95 108 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
96 109
97 110 * IPython/genutils.py: Add 2.2 compatibility here, so all other
98 111 code can work transparently for 2.2/2.3.
99 112
100 113 2005-07-16 Fernando Perez <fperez@colorado.edu>
101 114
102 115 * IPython/ultraTB.py (ExceptionColors): Make a global variable
103 116 out of the color scheme table used for coloring exception
104 117 tracebacks. This allows user code to add new schemes at runtime.
105 118 This is a minimally modified version of the patch at
106 119 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
107 120 for the contribution.
108 121
109 122 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
110 123 slightly modified version of the patch in
111 124 http://www.scipy.net/roundup/ipython/issue34, which also allows me
112 125 to remove the previous try/except solution (which was costlier).
113 126 Thanks to Gaetan Lehmann <gaetan.lehmann AT jouy.inra.fr> for the fix.
114 127
115 128 2005-06-08 Fernando Perez <fperez@colorado.edu>
116 129
117 130 * IPython/iplib.py (write/write_err): Add methods to abstract all
118 131 I/O a bit more.
119 132
120 133 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
121 134 warning, reported by Aric Hagberg, fix by JD Hunter.
122 135
123 136 2005-06-02 *** Released version 0.6.15
124 137
125 138 2005-06-01 Fernando Perez <fperez@colorado.edu>
126 139
127 140 * IPython/iplib.py (MagicCompleter.file_matches): Fix
128 141 tab-completion of filenames within open-quoted strings. Note that
129 142 this requires that in ~/.ipython/ipythonrc, users change the
130 143 readline delimiters configuration to read:
131 144
132 145 readline_remove_delims -/~
133 146
134 147
135 148 2005-05-31 *** Released version 0.6.14
136 149
137 150 2005-05-29 Fernando Perez <fperez@colorado.edu>
138 151
139 152 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
140 153 with files not on the filesystem. Reported by Eliyahu Sandler
141 154 <eli@gondolin.net>
142 155
143 156 2005-05-22 Fernando Perez <fperez@colorado.edu>
144 157
145 158 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
146 159 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
147 160
148 161 2005-05-19 Fernando Perez <fperez@colorado.edu>
149 162
150 163 * IPython/iplib.py (safe_execfile): close a file which could be
151 164 left open (causing problems in win32, which locks open files).
152 165 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
153 166
154 167 2005-05-18 Fernando Perez <fperez@colorado.edu>
155 168
156 169 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
157 170 keyword arguments correctly to safe_execfile().
158 171
159 172 2005-05-13 Fernando Perez <fperez@colorado.edu>
160 173
161 174 * ipython.1: Added info about Qt to manpage, and threads warning
162 175 to usage page (invoked with --help).
163 176
164 177 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
165 178 new matcher (it goes at the end of the priority list) to do
166 179 tab-completion on named function arguments. Submitted by George
167 180 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
168 181 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
169 182 for more details.
170 183
171 184 * IPython/Magic.py (magic_run): Added new -e flag to ignore
172 185 SystemExit exceptions in the script being run. Thanks to a report
173 186 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
174 187 producing very annoying behavior when running unit tests.
175 188
176 189 2005-05-12 Fernando Perez <fperez@colorado.edu>
177 190
178 191 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
179 192 which I'd broken (again) due to a changed regexp. In the process,
180 193 added ';' as an escape to auto-quote the whole line without
181 194 splitting its arguments. Thanks to a report by Jerry McRae
182 195 <qrs0xyc02-AT-sneakemail.com>.
183 196
184 197 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
185 198 possible crashes caused by a TokenError. Reported by Ed Schofield
186 199 <schofield-AT-ftw.at>.
187 200
188 201 2005-05-06 Fernando Perez <fperez@colorado.edu>
189 202
190 203 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
191 204
192 205 2005-04-29 Fernando Perez <fperez@colorado.edu>
193 206
194 207 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
195 208 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
196 209 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
197 210 which provides support for Qt interactive usage (similar to the
198 211 existing one for WX and GTK). This had been often requested.
199 212
200 213 2005-04-14 *** Released version 0.6.13
201 214
202 215 2005-04-08 Fernando Perez <fperez@colorado.edu>
203 216
204 217 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
205 218 from _ofind, which gets called on almost every input line. Now,
206 219 we only try to get docstrings if they are actually going to be
207 220 used (the overhead of fetching unnecessary docstrings can be
208 221 noticeable for certain objects, such as Pyro proxies).
209 222
210 223 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
211 224 for completers. For some reason I had been passing them the state
212 225 variable, which completers never actually need, and was in
213 226 conflict with the rlcompleter API. Custom completers ONLY need to
214 227 take the text parameter.
215 228
216 229 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
217 230 work correctly in pysh. I've also moved all the logic which used
218 231 to be in pysh.py here, which will prevent problems with future
219 232 upgrades. However, this time I must warn users to update their
220 233 pysh profile to include the line
221 234
222 235 import_all IPython.Extensions.InterpreterExec
223 236
224 237 because otherwise things won't work for them. They MUST also
225 238 delete pysh.py and the line
226 239
227 240 execfile pysh.py
228 241
229 242 from their ipythonrc-pysh.
230 243
231 244 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
232 245 robust in the face of objects whose dir() returns non-strings
233 246 (which it shouldn't, but some broken libs like ITK do). Thanks to
234 247 a patch by John Hunter (implemented differently, though). Also
235 248 minor improvements by using .extend instead of + on lists.
236 249
237 250 * pysh.py:
238 251
239 252 2005-04-06 Fernando Perez <fperez@colorado.edu>
240 253
241 254 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
242 255 by default, so that all users benefit from it. Those who don't
243 256 want it can still turn it off.
244 257
245 258 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
246 259 config file, I'd forgotten about this, so users were getting it
247 260 off by default.
248 261
249 262 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
250 263 consistency. Now magics can be called in multiline statements,
251 264 and python variables can be expanded in magic calls via $var.
252 265 This makes the magic system behave just like aliases or !system
253 266 calls.
254 267
255 268 2005-03-28 Fernando Perez <fperez@colorado.edu>
256 269
257 270 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
258 271 expensive string additions for building command. Add support for
259 272 trailing ';' when autocall is used.
260 273
261 274 2005-03-26 Fernando Perez <fperez@colorado.edu>
262 275
263 276 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
264 277 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
265 278 ipython.el robust against prompts with any number of spaces
266 279 (including 0) after the ':' character.
267 280
268 281 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
269 282 continuation prompt, which misled users to think the line was
270 283 already indented. Closes debian Bug#300847, reported to me by
271 284 Norbert Tretkowski <tretkowski-AT-inittab.de>.
272 285
273 286 2005-03-23 Fernando Perez <fperez@colorado.edu>
274 287
275 288 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
276 289 properly aligned if they have embedded newlines.
277 290
278 291 * IPython/iplib.py (runlines): Add a public method to expose
279 292 IPython's code execution machinery, so that users can run strings
280 293 as if they had been typed at the prompt interactively.
281 294 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
282 295 methods which can call the system shell, but with python variable
283 296 expansion. The three such methods are: __IPYTHON__.system,
284 297 .getoutput and .getoutputerror. These need to be documented in a
285 298 'public API' section (to be written) of the manual.
286 299
287 300 2005-03-20 Fernando Perez <fperez@colorado.edu>
288 301
289 302 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
290 303 for custom exception handling. This is quite powerful, and it
291 304 allows for user-installable exception handlers which can trap
292 305 custom exceptions at runtime and treat them separately from
293 306 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
294 307 Mantegazza <mantegazza-AT-ill.fr>.
295 308 (InteractiveShell.set_custom_completer): public API function to
296 309 add new completers at runtime.
297 310
298 311 2005-03-19 Fernando Perez <fperez@colorado.edu>
299 312
300 313 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
301 314 allow objects which provide their docstrings via non-standard
302 315 mechanisms (like Pyro proxies) to still be inspected by ipython's
303 316 ? system.
304 317
305 318 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
306 319 automatic capture system. I tried quite hard to make it work
307 320 reliably, and simply failed. I tried many combinations with the
308 321 subprocess module, but eventually nothing worked in all needed
309 322 cases (not blocking stdin for the child, duplicating stdout
310 323 without blocking, etc). The new %sc/%sx still do capture to these
311 324 magical list/string objects which make shell use much more
312 325 conveninent, so not all is lost.
313 326
314 327 XXX - FIX MANUAL for the change above!
315 328
316 329 (runsource): I copied code.py's runsource() into ipython to modify
317 330 it a bit. Now the code object and source to be executed are
318 331 stored in ipython. This makes this info accessible to third-party
319 332 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
320 333 Mantegazza <mantegazza-AT-ill.fr>.
321 334
322 335 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
323 336 history-search via readline (like C-p/C-n). I'd wanted this for a
324 337 long time, but only recently found out how to do it. For users
325 338 who already have their ipythonrc files made and want this, just
326 339 add:
327 340
328 341 readline_parse_and_bind "\e[A": history-search-backward
329 342 readline_parse_and_bind "\e[B": history-search-forward
330 343
331 344 2005-03-18 Fernando Perez <fperez@colorado.edu>
332 345
333 346 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
334 347 LSString and SList classes which allow transparent conversions
335 348 between list mode and whitespace-separated string.
336 349 (magic_r): Fix recursion problem in %r.
337 350
338 351 * IPython/genutils.py (LSString): New class to be used for
339 352 automatic storage of the results of all alias/system calls in _o
340 353 and _e (stdout/err). These provide a .l/.list attribute which
341 354 does automatic splitting on newlines. This means that for most
342 355 uses, you'll never need to do capturing of output with %sc/%sx
343 356 anymore, since ipython keeps this always done for you. Note that
344 357 only the LAST results are stored, the _o/e variables are
345 358 overwritten on each call. If you need to save their contents
346 359 further, simply bind them to any other name.
347 360
348 361 2005-03-17 Fernando Perez <fperez@colorado.edu>
349 362
350 363 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
351 364 prompt namespace handling.
352 365
353 366 2005-03-16 Fernando Perez <fperez@colorado.edu>
354 367
355 368 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
356 369 classic prompts to be '>>> ' (final space was missing, and it
357 370 trips the emacs python mode).
358 371 (BasePrompt.__str__): Added safe support for dynamic prompt
359 372 strings. Now you can set your prompt string to be '$x', and the
360 373 value of x will be printed from your interactive namespace. The
361 374 interpolation syntax includes the full Itpl support, so
362 375 ${foo()+x+bar()} is a valid prompt string now, and the function
363 376 calls will be made at runtime.
364 377
365 378 2005-03-15 Fernando Perez <fperez@colorado.edu>
366 379
367 380 * IPython/Magic.py (magic_history): renamed %hist to %history, to
368 381 avoid name clashes in pylab. %hist still works, it just forwards
369 382 the call to %history.
370 383
371 384 2005-03-02 *** Released version 0.6.12
372 385
373 386 2005-03-02 Fernando Perez <fperez@colorado.edu>
374 387
375 388 * IPython/iplib.py (handle_magic): log magic calls properly as
376 389 ipmagic() function calls.
377 390
378 391 * IPython/Magic.py (magic_time): Improved %time to support
379 392 statements and provide wall-clock as well as CPU time.
380 393
381 394 2005-02-27 Fernando Perez <fperez@colorado.edu>
382 395
383 396 * IPython/hooks.py: New hooks module, to expose user-modifiable
384 397 IPython functionality in a clean manner. For now only the editor
385 398 hook is actually written, and other thigns which I intend to turn
386 399 into proper hooks aren't yet there. The display and prefilter
387 400 stuff, for example, should be hooks. But at least now the
388 401 framework is in place, and the rest can be moved here with more
389 402 time later. IPython had had a .hooks variable for a long time for
390 403 this purpose, but I'd never actually used it for anything.
391 404
392 405 2005-02-26 Fernando Perez <fperez@colorado.edu>
393 406
394 407 * IPython/ipmaker.py (make_IPython): make the default ipython
395 408 directory be called _ipython under win32, to follow more the
396 409 naming peculiarities of that platform (where buggy software like
397 410 Visual Sourcesafe breaks with .named directories). Reported by
398 411 Ville Vainio.
399 412
400 413 2005-02-23 Fernando Perez <fperez@colorado.edu>
401 414
402 415 * IPython/iplib.py (InteractiveShell.__init__): removed a few
403 416 auto_aliases for win32 which were causing problems. Users can
404 417 define the ones they personally like.
405 418
406 419 2005-02-21 Fernando Perez <fperez@colorado.edu>
407 420
408 421 * IPython/Magic.py (magic_time): new magic to time execution of
409 422 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
410 423
411 424 2005-02-19 Fernando Perez <fperez@colorado.edu>
412 425
413 426 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
414 427 into keys (for prompts, for example).
415 428
416 429 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
417 430 prompts in case users want them. This introduces a small behavior
418 431 change: ipython does not automatically add a space to all prompts
419 432 anymore. To get the old prompts with a space, users should add it
420 433 manually to their ipythonrc file, so for example prompt_in1 should
421 434 now read 'In [\#]: ' instead of 'In [\#]:'.
422 435 (BasePrompt.__init__): New option prompts_pad_left (only in rc
423 436 file) to control left-padding of secondary prompts.
424 437
425 438 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
426 439 the profiler can't be imported. Fix for Debian, which removed
427 440 profile.py because of License issues. I applied a slightly
428 441 modified version of the original Debian patch at
429 442 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
430 443
431 444 2005-02-17 Fernando Perez <fperez@colorado.edu>
432 445
433 446 * IPython/genutils.py (native_line_ends): Fix bug which would
434 447 cause improper line-ends under win32 b/c I was not opening files
435 448 in binary mode. Bug report and fix thanks to Ville.
436 449
437 450 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
438 451 trying to catch spurious foo[1] autocalls. My fix actually broke
439 452 ',/' autoquote/call with explicit escape (bad regexp).
440 453
441 454 2005-02-15 *** Released version 0.6.11
442 455
443 456 2005-02-14 Fernando Perez <fperez@colorado.edu>
444 457
445 458 * IPython/background_jobs.py: New background job management
446 459 subsystem. This is implemented via a new set of classes, and
447 460 IPython now provides a builtin 'jobs' object for background job
448 461 execution. A convenience %bg magic serves as a lightweight
449 462 frontend for starting the more common type of calls. This was
450 463 inspired by discussions with B. Granger and the BackgroundCommand
451 464 class described in the book Python Scripting for Computational
452 465 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
453 466 (although ultimately no code from this text was used, as IPython's
454 467 system is a separate implementation).
455 468
456 469 * IPython/iplib.py (MagicCompleter.python_matches): add new option
457 470 to control the completion of single/double underscore names
458 471 separately. As documented in the example ipytonrc file, the
459 472 readline_omit__names variable can now be set to 2, to omit even
460 473 single underscore names. Thanks to a patch by Brian Wong
461 474 <BrianWong-AT-AirgoNetworks.Com>.
462 475 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
463 476 be autocalled as foo([1]) if foo were callable. A problem for
464 477 things which are both callable and implement __getitem__.
465 478 (init_readline): Fix autoindentation for win32. Thanks to a patch
466 479 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
467 480
468 481 2005-02-12 Fernando Perez <fperez@colorado.edu>
469 482
470 483 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
471 484 which I had written long ago to sort out user error messages which
472 485 may occur during startup. This seemed like a good idea initially,
473 486 but it has proven a disaster in retrospect. I don't want to
474 487 change much code for now, so my fix is to set the internal 'debug'
475 488 flag to true everywhere, whose only job was precisely to control
476 489 this subsystem. This closes issue 28 (as well as avoiding all
477 490 sorts of strange hangups which occur from time to time).
478 491
479 492 2005-02-07 Fernando Perez <fperez@colorado.edu>
480 493
481 494 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
482 495 previous call produced a syntax error.
483 496
484 497 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
485 498 classes without constructor.
486 499
487 500 2005-02-06 Fernando Perez <fperez@colorado.edu>
488 501
489 502 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
490 503 completions with the results of each matcher, so we return results
491 504 to the user from all namespaces. This breaks with ipython
492 505 tradition, but I think it's a nicer behavior. Now you get all
493 506 possible completions listed, from all possible namespaces (python,
494 507 filesystem, magics...) After a request by John Hunter
495 508 <jdhunter-AT-nitace.bsd.uchicago.edu>.
496 509
497 510 2005-02-05 Fernando Perez <fperez@colorado.edu>
498 511
499 512 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
500 513 the call had quote characters in it (the quotes were stripped).
501 514
502 515 2005-01-31 Fernando Perez <fperez@colorado.edu>
503 516
504 517 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
505 518 Itpl.itpl() to make the code more robust against psyco
506 519 optimizations.
507 520
508 521 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
509 522 of causing an exception. Quicker, cleaner.
510 523
511 524 2005-01-28 Fernando Perez <fperez@colorado.edu>
512 525
513 526 * scripts/ipython_win_post_install.py (install): hardcode
514 527 sys.prefix+'python.exe' as the executable path. It turns out that
515 528 during the post-installation run, sys.executable resolves to the
516 529 name of the binary installer! I should report this as a distutils
517 530 bug, I think. I updated the .10 release with this tiny fix, to
518 531 avoid annoying the lists further.
519 532
520 533 2005-01-27 *** Released version 0.6.10
521 534
522 535 2005-01-27 Fernando Perez <fperez@colorado.edu>
523 536
524 537 * IPython/numutils.py (norm): Added 'inf' as optional name for
525 538 L-infinity norm, included references to mathworld.com for vector
526 539 norm definitions.
527 540 (amin/amax): added amin/amax for array min/max. Similar to what
528 541 pylab ships with after the recent reorganization of names.
529 542 (spike/spike_odd): removed deprecated spike/spike_odd functions.
530 543
531 544 * ipython.el: committed Alex's recent fixes and improvements.
532 545 Tested with python-mode from CVS, and it looks excellent. Since
533 546 python-mode hasn't released anything in a while, I'm temporarily
534 547 putting a copy of today's CVS (v 4.70) of python-mode in:
535 548 http://ipython.scipy.org/tmp/python-mode.el
536 549
537 550 * scripts/ipython_win_post_install.py (install): Win32 fix to use
538 551 sys.executable for the executable name, instead of assuming it's
539 552 called 'python.exe' (the post-installer would have produced broken
540 553 setups on systems with a differently named python binary).
541 554
542 555 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
543 556 references to os.linesep, to make the code more
544 557 platform-independent. This is also part of the win32 coloring
545 558 fixes.
546 559
547 560 * IPython/genutils.py (page_dumb): Remove attempts to chop long
548 561 lines, which actually cause coloring bugs because the length of
549 562 the line is very difficult to correctly compute with embedded
550 563 escapes. This was the source of all the coloring problems under
551 564 Win32. I think that _finally_, Win32 users have a properly
552 565 working ipython in all respects. This would never have happened
553 566 if not for Gary Bishop and Viktor Ransmayr's great help and work.
554 567
555 568 2005-01-26 *** Released version 0.6.9
556 569
557 570 2005-01-25 Fernando Perez <fperez@colorado.edu>
558 571
559 572 * setup.py: finally, we have a true Windows installer, thanks to
560 573 the excellent work of Viktor Ransmayr
561 574 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
562 575 Windows users. The setup routine is quite a bit cleaner thanks to
563 576 this, and the post-install script uses the proper functions to
564 577 allow a clean de-installation using the standard Windows Control
565 578 Panel.
566 579
567 580 * IPython/genutils.py (get_home_dir): changed to use the $HOME
568 581 environment variable under all OSes (including win32) if
569 582 available. This will give consistency to win32 users who have set
570 583 this variable for any reason. If os.environ['HOME'] fails, the
571 584 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
572 585
573 586 2005-01-24 Fernando Perez <fperez@colorado.edu>
574 587
575 588 * IPython/numutils.py (empty_like): add empty_like(), similar to
576 589 zeros_like() but taking advantage of the new empty() Numeric routine.
577 590
578 591 2005-01-23 *** Released version 0.6.8
579 592
580 593 2005-01-22 Fernando Perez <fperez@colorado.edu>
581 594
582 595 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
583 596 automatic show() calls. After discussing things with JDH, it
584 597 turns out there are too many corner cases where this can go wrong.
585 598 It's best not to try to be 'too smart', and simply have ipython
586 599 reproduce as much as possible the default behavior of a normal
587 600 python shell.
588 601
589 602 * IPython/iplib.py (InteractiveShell.__init__): Modified the
590 603 line-splitting regexp and _prefilter() to avoid calling getattr()
591 604 on assignments. This closes
592 605 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
593 606 readline uses getattr(), so a simple <TAB> keypress is still
594 607 enough to trigger getattr() calls on an object.
595 608
596 609 2005-01-21 Fernando Perez <fperez@colorado.edu>
597 610
598 611 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
599 612 docstring under pylab so it doesn't mask the original.
600 613
601 614 2005-01-21 *** Released version 0.6.7
602 615
603 616 2005-01-21 Fernando Perez <fperez@colorado.edu>
604 617
605 618 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
606 619 signal handling for win32 users in multithreaded mode.
607 620
608 621 2005-01-17 Fernando Perez <fperez@colorado.edu>
609 622
610 623 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
611 624 instances with no __init__. After a crash report by Norbert Nemec
612 625 <Norbert-AT-nemec-online.de>.
613 626
614 627 2005-01-14 Fernando Perez <fperez@colorado.edu>
615 628
616 629 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
617 630 names for verbose exceptions, when multiple dotted names and the
618 631 'parent' object were present on the same line.
619 632
620 633 2005-01-11 Fernando Perez <fperez@colorado.edu>
621 634
622 635 * IPython/genutils.py (flag_calls): new utility to trap and flag
623 636 calls in functions. I need it to clean up matplotlib support.
624 637 Also removed some deprecated code in genutils.
625 638
626 639 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
627 640 that matplotlib scripts called with %run, which don't call show()
628 641 themselves, still have their plotting windows open.
629 642
630 643 2005-01-05 Fernando Perez <fperez@colorado.edu>
631 644
632 645 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
633 646 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
634 647
635 648 2004-12-19 Fernando Perez <fperez@colorado.edu>
636 649
637 650 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
638 651 parent_runcode, which was an eyesore. The same result can be
639 652 obtained with Python's regular superclass mechanisms.
640 653
641 654 2004-12-17 Fernando Perez <fperez@colorado.edu>
642 655
643 656 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
644 657 reported by Prabhu.
645 658 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
646 659 sys.stderr) instead of explicitly calling sys.stderr. This helps
647 660 maintain our I/O abstractions clean, for future GUI embeddings.
648 661
649 662 * IPython/genutils.py (info): added new utility for sys.stderr
650 663 unified info message handling (thin wrapper around warn()).
651 664
652 665 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
653 666 composite (dotted) names on verbose exceptions.
654 667 (VerboseTB.nullrepr): harden against another kind of errors which
655 668 Python's inspect module can trigger, and which were crashing
656 669 IPython. Thanks to a report by Marco Lombardi
657 670 <mlombard-AT-ma010192.hq.eso.org>.
658 671
659 672 2004-12-13 *** Released version 0.6.6
660 673
661 674 2004-12-12 Fernando Perez <fperez@colorado.edu>
662 675
663 676 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
664 677 generated by pygtk upon initialization if it was built without
665 678 threads (for matplotlib users). After a crash reported by
666 679 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
667 680
668 681 * IPython/ipmaker.py (make_IPython): fix small bug in the
669 682 import_some parameter for multiple imports.
670 683
671 684 * IPython/iplib.py (ipmagic): simplified the interface of
672 685 ipmagic() to take a single string argument, just as it would be
673 686 typed at the IPython cmd line.
674 687 (ipalias): Added new ipalias() with an interface identical to
675 688 ipmagic(). This completes exposing a pure python interface to the
676 689 alias and magic system, which can be used in loops or more complex
677 690 code where IPython's automatic line mangling is not active.
678 691
679 692 * IPython/genutils.py (timing): changed interface of timing to
680 693 simply run code once, which is the most common case. timings()
681 694 remains unchanged, for the cases where you want multiple runs.
682 695
683 696 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
684 697 bug where Python2.2 crashes with exec'ing code which does not end
685 698 in a single newline. Python 2.3 is OK, so I hadn't noticed this
686 699 before.
687 700
688 701 2004-12-10 Fernando Perez <fperez@colorado.edu>
689 702
690 703 * IPython/Magic.py (Magic.magic_prun): changed name of option from
691 704 -t to -T, to accomodate the new -t flag in %run (the %run and
692 705 %prun options are kind of intermixed, and it's not easy to change
693 706 this with the limitations of python's getopt).
694 707
695 708 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
696 709 the execution of scripts. It's not as fine-tuned as timeit.py,
697 710 but it works from inside ipython (and under 2.2, which lacks
698 711 timeit.py). Optionally a number of runs > 1 can be given for
699 712 timing very short-running code.
700 713
701 714 * IPython/genutils.py (uniq_stable): new routine which returns a
702 715 list of unique elements in any iterable, but in stable order of
703 716 appearance. I needed this for the ultraTB fixes, and it's a handy
704 717 utility.
705 718
706 719 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
707 720 dotted names in Verbose exceptions. This had been broken since
708 721 the very start, now x.y will properly be printed in a Verbose
709 722 traceback, instead of x being shown and y appearing always as an
710 723 'undefined global'. Getting this to work was a bit tricky,
711 724 because by default python tokenizers are stateless. Saved by
712 725 python's ability to easily add a bit of state to an arbitrary
713 726 function (without needing to build a full-blown callable object).
714 727
715 728 Also big cleanup of this code, which had horrendous runtime
716 729 lookups of zillions of attributes for colorization. Moved all
717 730 this code into a few templates, which make it cleaner and quicker.
718 731
719 732 Printout quality was also improved for Verbose exceptions: one
720 733 variable per line, and memory addresses are printed (this can be
721 734 quite handy in nasty debugging situations, which is what Verbose
722 735 is for).
723 736
724 737 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
725 738 the command line as scripts to be loaded by embedded instances.
726 739 Doing so has the potential for an infinite recursion if there are
727 740 exceptions thrown in the process. This fixes a strange crash
728 741 reported by Philippe MULLER <muller-AT-irit.fr>.
729 742
730 743 2004-12-09 Fernando Perez <fperez@colorado.edu>
731 744
732 745 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
733 746 to reflect new names in matplotlib, which now expose the
734 747 matlab-compatible interface via a pylab module instead of the
735 748 'matlab' name. The new code is backwards compatible, so users of
736 749 all matplotlib versions are OK. Patch by J. Hunter.
737 750
738 751 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
739 752 of __init__ docstrings for instances (class docstrings are already
740 753 automatically printed). Instances with customized docstrings
741 754 (indep. of the class) are also recognized and all 3 separate
742 755 docstrings are printed (instance, class, constructor). After some
743 756 comments/suggestions by J. Hunter.
744 757
745 758 2004-12-05 Fernando Perez <fperez@colorado.edu>
746 759
747 760 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
748 761 warnings when tab-completion fails and triggers an exception.
749 762
750 763 2004-12-03 Fernando Perez <fperez@colorado.edu>
751 764
752 765 * IPython/Magic.py (magic_prun): Fix bug where an exception would
753 766 be triggered when using 'run -p'. An incorrect option flag was
754 767 being set ('d' instead of 'D').
755 768 (manpage): fix missing escaped \- sign.
756 769
757 770 2004-11-30 *** Released version 0.6.5
758 771
759 772 2004-11-30 Fernando Perez <fperez@colorado.edu>
760 773
761 774 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
762 775 setting with -d option.
763 776
764 777 * setup.py (docfiles): Fix problem where the doc glob I was using
765 778 was COMPLETELY BROKEN. It was giving the right files by pure
766 779 accident, but failed once I tried to include ipython.el. Note:
767 780 glob() does NOT allow you to do exclusion on multiple endings!
768 781
769 782 2004-11-29 Fernando Perez <fperez@colorado.edu>
770 783
771 784 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
772 785 the manpage as the source. Better formatting & consistency.
773 786
774 787 * IPython/Magic.py (magic_run): Added new -d option, to run
775 788 scripts under the control of the python pdb debugger. Note that
776 789 this required changing the %prun option -d to -D, to avoid a clash
777 790 (since %run must pass options to %prun, and getopt is too dumb to
778 791 handle options with string values with embedded spaces). Thanks
779 792 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
780 793 (magic_who_ls): added type matching to %who and %whos, so that one
781 794 can filter their output to only include variables of certain
782 795 types. Another suggestion by Matthew.
783 796 (magic_whos): Added memory summaries in kb and Mb for arrays.
784 797 (magic_who): Improve formatting (break lines every 9 vars).
785 798
786 799 2004-11-28 Fernando Perez <fperez@colorado.edu>
787 800
788 801 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
789 802 cache when empty lines were present.
790 803
791 804 2004-11-24 Fernando Perez <fperez@colorado.edu>
792 805
793 806 * IPython/usage.py (__doc__): document the re-activated threading
794 807 options for WX and GTK.
795 808
796 809 2004-11-23 Fernando Perez <fperez@colorado.edu>
797 810
798 811 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
799 812 the -wthread and -gthread options, along with a new -tk one to try
800 813 and coordinate Tk threading with wx/gtk. The tk support is very
801 814 platform dependent, since it seems to require Tcl and Tk to be
802 815 built with threads (Fedora1/2 appears NOT to have it, but in
803 816 Prabhu's Debian boxes it works OK). But even with some Tk
804 817 limitations, this is a great improvement.
805 818
806 819 * IPython/Prompts.py (prompt_specials_color): Added \t for time
807 820 info in user prompts. Patch by Prabhu.
808 821
809 822 2004-11-18 Fernando Perez <fperez@colorado.edu>
810 823
811 824 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
812 825 EOFErrors and bail, to avoid infinite loops if a non-terminating
813 826 file is fed into ipython. Patch submitted in issue 19 by user,
814 827 many thanks.
815 828
816 829 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
817 830 autoquote/parens in continuation prompts, which can cause lots of
818 831 problems. Closes roundup issue 20.
819 832
820 833 2004-11-17 Fernando Perez <fperez@colorado.edu>
821 834
822 835 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
823 836 reported as debian bug #280505. I'm not sure my local changelog
824 837 entry has the proper debian format (Jack?).
825 838
826 839 2004-11-08 *** Released version 0.6.4
827 840
828 841 2004-11-08 Fernando Perez <fperez@colorado.edu>
829 842
830 843 * IPython/iplib.py (init_readline): Fix exit message for Windows
831 844 when readline is active. Thanks to a report by Eric Jones
832 845 <eric-AT-enthought.com>.
833 846
834 847 2004-11-07 Fernando Perez <fperez@colorado.edu>
835 848
836 849 * IPython/genutils.py (page): Add a trap for OSError exceptions,
837 850 sometimes seen by win2k/cygwin users.
838 851
839 852 2004-11-06 Fernando Perez <fperez@colorado.edu>
840 853
841 854 * IPython/iplib.py (interact): Change the handling of %Exit from
842 855 trying to propagate a SystemExit to an internal ipython flag.
843 856 This is less elegant than using Python's exception mechanism, but
844 857 I can't get that to work reliably with threads, so under -pylab
845 858 %Exit was hanging IPython. Cross-thread exception handling is
846 859 really a bitch. Thaks to a bug report by Stephen Walton
847 860 <stephen.walton-AT-csun.edu>.
848 861
849 862 2004-11-04 Fernando Perez <fperez@colorado.edu>
850 863
851 864 * IPython/iplib.py (raw_input_original): store a pointer to the
852 865 true raw_input to harden against code which can modify it
853 866 (wx.py.PyShell does this and would otherwise crash ipython).
854 867 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
855 868
856 869 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
857 870 Ctrl-C problem, which does not mess up the input line.
858 871
859 872 2004-11-03 Fernando Perez <fperez@colorado.edu>
860 873
861 874 * IPython/Release.py: Changed licensing to BSD, in all files.
862 875 (name): lowercase name for tarball/RPM release.
863 876
864 877 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
865 878 use throughout ipython.
866 879
867 880 * IPython/Magic.py (Magic._ofind): Switch to using the new
868 881 OInspect.getdoc() function.
869 882
870 883 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
871 884 of the line currently being canceled via Ctrl-C. It's extremely
872 885 ugly, but I don't know how to do it better (the problem is one of
873 886 handling cross-thread exceptions).
874 887
875 888 2004-10-28 Fernando Perez <fperez@colorado.edu>
876 889
877 890 * IPython/Shell.py (signal_handler): add signal handlers to trap
878 891 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
879 892 report by Francesc Alted.
880 893
881 894 2004-10-21 Fernando Perez <fperez@colorado.edu>
882 895
883 896 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
884 897 to % for pysh syntax extensions.
885 898
886 899 2004-10-09 Fernando Perez <fperez@colorado.edu>
887 900
888 901 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
889 902 arrays to print a more useful summary, without calling str(arr).
890 903 This avoids the problem of extremely lengthy computations which
891 904 occur if arr is large, and appear to the user as a system lockup
892 905 with 100% cpu activity. After a suggestion by Kristian Sandberg
893 906 <Kristian.Sandberg@colorado.edu>.
894 907 (Magic.__init__): fix bug in global magic escapes not being
895 908 correctly set.
896 909
897 910 2004-10-08 Fernando Perez <fperez@colorado.edu>
898 911
899 912 * IPython/Magic.py (__license__): change to absolute imports of
900 913 ipython's own internal packages, to start adapting to the absolute
901 914 import requirement of PEP-328.
902 915
903 916 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
904 917 files, and standardize author/license marks through the Release
905 918 module instead of having per/file stuff (except for files with
906 919 particular licenses, like the MIT/PSF-licensed codes).
907 920
908 921 * IPython/Debugger.py: remove dead code for python 2.1
909 922
910 923 2004-10-04 Fernando Perez <fperez@colorado.edu>
911 924
912 925 * IPython/iplib.py (ipmagic): New function for accessing magics
913 926 via a normal python function call.
914 927
915 928 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
916 929 from '@' to '%', to accomodate the new @decorator syntax of python
917 930 2.4.
918 931
919 932 2004-09-29 Fernando Perez <fperez@colorado.edu>
920 933
921 934 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
922 935 matplotlib.use to prevent running scripts which try to switch
923 936 interactive backends from within ipython. This will just crash
924 937 the python interpreter, so we can't allow it (but a detailed error
925 938 is given to the user).
926 939
927 940 2004-09-28 Fernando Perez <fperez@colorado.edu>
928 941
929 942 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
930 943 matplotlib-related fixes so that using @run with non-matplotlib
931 944 scripts doesn't pop up spurious plot windows. This requires
932 945 matplotlib >= 0.63, where I had to make some changes as well.
933 946
934 947 * IPython/ipmaker.py (make_IPython): update version requirement to
935 948 python 2.2.
936 949
937 950 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
938 951 banner arg for embedded customization.
939 952
940 953 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
941 954 explicit uses of __IP as the IPython's instance name. Now things
942 955 are properly handled via the shell.name value. The actual code
943 956 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
944 957 is much better than before. I'll clean things completely when the
945 958 magic stuff gets a real overhaul.
946 959
947 960 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
948 961 minor changes to debian dir.
949 962
950 963 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
951 964 pointer to the shell itself in the interactive namespace even when
952 965 a user-supplied dict is provided. This is needed for embedding
953 966 purposes (found by tests with Michel Sanner).
954 967
955 968 2004-09-27 Fernando Perez <fperez@colorado.edu>
956 969
957 970 * IPython/UserConfig/ipythonrc: remove []{} from
958 971 readline_remove_delims, so that things like [modname.<TAB> do
959 972 proper completion. This disables [].TAB, but that's a less common
960 973 case than module names in list comprehensions, for example.
961 974 Thanks to a report by Andrea Riciputi.
962 975
963 976 2004-09-09 Fernando Perez <fperez@colorado.edu>
964 977
965 978 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
966 979 blocking problems in win32 and osx. Fix by John.
967 980
968 981 2004-09-08 Fernando Perez <fperez@colorado.edu>
969 982
970 983 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
971 984 for Win32 and OSX. Fix by John Hunter.
972 985
973 986 2004-08-30 *** Released version 0.6.3
974 987
975 988 2004-08-30 Fernando Perez <fperez@colorado.edu>
976 989
977 990 * setup.py (isfile): Add manpages to list of dependent files to be
978 991 updated.
979 992
980 993 2004-08-27 Fernando Perez <fperez@colorado.edu>
981 994
982 995 * IPython/Shell.py (start): I've disabled -wthread and -gthread
983 996 for now. They don't really work with standalone WX/GTK code
984 997 (though matplotlib IS working fine with both of those backends).
985 998 This will neeed much more testing. I disabled most things with
986 999 comments, so turning it back on later should be pretty easy.
987 1000
988 1001 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
989 1002 autocalling of expressions like r'foo', by modifying the line
990 1003 split regexp. Closes
991 1004 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
992 1005 Riley <ipythonbugs-AT-sabi.net>.
993 1006 (InteractiveShell.mainloop): honor --nobanner with banner
994 1007 extensions.
995 1008
996 1009 * IPython/Shell.py: Significant refactoring of all classes, so
997 1010 that we can really support ALL matplotlib backends and threading
998 1011 models (John spotted a bug with Tk which required this). Now we
999 1012 should support single-threaded, WX-threads and GTK-threads, both
1000 1013 for generic code and for matplotlib.
1001 1014
1002 1015 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1003 1016 -pylab, to simplify things for users. Will also remove the pylab
1004 1017 profile, since now all of matplotlib configuration is directly
1005 1018 handled here. This also reduces startup time.
1006 1019
1007 1020 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1008 1021 shell wasn't being correctly called. Also in IPShellWX.
1009 1022
1010 1023 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1011 1024 fine-tune banner.
1012 1025
1013 1026 * IPython/numutils.py (spike): Deprecate these spike functions,
1014 1027 delete (long deprecated) gnuplot_exec handler.
1015 1028
1016 1029 2004-08-26 Fernando Perez <fperez@colorado.edu>
1017 1030
1018 1031 * ipython.1: Update for threading options, plus some others which
1019 1032 were missing.
1020 1033
1021 1034 * IPython/ipmaker.py (__call__): Added -wthread option for
1022 1035 wxpython thread handling. Make sure threading options are only
1023 1036 valid at the command line.
1024 1037
1025 1038 * scripts/ipython: moved shell selection into a factory function
1026 1039 in Shell.py, to keep the starter script to a minimum.
1027 1040
1028 1041 2004-08-25 Fernando Perez <fperez@colorado.edu>
1029 1042
1030 1043 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1031 1044 John. Along with some recent changes he made to matplotlib, the
1032 1045 next versions of both systems should work very well together.
1033 1046
1034 1047 2004-08-24 Fernando Perez <fperez@colorado.edu>
1035 1048
1036 1049 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1037 1050 tried to switch the profiling to using hotshot, but I'm getting
1038 1051 strange errors from prof.runctx() there. I may be misreading the
1039 1052 docs, but it looks weird. For now the profiling code will
1040 1053 continue to use the standard profiler.
1041 1054
1042 1055 2004-08-23 Fernando Perez <fperez@colorado.edu>
1043 1056
1044 1057 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1045 1058 threaded shell, by John Hunter. It's not quite ready yet, but
1046 1059 close.
1047 1060
1048 1061 2004-08-22 Fernando Perez <fperez@colorado.edu>
1049 1062
1050 1063 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1051 1064 in Magic and ultraTB.
1052 1065
1053 1066 * ipython.1: document threading options in manpage.
1054 1067
1055 1068 * scripts/ipython: Changed name of -thread option to -gthread,
1056 1069 since this is GTK specific. I want to leave the door open for a
1057 1070 -wthread option for WX, which will most likely be necessary. This
1058 1071 change affects usage and ipmaker as well.
1059 1072
1060 1073 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1061 1074 handle the matplotlib shell issues. Code by John Hunter
1062 1075 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1063 1076 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1064 1077 broken (and disabled for end users) for now, but it puts the
1065 1078 infrastructure in place.
1066 1079
1067 1080 2004-08-21 Fernando Perez <fperez@colorado.edu>
1068 1081
1069 1082 * ipythonrc-pylab: Add matplotlib support.
1070 1083
1071 1084 * matplotlib_config.py: new files for matplotlib support, part of
1072 1085 the pylab profile.
1073 1086
1074 1087 * IPython/usage.py (__doc__): documented the threading options.
1075 1088
1076 1089 2004-08-20 Fernando Perez <fperez@colorado.edu>
1077 1090
1078 1091 * ipython: Modified the main calling routine to handle the -thread
1079 1092 and -mpthread options. This needs to be done as a top-level hack,
1080 1093 because it determines which class to instantiate for IPython
1081 1094 itself.
1082 1095
1083 1096 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1084 1097 classes to support multithreaded GTK operation without blocking,
1085 1098 and matplotlib with all backends. This is a lot of still very
1086 1099 experimental code, and threads are tricky. So it may still have a
1087 1100 few rough edges... This code owes a lot to
1088 1101 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1089 1102 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1090 1103 to John Hunter for all the matplotlib work.
1091 1104
1092 1105 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1093 1106 options for gtk thread and matplotlib support.
1094 1107
1095 1108 2004-08-16 Fernando Perez <fperez@colorado.edu>
1096 1109
1097 1110 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1098 1111 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1099 1112 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1100 1113
1101 1114 2004-08-11 Fernando Perez <fperez@colorado.edu>
1102 1115
1103 1116 * setup.py (isfile): Fix build so documentation gets updated for
1104 1117 rpms (it was only done for .tgz builds).
1105 1118
1106 1119 2004-08-10 Fernando Perez <fperez@colorado.edu>
1107 1120
1108 1121 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1109 1122
1110 1123 * iplib.py : Silence syntax error exceptions in tab-completion.
1111 1124
1112 1125 2004-08-05 Fernando Perez <fperez@colorado.edu>
1113 1126
1114 1127 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1115 1128 'color off' mark for continuation prompts. This was causing long
1116 1129 continuation lines to mis-wrap.
1117 1130
1118 1131 2004-08-01 Fernando Perez <fperez@colorado.edu>
1119 1132
1120 1133 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1121 1134 for building ipython to be a parameter. All this is necessary
1122 1135 right now to have a multithreaded version, but this insane
1123 1136 non-design will be cleaned up soon. For now, it's a hack that
1124 1137 works.
1125 1138
1126 1139 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1127 1140 args in various places. No bugs so far, but it's a dangerous
1128 1141 practice.
1129 1142
1130 1143 2004-07-31 Fernando Perez <fperez@colorado.edu>
1131 1144
1132 1145 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1133 1146 fix completion of files with dots in their names under most
1134 1147 profiles (pysh was OK because the completion order is different).
1135 1148
1136 1149 2004-07-27 Fernando Perez <fperez@colorado.edu>
1137 1150
1138 1151 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1139 1152 keywords manually, b/c the one in keyword.py was removed in python
1140 1153 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1141 1154 This is NOT a bug under python 2.3 and earlier.
1142 1155
1143 1156 2004-07-26 Fernando Perez <fperez@colorado.edu>
1144 1157
1145 1158 * IPython/ultraTB.py (VerboseTB.text): Add another
1146 1159 linecache.checkcache() call to try to prevent inspect.py from
1147 1160 crashing under python 2.3. I think this fixes
1148 1161 http://www.scipy.net/roundup/ipython/issue17.
1149 1162
1150 1163 2004-07-26 *** Released version 0.6.2
1151 1164
1152 1165 2004-07-26 Fernando Perez <fperez@colorado.edu>
1153 1166
1154 1167 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1155 1168 fail for any number.
1156 1169 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1157 1170 empty bookmarks.
1158 1171
1159 1172 2004-07-26 *** Released version 0.6.1
1160 1173
1161 1174 2004-07-26 Fernando Perez <fperez@colorado.edu>
1162 1175
1163 1176 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1164 1177
1165 1178 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1166 1179 escaping '()[]{}' in filenames.
1167 1180
1168 1181 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1169 1182 Python 2.2 users who lack a proper shlex.split.
1170 1183
1171 1184 2004-07-19 Fernando Perez <fperez@colorado.edu>
1172 1185
1173 1186 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1174 1187 for reading readline's init file. I follow the normal chain:
1175 1188 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1176 1189 report by Mike Heeter. This closes
1177 1190 http://www.scipy.net/roundup/ipython/issue16.
1178 1191
1179 1192 2004-07-18 Fernando Perez <fperez@colorado.edu>
1180 1193
1181 1194 * IPython/iplib.py (__init__): Add better handling of '\' under
1182 1195 Win32 for filenames. After a patch by Ville.
1183 1196
1184 1197 2004-07-17 Fernando Perez <fperez@colorado.edu>
1185 1198
1186 1199 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1187 1200 autocalling would be triggered for 'foo is bar' if foo is
1188 1201 callable. I also cleaned up the autocall detection code to use a
1189 1202 regexp, which is faster. Bug reported by Alexander Schmolck.
1190 1203
1191 1204 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1192 1205 '?' in them would confuse the help system. Reported by Alex
1193 1206 Schmolck.
1194 1207
1195 1208 2004-07-16 Fernando Perez <fperez@colorado.edu>
1196 1209
1197 1210 * IPython/GnuplotInteractive.py (__all__): added plot2.
1198 1211
1199 1212 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1200 1213 plotting dictionaries, lists or tuples of 1d arrays.
1201 1214
1202 1215 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1203 1216 optimizations.
1204 1217
1205 1218 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1206 1219 the information which was there from Janko's original IPP code:
1207 1220
1208 1221 03.05.99 20:53 porto.ifm.uni-kiel.de
1209 1222 --Started changelog.
1210 1223 --make clear do what it say it does
1211 1224 --added pretty output of lines from inputcache
1212 1225 --Made Logger a mixin class, simplifies handling of switches
1213 1226 --Added own completer class. .string<TAB> expands to last history
1214 1227 line which starts with string. The new expansion is also present
1215 1228 with Ctrl-r from the readline library. But this shows, who this
1216 1229 can be done for other cases.
1217 1230 --Added convention that all shell functions should accept a
1218 1231 parameter_string This opens the door for different behaviour for
1219 1232 each function. @cd is a good example of this.
1220 1233
1221 1234 04.05.99 12:12 porto.ifm.uni-kiel.de
1222 1235 --added logfile rotation
1223 1236 --added new mainloop method which freezes first the namespace
1224 1237
1225 1238 07.05.99 21:24 porto.ifm.uni-kiel.de
1226 1239 --added the docreader classes. Now there is a help system.
1227 1240 -This is only a first try. Currently it's not easy to put new
1228 1241 stuff in the indices. But this is the way to go. Info would be
1229 1242 better, but HTML is every where and not everybody has an info
1230 1243 system installed and it's not so easy to change html-docs to info.
1231 1244 --added global logfile option
1232 1245 --there is now a hook for object inspection method pinfo needs to
1233 1246 be provided for this. Can be reached by two '??'.
1234 1247
1235 1248 08.05.99 20:51 porto.ifm.uni-kiel.de
1236 1249 --added a README
1237 1250 --bug in rc file. Something has changed so functions in the rc
1238 1251 file need to reference the shell and not self. Not clear if it's a
1239 1252 bug or feature.
1240 1253 --changed rc file for new behavior
1241 1254
1242 1255 2004-07-15 Fernando Perez <fperez@colorado.edu>
1243 1256
1244 1257 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1245 1258 cache was falling out of sync in bizarre manners when multi-line
1246 1259 input was present. Minor optimizations and cleanup.
1247 1260
1248 1261 (Logger): Remove old Changelog info for cleanup. This is the
1249 1262 information which was there from Janko's original code:
1250 1263
1251 1264 Changes to Logger: - made the default log filename a parameter
1252 1265
1253 1266 - put a check for lines beginning with !@? in log(). Needed
1254 1267 (even if the handlers properly log their lines) for mid-session
1255 1268 logging activation to work properly. Without this, lines logged
1256 1269 in mid session, which get read from the cache, would end up
1257 1270 'bare' (with !@? in the open) in the log. Now they are caught
1258 1271 and prepended with a #.
1259 1272
1260 1273 * IPython/iplib.py (InteractiveShell.init_readline): added check
1261 1274 in case MagicCompleter fails to be defined, so we don't crash.
1262 1275
1263 1276 2004-07-13 Fernando Perez <fperez@colorado.edu>
1264 1277
1265 1278 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1266 1279 of EPS if the requested filename ends in '.eps'.
1267 1280
1268 1281 2004-07-04 Fernando Perez <fperez@colorado.edu>
1269 1282
1270 1283 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1271 1284 escaping of quotes when calling the shell.
1272 1285
1273 1286 2004-07-02 Fernando Perez <fperez@colorado.edu>
1274 1287
1275 1288 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1276 1289 gettext not working because we were clobbering '_'. Fixes
1277 1290 http://www.scipy.net/roundup/ipython/issue6.
1278 1291
1279 1292 2004-07-01 Fernando Perez <fperez@colorado.edu>
1280 1293
1281 1294 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1282 1295 into @cd. Patch by Ville.
1283 1296
1284 1297 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1285 1298 new function to store things after ipmaker runs. Patch by Ville.
1286 1299 Eventually this will go away once ipmaker is removed and the class
1287 1300 gets cleaned up, but for now it's ok. Key functionality here is
1288 1301 the addition of the persistent storage mechanism, a dict for
1289 1302 keeping data across sessions (for now just bookmarks, but more can
1290 1303 be implemented later).
1291 1304
1292 1305 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1293 1306 persistent across sections. Patch by Ville, I modified it
1294 1307 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1295 1308 added a '-l' option to list all bookmarks.
1296 1309
1297 1310 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1298 1311 center for cleanup. Registered with atexit.register(). I moved
1299 1312 here the old exit_cleanup(). After a patch by Ville.
1300 1313
1301 1314 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1302 1315 characters in the hacked shlex_split for python 2.2.
1303 1316
1304 1317 * IPython/iplib.py (file_matches): more fixes to filenames with
1305 1318 whitespace in them. It's not perfect, but limitations in python's
1306 1319 readline make it impossible to go further.
1307 1320
1308 1321 2004-06-29 Fernando Perez <fperez@colorado.edu>
1309 1322
1310 1323 * IPython/iplib.py (file_matches): escape whitespace correctly in
1311 1324 filename completions. Bug reported by Ville.
1312 1325
1313 1326 2004-06-28 Fernando Perez <fperez@colorado.edu>
1314 1327
1315 1328 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1316 1329 the history file will be called 'history-PROFNAME' (or just
1317 1330 'history' if no profile is loaded). I was getting annoyed at
1318 1331 getting my Numerical work history clobbered by pysh sessions.
1319 1332
1320 1333 * IPython/iplib.py (InteractiveShell.__init__): Internal
1321 1334 getoutputerror() function so that we can honor the system_verbose
1322 1335 flag for _all_ system calls. I also added escaping of #
1323 1336 characters here to avoid confusing Itpl.
1324 1337
1325 1338 * IPython/Magic.py (shlex_split): removed call to shell in
1326 1339 parse_options and replaced it with shlex.split(). The annoying
1327 1340 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1328 1341 to backport it from 2.3, with several frail hacks (the shlex
1329 1342 module is rather limited in 2.2). Thanks to a suggestion by Ville
1330 1343 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1331 1344 problem.
1332 1345
1333 1346 (Magic.magic_system_verbose): new toggle to print the actual
1334 1347 system calls made by ipython. Mainly for debugging purposes.
1335 1348
1336 1349 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1337 1350 doesn't support persistence. Reported (and fix suggested) by
1338 1351 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1339 1352
1340 1353 2004-06-26 Fernando Perez <fperez@colorado.edu>
1341 1354
1342 1355 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1343 1356 continue prompts.
1344 1357
1345 1358 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1346 1359 function (basically a big docstring) and a few more things here to
1347 1360 speedup startup. pysh.py is now very lightweight. We want because
1348 1361 it gets execfile'd, while InterpreterExec gets imported, so
1349 1362 byte-compilation saves time.
1350 1363
1351 1364 2004-06-25 Fernando Perez <fperez@colorado.edu>
1352 1365
1353 1366 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1354 1367 -NUM', which was recently broken.
1355 1368
1356 1369 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1357 1370 in multi-line input (but not !!, which doesn't make sense there).
1358 1371
1359 1372 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1360 1373 It's just too useful, and people can turn it off in the less
1361 1374 common cases where it's a problem.
1362 1375
1363 1376 2004-06-24 Fernando Perez <fperez@colorado.edu>
1364 1377
1365 1378 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1366 1379 special syntaxes (like alias calling) is now allied in multi-line
1367 1380 input. This is still _very_ experimental, but it's necessary for
1368 1381 efficient shell usage combining python looping syntax with system
1369 1382 calls. For now it's restricted to aliases, I don't think it
1370 1383 really even makes sense to have this for magics.
1371 1384
1372 1385 2004-06-23 Fernando Perez <fperez@colorado.edu>
1373 1386
1374 1387 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1375 1388 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1376 1389
1377 1390 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1378 1391 extensions under Windows (after code sent by Gary Bishop). The
1379 1392 extensions considered 'executable' are stored in IPython's rc
1380 1393 structure as win_exec_ext.
1381 1394
1382 1395 * IPython/genutils.py (shell): new function, like system() but
1383 1396 without return value. Very useful for interactive shell work.
1384 1397
1385 1398 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1386 1399 delete aliases.
1387 1400
1388 1401 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1389 1402 sure that the alias table doesn't contain python keywords.
1390 1403
1391 1404 2004-06-21 Fernando Perez <fperez@colorado.edu>
1392 1405
1393 1406 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1394 1407 non-existent items are found in $PATH. Reported by Thorsten.
1395 1408
1396 1409 2004-06-20 Fernando Perez <fperez@colorado.edu>
1397 1410
1398 1411 * IPython/iplib.py (complete): modified the completer so that the
1399 1412 order of priorities can be easily changed at runtime.
1400 1413
1401 1414 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1402 1415 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1403 1416
1404 1417 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1405 1418 expand Python variables prepended with $ in all system calls. The
1406 1419 same was done to InteractiveShell.handle_shell_escape. Now all
1407 1420 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1408 1421 expansion of python variables and expressions according to the
1409 1422 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1410 1423
1411 1424 Though PEP-215 has been rejected, a similar (but simpler) one
1412 1425 seems like it will go into Python 2.4, PEP-292 -
1413 1426 http://www.python.org/peps/pep-0292.html.
1414 1427
1415 1428 I'll keep the full syntax of PEP-215, since IPython has since the
1416 1429 start used Ka-Ping Yee's reference implementation discussed there
1417 1430 (Itpl), and I actually like the powerful semantics it offers.
1418 1431
1419 1432 In order to access normal shell variables, the $ has to be escaped
1420 1433 via an extra $. For example:
1421 1434
1422 1435 In [7]: PATH='a python variable'
1423 1436
1424 1437 In [8]: !echo $PATH
1425 1438 a python variable
1426 1439
1427 1440 In [9]: !echo $$PATH
1428 1441 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1429 1442
1430 1443 (Magic.parse_options): escape $ so the shell doesn't evaluate
1431 1444 things prematurely.
1432 1445
1433 1446 * IPython/iplib.py (InteractiveShell.call_alias): added the
1434 1447 ability for aliases to expand python variables via $.
1435 1448
1436 1449 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1437 1450 system, now there's a @rehash/@rehashx pair of magics. These work
1438 1451 like the csh rehash command, and can be invoked at any time. They
1439 1452 build a table of aliases to everything in the user's $PATH
1440 1453 (@rehash uses everything, @rehashx is slower but only adds
1441 1454 executable files). With this, the pysh.py-based shell profile can
1442 1455 now simply call rehash upon startup, and full access to all
1443 1456 programs in the user's path is obtained.
1444 1457
1445 1458 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1446 1459 functionality is now fully in place. I removed the old dynamic
1447 1460 code generation based approach, in favor of a much lighter one
1448 1461 based on a simple dict. The advantage is that this allows me to
1449 1462 now have thousands of aliases with negligible cost (unthinkable
1450 1463 with the old system).
1451 1464
1452 1465 2004-06-19 Fernando Perez <fperez@colorado.edu>
1453 1466
1454 1467 * IPython/iplib.py (__init__): extended MagicCompleter class to
1455 1468 also complete (last in priority) on user aliases.
1456 1469
1457 1470 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1458 1471 call to eval.
1459 1472 (ItplNS.__init__): Added a new class which functions like Itpl,
1460 1473 but allows configuring the namespace for the evaluation to occur
1461 1474 in.
1462 1475
1463 1476 2004-06-18 Fernando Perez <fperez@colorado.edu>
1464 1477
1465 1478 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1466 1479 better message when 'exit' or 'quit' are typed (a common newbie
1467 1480 confusion).
1468 1481
1469 1482 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1470 1483 check for Windows users.
1471 1484
1472 1485 * IPython/iplib.py (InteractiveShell.user_setup): removed
1473 1486 disabling of colors for Windows. I'll test at runtime and issue a
1474 1487 warning if Gary's readline isn't found, as to nudge users to
1475 1488 download it.
1476 1489
1477 1490 2004-06-16 Fernando Perez <fperez@colorado.edu>
1478 1491
1479 1492 * IPython/genutils.py (Stream.__init__): changed to print errors
1480 1493 to sys.stderr. I had a circular dependency here. Now it's
1481 1494 possible to run ipython as IDLE's shell (consider this pre-alpha,
1482 1495 since true stdout things end up in the starting terminal instead
1483 1496 of IDLE's out).
1484 1497
1485 1498 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1486 1499 users who haven't # updated their prompt_in2 definitions. Remove
1487 1500 eventually.
1488 1501 (multiple_replace): added credit to original ASPN recipe.
1489 1502
1490 1503 2004-06-15 Fernando Perez <fperez@colorado.edu>
1491 1504
1492 1505 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1493 1506 list of auto-defined aliases.
1494 1507
1495 1508 2004-06-13 Fernando Perez <fperez@colorado.edu>
1496 1509
1497 1510 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1498 1511 install was really requested (so setup.py can be used for other
1499 1512 things under Windows).
1500 1513
1501 1514 2004-06-10 Fernando Perez <fperez@colorado.edu>
1502 1515
1503 1516 * IPython/Logger.py (Logger.create_log): Manually remove any old
1504 1517 backup, since os.remove may fail under Windows. Fixes bug
1505 1518 reported by Thorsten.
1506 1519
1507 1520 2004-06-09 Fernando Perez <fperez@colorado.edu>
1508 1521
1509 1522 * examples/example-embed.py: fixed all references to %n (replaced
1510 1523 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1511 1524 for all examples and the manual as well.
1512 1525
1513 1526 2004-06-08 Fernando Perez <fperez@colorado.edu>
1514 1527
1515 1528 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1516 1529 alignment and color management. All 3 prompt subsystems now
1517 1530 inherit from BasePrompt.
1518 1531
1519 1532 * tools/release: updates for windows installer build and tag rpms
1520 1533 with python version (since paths are fixed).
1521 1534
1522 1535 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1523 1536 which will become eventually obsolete. Also fixed the default
1524 1537 prompt_in2 to use \D, so at least new users start with the correct
1525 1538 defaults.
1526 1539 WARNING: Users with existing ipythonrc files will need to apply
1527 1540 this fix manually!
1528 1541
1529 1542 * setup.py: make windows installer (.exe). This is finally the
1530 1543 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1531 1544 which I hadn't included because it required Python 2.3 (or recent
1532 1545 distutils).
1533 1546
1534 1547 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1535 1548 usage of new '\D' escape.
1536 1549
1537 1550 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1538 1551 lacks os.getuid())
1539 1552 (CachedOutput.set_colors): Added the ability to turn coloring
1540 1553 on/off with @colors even for manually defined prompt colors. It
1541 1554 uses a nasty global, but it works safely and via the generic color
1542 1555 handling mechanism.
1543 1556 (Prompt2.__init__): Introduced new escape '\D' for continuation
1544 1557 prompts. It represents the counter ('\#') as dots.
1545 1558 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1546 1559 need to update their ipythonrc files and replace '%n' with '\D' in
1547 1560 their prompt_in2 settings everywhere. Sorry, but there's
1548 1561 otherwise no clean way to get all prompts to properly align. The
1549 1562 ipythonrc shipped with IPython has been updated.
1550 1563
1551 1564 2004-06-07 Fernando Perez <fperez@colorado.edu>
1552 1565
1553 1566 * setup.py (isfile): Pass local_icons option to latex2html, so the
1554 1567 resulting HTML file is self-contained. Thanks to
1555 1568 dryice-AT-liu.com.cn for the tip.
1556 1569
1557 1570 * pysh.py: I created a new profile 'shell', which implements a
1558 1571 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1559 1572 system shell, nor will it become one anytime soon. It's mainly
1560 1573 meant to illustrate the use of the new flexible bash-like prompts.
1561 1574 I guess it could be used by hardy souls for true shell management,
1562 1575 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1563 1576 profile. This uses the InterpreterExec extension provided by
1564 1577 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1565 1578
1566 1579 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1567 1580 auto-align itself with the length of the previous input prompt
1568 1581 (taking into account the invisible color escapes).
1569 1582 (CachedOutput.__init__): Large restructuring of this class. Now
1570 1583 all three prompts (primary1, primary2, output) are proper objects,
1571 1584 managed by the 'parent' CachedOutput class. The code is still a
1572 1585 bit hackish (all prompts share state via a pointer to the cache),
1573 1586 but it's overall far cleaner than before.
1574 1587
1575 1588 * IPython/genutils.py (getoutputerror): modified to add verbose,
1576 1589 debug and header options. This makes the interface of all getout*
1577 1590 functions uniform.
1578 1591 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1579 1592
1580 1593 * IPython/Magic.py (Magic.default_option): added a function to
1581 1594 allow registering default options for any magic command. This
1582 1595 makes it easy to have profiles which customize the magics globally
1583 1596 for a certain use. The values set through this function are
1584 1597 picked up by the parse_options() method, which all magics should
1585 1598 use to parse their options.
1586 1599
1587 1600 * IPython/genutils.py (warn): modified the warnings framework to
1588 1601 use the Term I/O class. I'm trying to slowly unify all of
1589 1602 IPython's I/O operations to pass through Term.
1590 1603
1591 1604 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1592 1605 the secondary prompt to correctly match the length of the primary
1593 1606 one for any prompt. Now multi-line code will properly line up
1594 1607 even for path dependent prompts, such as the new ones available
1595 1608 via the prompt_specials.
1596 1609
1597 1610 2004-06-06 Fernando Perez <fperez@colorado.edu>
1598 1611
1599 1612 * IPython/Prompts.py (prompt_specials): Added the ability to have
1600 1613 bash-like special sequences in the prompts, which get
1601 1614 automatically expanded. Things like hostname, current working
1602 1615 directory and username are implemented already, but it's easy to
1603 1616 add more in the future. Thanks to a patch by W.J. van der Laan
1604 1617 <gnufnork-AT-hetdigitalegat.nl>
1605 1618 (prompt_specials): Added color support for prompt strings, so
1606 1619 users can define arbitrary color setups for their prompts.
1607 1620
1608 1621 2004-06-05 Fernando Perez <fperez@colorado.edu>
1609 1622
1610 1623 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1611 1624 code to load Gary Bishop's readline and configure it
1612 1625 automatically. Thanks to Gary for help on this.
1613 1626
1614 1627 2004-06-01 Fernando Perez <fperez@colorado.edu>
1615 1628
1616 1629 * IPython/Logger.py (Logger.create_log): fix bug for logging
1617 1630 with no filename (previous fix was incomplete).
1618 1631
1619 1632 2004-05-25 Fernando Perez <fperez@colorado.edu>
1620 1633
1621 1634 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1622 1635 parens would get passed to the shell.
1623 1636
1624 1637 2004-05-20 Fernando Perez <fperez@colorado.edu>
1625 1638
1626 1639 * IPython/Magic.py (Magic.magic_prun): changed default profile
1627 1640 sort order to 'time' (the more common profiling need).
1628 1641
1629 1642 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1630 1643 so that source code shown is guaranteed in sync with the file on
1631 1644 disk (also changed in psource). Similar fix to the one for
1632 1645 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1633 1646 <yann.ledu-AT-noos.fr>.
1634 1647
1635 1648 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1636 1649 with a single option would not be correctly parsed. Closes
1637 1650 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1638 1651 introduced in 0.6.0 (on 2004-05-06).
1639 1652
1640 1653 2004-05-13 *** Released version 0.6.0
1641 1654
1642 1655 2004-05-13 Fernando Perez <fperez@colorado.edu>
1643 1656
1644 1657 * debian/: Added debian/ directory to CVS, so that debian support
1645 1658 is publicly accessible. The debian package is maintained by Jack
1646 1659 Moffit <jack-AT-xiph.org>.
1647 1660
1648 1661 * Documentation: included the notes about an ipython-based system
1649 1662 shell (the hypothetical 'pysh') into the new_design.pdf document,
1650 1663 so that these ideas get distributed to users along with the
1651 1664 official documentation.
1652 1665
1653 1666 2004-05-10 Fernando Perez <fperez@colorado.edu>
1654 1667
1655 1668 * IPython/Logger.py (Logger.create_log): fix recently introduced
1656 1669 bug (misindented line) where logstart would fail when not given an
1657 1670 explicit filename.
1658 1671
1659 1672 2004-05-09 Fernando Perez <fperez@colorado.edu>
1660 1673
1661 1674 * IPython/Magic.py (Magic.parse_options): skip system call when
1662 1675 there are no options to look for. Faster, cleaner for the common
1663 1676 case.
1664 1677
1665 1678 * Documentation: many updates to the manual: describing Windows
1666 1679 support better, Gnuplot updates, credits, misc small stuff. Also
1667 1680 updated the new_design doc a bit.
1668 1681
1669 1682 2004-05-06 *** Released version 0.6.0.rc1
1670 1683
1671 1684 2004-05-06 Fernando Perez <fperez@colorado.edu>
1672 1685
1673 1686 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1674 1687 operations to use the vastly more efficient list/''.join() method.
1675 1688 (FormattedTB.text): Fix
1676 1689 http://www.scipy.net/roundup/ipython/issue12 - exception source
1677 1690 extract not updated after reload. Thanks to Mike Salib
1678 1691 <msalib-AT-mit.edu> for pinning the source of the problem.
1679 1692 Fortunately, the solution works inside ipython and doesn't require
1680 1693 any changes to python proper.
1681 1694
1682 1695 * IPython/Magic.py (Magic.parse_options): Improved to process the
1683 1696 argument list as a true shell would (by actually using the
1684 1697 underlying system shell). This way, all @magics automatically get
1685 1698 shell expansion for variables. Thanks to a comment by Alex
1686 1699 Schmolck.
1687 1700
1688 1701 2004-04-04 Fernando Perez <fperez@colorado.edu>
1689 1702
1690 1703 * IPython/iplib.py (InteractiveShell.interact): Added a special
1691 1704 trap for a debugger quit exception, which is basically impossible
1692 1705 to handle by normal mechanisms, given what pdb does to the stack.
1693 1706 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1694 1707
1695 1708 2004-04-03 Fernando Perez <fperez@colorado.edu>
1696 1709
1697 1710 * IPython/genutils.py (Term): Standardized the names of the Term
1698 1711 class streams to cin/cout/cerr, following C++ naming conventions
1699 1712 (I can't use in/out/err because 'in' is not a valid attribute
1700 1713 name).
1701 1714
1702 1715 * IPython/iplib.py (InteractiveShell.interact): don't increment
1703 1716 the prompt if there's no user input. By Daniel 'Dang' Griffith
1704 1717 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
1705 1718 Francois Pinard.
1706 1719
1707 1720 2004-04-02 Fernando Perez <fperez@colorado.edu>
1708 1721
1709 1722 * IPython/genutils.py (Stream.__init__): Modified to survive at
1710 1723 least importing in contexts where stdin/out/err aren't true file
1711 1724 objects, such as PyCrust (they lack fileno() and mode). However,
1712 1725 the recovery facilities which rely on these things existing will
1713 1726 not work.
1714 1727
1715 1728 2004-04-01 Fernando Perez <fperez@colorado.edu>
1716 1729
1717 1730 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
1718 1731 use the new getoutputerror() function, so it properly
1719 1732 distinguishes stdout/err.
1720 1733
1721 1734 * IPython/genutils.py (getoutputerror): added a function to
1722 1735 capture separately the standard output and error of a command.
1723 1736 After a comment from dang on the mailing lists. This code is
1724 1737 basically a modified version of commands.getstatusoutput(), from
1725 1738 the standard library.
1726 1739
1727 1740 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
1728 1741 '!!' as a special syntax (shorthand) to access @sx.
1729 1742
1730 1743 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
1731 1744 command and return its output as a list split on '\n'.
1732 1745
1733 1746 2004-03-31 Fernando Perez <fperez@colorado.edu>
1734 1747
1735 1748 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
1736 1749 method to dictionaries used as FakeModule instances if they lack
1737 1750 it. At least pydoc in python2.3 breaks for runtime-defined
1738 1751 functions without this hack. At some point I need to _really_
1739 1752 understand what FakeModule is doing, because it's a gross hack.
1740 1753 But it solves Arnd's problem for now...
1741 1754
1742 1755 2004-02-27 Fernando Perez <fperez@colorado.edu>
1743 1756
1744 1757 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
1745 1758 mode would behave erratically. Also increased the number of
1746 1759 possible logs in rotate mod to 999. Thanks to Rod Holland
1747 1760 <rhh@StructureLABS.com> for the report and fixes.
1748 1761
1749 1762 2004-02-26 Fernando Perez <fperez@colorado.edu>
1750 1763
1751 1764 * IPython/genutils.py (page): Check that the curses module really
1752 1765 has the initscr attribute before trying to use it. For some
1753 1766 reason, the Solaris curses module is missing this. I think this
1754 1767 should be considered a Solaris python bug, but I'm not sure.
1755 1768
1756 1769 2004-01-17 Fernando Perez <fperez@colorado.edu>
1757 1770
1758 1771 * IPython/genutils.py (Stream.__init__): Changes to try to make
1759 1772 ipython robust against stdin/out/err being closed by the user.
1760 1773 This is 'user error' (and blocks a normal python session, at least
1761 1774 the stdout case). However, Ipython should be able to survive such
1762 1775 instances of abuse as gracefully as possible. To simplify the
1763 1776 coding and maintain compatibility with Gary Bishop's Term
1764 1777 contributions, I've made use of classmethods for this. I think
1765 1778 this introduces a dependency on python 2.2.
1766 1779
1767 1780 2004-01-13 Fernando Perez <fperez@colorado.edu>
1768 1781
1769 1782 * IPython/numutils.py (exp_safe): simplified the code a bit and
1770 1783 removed the need for importing the kinds module altogether.
1771 1784
1772 1785 2004-01-06 Fernando Perez <fperez@colorado.edu>
1773 1786
1774 1787 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
1775 1788 a magic function instead, after some community feedback. No
1776 1789 special syntax will exist for it, but its name is deliberately
1777 1790 very short.
1778 1791
1779 1792 2003-12-20 Fernando Perez <fperez@colorado.edu>
1780 1793
1781 1794 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
1782 1795 new functionality, to automagically assign the result of a shell
1783 1796 command to a variable. I'll solicit some community feedback on
1784 1797 this before making it permanent.
1785 1798
1786 1799 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
1787 1800 requested about callables for which inspect couldn't obtain a
1788 1801 proper argspec. Thanks to a crash report sent by Etienne
1789 1802 Posthumus <etienne-AT-apple01.cs.vu.nl>.
1790 1803
1791 1804 2003-12-09 Fernando Perez <fperez@colorado.edu>
1792 1805
1793 1806 * IPython/genutils.py (page): patch for the pager to work across
1794 1807 various versions of Windows. By Gary Bishop.
1795 1808
1796 1809 2003-12-04 Fernando Perez <fperez@colorado.edu>
1797 1810
1798 1811 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
1799 1812 Gnuplot.py version 1.7, whose internal names changed quite a bit.
1800 1813 While I tested this and it looks ok, there may still be corner
1801 1814 cases I've missed.
1802 1815
1803 1816 2003-12-01 Fernando Perez <fperez@colorado.edu>
1804 1817
1805 1818 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
1806 1819 where a line like 'p,q=1,2' would fail because the automagic
1807 1820 system would be triggered for @p.
1808 1821
1809 1822 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
1810 1823 cleanups, code unmodified.
1811 1824
1812 1825 * IPython/genutils.py (Term): added a class for IPython to handle
1813 1826 output. In most cases it will just be a proxy for stdout/err, but
1814 1827 having this allows modifications to be made for some platforms,
1815 1828 such as handling color escapes under Windows. All of this code
1816 1829 was contributed by Gary Bishop, with minor modifications by me.
1817 1830 The actual changes affect many files.
1818 1831
1819 1832 2003-11-30 Fernando Perez <fperez@colorado.edu>
1820 1833
1821 1834 * IPython/iplib.py (file_matches): new completion code, courtesy
1822 1835 of Jeff Collins. This enables filename completion again under
1823 1836 python 2.3, which disabled it at the C level.
1824 1837
1825 1838 2003-11-11 Fernando Perez <fperez@colorado.edu>
1826 1839
1827 1840 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
1828 1841 for Numeric.array(map(...)), but often convenient.
1829 1842
1830 1843 2003-11-05 Fernando Perez <fperez@colorado.edu>
1831 1844
1832 1845 * IPython/numutils.py (frange): Changed a call from int() to
1833 1846 int(round()) to prevent a problem reported with arange() in the
1834 1847 numpy list.
1835 1848
1836 1849 2003-10-06 Fernando Perez <fperez@colorado.edu>
1837 1850
1838 1851 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
1839 1852 prevent crashes if sys lacks an argv attribute (it happens with
1840 1853 embedded interpreters which build a bare-bones sys module).
1841 1854 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
1842 1855
1843 1856 2003-09-24 Fernando Perez <fperez@colorado.edu>
1844 1857
1845 1858 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
1846 1859 to protect against poorly written user objects where __getattr__
1847 1860 raises exceptions other than AttributeError. Thanks to a bug
1848 1861 report by Oliver Sander <osander-AT-gmx.de>.
1849 1862
1850 1863 * IPython/FakeModule.py (FakeModule.__repr__): this method was
1851 1864 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
1852 1865
1853 1866 2003-09-09 Fernando Perez <fperez@colorado.edu>
1854 1867
1855 1868 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1856 1869 unpacking a list whith a callable as first element would
1857 1870 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
1858 1871 Collins.
1859 1872
1860 1873 2003-08-25 *** Released version 0.5.0
1861 1874
1862 1875 2003-08-22 Fernando Perez <fperez@colorado.edu>
1863 1876
1864 1877 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
1865 1878 improperly defined user exceptions. Thanks to feedback from Mark
1866 1879 Russell <mrussell-AT-verio.net>.
1867 1880
1868 1881 2003-08-20 Fernando Perez <fperez@colorado.edu>
1869 1882
1870 1883 * IPython/OInspect.py (Inspector.pinfo): changed String Form
1871 1884 printing so that it would print multi-line string forms starting
1872 1885 with a new line. This way the formatting is better respected for
1873 1886 objects which work hard to make nice string forms.
1874 1887
1875 1888 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
1876 1889 autocall would overtake data access for objects with both
1877 1890 __getitem__ and __call__.
1878 1891
1879 1892 2003-08-19 *** Released version 0.5.0-rc1
1880 1893
1881 1894 2003-08-19 Fernando Perez <fperez@colorado.edu>
1882 1895
1883 1896 * IPython/deep_reload.py (load_tail): single tiny change here
1884 1897 seems to fix the long-standing bug of dreload() failing to work
1885 1898 for dotted names. But this module is pretty tricky, so I may have
1886 1899 missed some subtlety. Needs more testing!.
1887 1900
1888 1901 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
1889 1902 exceptions which have badly implemented __str__ methods.
1890 1903 (VerboseTB.text): harden against inspect.getinnerframes crashing,
1891 1904 which I've been getting reports about from Python 2.3 users. I
1892 1905 wish I had a simple test case to reproduce the problem, so I could
1893 1906 either write a cleaner workaround or file a bug report if
1894 1907 necessary.
1895 1908
1896 1909 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
1897 1910 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
1898 1911 a bug report by Tjabo Kloppenburg.
1899 1912
1900 1913 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
1901 1914 crashes. Wrapped the pdb call in a blanket try/except, since pdb
1902 1915 seems rather unstable. Thanks to a bug report by Tjabo
1903 1916 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
1904 1917
1905 1918 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
1906 1919 this out soon because of the critical fixes in the inner loop for
1907 1920 generators.
1908 1921
1909 1922 * IPython/Magic.py (Magic.getargspec): removed. This (and
1910 1923 _get_def) have been obsoleted by OInspect for a long time, I
1911 1924 hadn't noticed that they were dead code.
1912 1925 (Magic._ofind): restored _ofind functionality for a few literals
1913 1926 (those in ["''",'""','[]','{}','()']). But it won't work anymore
1914 1927 for things like "hello".capitalize?, since that would require a
1915 1928 potentially dangerous eval() again.
1916 1929
1917 1930 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
1918 1931 logic a bit more to clean up the escapes handling and minimize the
1919 1932 use of _ofind to only necessary cases. The interactive 'feel' of
1920 1933 IPython should have improved quite a bit with the changes in
1921 1934 _prefilter and _ofind (besides being far safer than before).
1922 1935
1923 1936 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
1924 1937 obscure, never reported). Edit would fail to find the object to
1925 1938 edit under some circumstances.
1926 1939 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
1927 1940 which were causing double-calling of generators. Those eval calls
1928 1941 were _very_ dangerous, since code with side effects could be
1929 1942 triggered. As they say, 'eval is evil'... These were the
1930 1943 nastiest evals in IPython. Besides, _ofind is now far simpler,
1931 1944 and it should also be quite a bit faster. Its use of inspect is
1932 1945 also safer, so perhaps some of the inspect-related crashes I've
1933 1946 seen lately with Python 2.3 might be taken care of. That will
1934 1947 need more testing.
1935 1948
1936 1949 2003-08-17 Fernando Perez <fperez@colorado.edu>
1937 1950
1938 1951 * IPython/iplib.py (InteractiveShell._prefilter): significant
1939 1952 simplifications to the logic for handling user escapes. Faster
1940 1953 and simpler code.
1941 1954
1942 1955 2003-08-14 Fernando Perez <fperez@colorado.edu>
1943 1956
1944 1957 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
1945 1958 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
1946 1959 but it should be quite a bit faster. And the recursive version
1947 1960 generated O(log N) intermediate storage for all rank>1 arrays,
1948 1961 even if they were contiguous.
1949 1962 (l1norm): Added this function.
1950 1963 (norm): Added this function for arbitrary norms (including
1951 1964 l-infinity). l1 and l2 are still special cases for convenience
1952 1965 and speed.
1953 1966
1954 1967 2003-08-03 Fernando Perez <fperez@colorado.edu>
1955 1968
1956 1969 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
1957 1970 exceptions, which now raise PendingDeprecationWarnings in Python
1958 1971 2.3. There were some in Magic and some in Gnuplot2.
1959 1972
1960 1973 2003-06-30 Fernando Perez <fperez@colorado.edu>
1961 1974
1962 1975 * IPython/genutils.py (page): modified to call curses only for
1963 1976 terminals where TERM=='xterm'. After problems under many other
1964 1977 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
1965 1978
1966 1979 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
1967 1980 would be triggered when readline was absent. This was just an old
1968 1981 debugging statement I'd forgotten to take out.
1969 1982
1970 1983 2003-06-20 Fernando Perez <fperez@colorado.edu>
1971 1984
1972 1985 * IPython/genutils.py (clock): modified to return only user time
1973 1986 (not counting system time), after a discussion on scipy. While
1974 1987 system time may be a useful quantity occasionally, it may much
1975 1988 more easily be skewed by occasional swapping or other similar
1976 1989 activity.
1977 1990
1978 1991 2003-06-05 Fernando Perez <fperez@colorado.edu>
1979 1992
1980 1993 * IPython/numutils.py (identity): new function, for building
1981 1994 arbitrary rank Kronecker deltas (mostly backwards compatible with
1982 1995 Numeric.identity)
1983 1996
1984 1997 2003-06-03 Fernando Perez <fperez@colorado.edu>
1985 1998
1986 1999 * IPython/iplib.py (InteractiveShell.handle_magic): protect
1987 2000 arguments passed to magics with spaces, to allow trailing '\' to
1988 2001 work normally (mainly for Windows users).
1989 2002
1990 2003 2003-05-29 Fernando Perez <fperez@colorado.edu>
1991 2004
1992 2005 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
1993 2006 instead of pydoc.help. This fixes a bizarre behavior where
1994 2007 printing '%s' % locals() would trigger the help system. Now
1995 2008 ipython behaves like normal python does.
1996 2009
1997 2010 Note that if one does 'from pydoc import help', the bizarre
1998 2011 behavior returns, but this will also happen in normal python, so
1999 2012 it's not an ipython bug anymore (it has to do with how pydoc.help
2000 2013 is implemented).
2001 2014
2002 2015 2003-05-22 Fernando Perez <fperez@colorado.edu>
2003 2016
2004 2017 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2005 2018 return [] instead of None when nothing matches, also match to end
2006 2019 of line. Patch by Gary Bishop.
2007 2020
2008 2021 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2009 2022 protection as before, for files passed on the command line. This
2010 2023 prevents the CrashHandler from kicking in if user files call into
2011 2024 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2012 2025 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2013 2026
2014 2027 2003-05-20 *** Released version 0.4.0
2015 2028
2016 2029 2003-05-20 Fernando Perez <fperez@colorado.edu>
2017 2030
2018 2031 * setup.py: added support for manpages. It's a bit hackish b/c of
2019 2032 a bug in the way the bdist_rpm distutils target handles gzipped
2020 2033 manpages, but it works. After a patch by Jack.
2021 2034
2022 2035 2003-05-19 Fernando Perez <fperez@colorado.edu>
2023 2036
2024 2037 * IPython/numutils.py: added a mockup of the kinds module, since
2025 2038 it was recently removed from Numeric. This way, numutils will
2026 2039 work for all users even if they are missing kinds.
2027 2040
2028 2041 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2029 2042 failure, which can occur with SWIG-wrapped extensions. After a
2030 2043 crash report from Prabhu.
2031 2044
2032 2045 2003-05-16 Fernando Perez <fperez@colorado.edu>
2033 2046
2034 2047 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2035 2048 protect ipython from user code which may call directly
2036 2049 sys.excepthook (this looks like an ipython crash to the user, even
2037 2050 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2038 2051 This is especially important to help users of WxWindows, but may
2039 2052 also be useful in other cases.
2040 2053
2041 2054 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2042 2055 an optional tb_offset to be specified, and to preserve exception
2043 2056 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2044 2057
2045 2058 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2046 2059
2047 2060 2003-05-15 Fernando Perez <fperez@colorado.edu>
2048 2061
2049 2062 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2050 2063 installing for a new user under Windows.
2051 2064
2052 2065 2003-05-12 Fernando Perez <fperez@colorado.edu>
2053 2066
2054 2067 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2055 2068 handler for Emacs comint-based lines. Currently it doesn't do
2056 2069 much (but importantly, it doesn't update the history cache). In
2057 2070 the future it may be expanded if Alex needs more functionality
2058 2071 there.
2059 2072
2060 2073 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2061 2074 info to crash reports.
2062 2075
2063 2076 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2064 2077 just like Python's -c. Also fixed crash with invalid -color
2065 2078 option value at startup. Thanks to Will French
2066 2079 <wfrench-AT-bestweb.net> for the bug report.
2067 2080
2068 2081 2003-05-09 Fernando Perez <fperez@colorado.edu>
2069 2082
2070 2083 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2071 2084 to EvalDict (it's a mapping, after all) and simplified its code
2072 2085 quite a bit, after a nice discussion on c.l.py where Gustavo
2073 2086 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2074 2087
2075 2088 2003-04-30 Fernando Perez <fperez@colorado.edu>
2076 2089
2077 2090 * IPython/genutils.py (timings_out): modified it to reduce its
2078 2091 overhead in the common reps==1 case.
2079 2092
2080 2093 2003-04-29 Fernando Perez <fperez@colorado.edu>
2081 2094
2082 2095 * IPython/genutils.py (timings_out): Modified to use the resource
2083 2096 module, which avoids the wraparound problems of time.clock().
2084 2097
2085 2098 2003-04-17 *** Released version 0.2.15pre4
2086 2099
2087 2100 2003-04-17 Fernando Perez <fperez@colorado.edu>
2088 2101
2089 2102 * setup.py (scriptfiles): Split windows-specific stuff over to a
2090 2103 separate file, in an attempt to have a Windows GUI installer.
2091 2104 That didn't work, but part of the groundwork is done.
2092 2105
2093 2106 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2094 2107 indent/unindent with 4 spaces. Particularly useful in combination
2095 2108 with the new auto-indent option.
2096 2109
2097 2110 2003-04-16 Fernando Perez <fperez@colorado.edu>
2098 2111
2099 2112 * IPython/Magic.py: various replacements of self.rc for
2100 2113 self.shell.rc. A lot more remains to be done to fully disentangle
2101 2114 this class from the main Shell class.
2102 2115
2103 2116 * IPython/GnuplotRuntime.py: added checks for mouse support so
2104 2117 that we don't try to enable it if the current gnuplot doesn't
2105 2118 really support it. Also added checks so that we don't try to
2106 2119 enable persist under Windows (where Gnuplot doesn't recognize the
2107 2120 option).
2108 2121
2109 2122 * IPython/iplib.py (InteractiveShell.interact): Added optional
2110 2123 auto-indenting code, after a patch by King C. Shu
2111 2124 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2112 2125 get along well with pasting indented code. If I ever figure out
2113 2126 how to make that part go well, it will become on by default.
2114 2127
2115 2128 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2116 2129 crash ipython if there was an unmatched '%' in the user's prompt
2117 2130 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2118 2131
2119 2132 * IPython/iplib.py (InteractiveShell.interact): removed the
2120 2133 ability to ask the user whether he wants to crash or not at the
2121 2134 'last line' exception handler. Calling functions at that point
2122 2135 changes the stack, and the error reports would have incorrect
2123 2136 tracebacks.
2124 2137
2125 2138 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2126 2139 pass through a peger a pretty-printed form of any object. After a
2127 2140 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2128 2141
2129 2142 2003-04-14 Fernando Perez <fperez@colorado.edu>
2130 2143
2131 2144 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2132 2145 all files in ~ would be modified at first install (instead of
2133 2146 ~/.ipython). This could be potentially disastrous, as the
2134 2147 modification (make line-endings native) could damage binary files.
2135 2148
2136 2149 2003-04-10 Fernando Perez <fperez@colorado.edu>
2137 2150
2138 2151 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2139 2152 handle only lines which are invalid python. This now means that
2140 2153 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2141 2154 for the bug report.
2142 2155
2143 2156 2003-04-01 Fernando Perez <fperez@colorado.edu>
2144 2157
2145 2158 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2146 2159 where failing to set sys.last_traceback would crash pdb.pm().
2147 2160 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2148 2161 report.
2149 2162
2150 2163 2003-03-25 Fernando Perez <fperez@colorado.edu>
2151 2164
2152 2165 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2153 2166 before printing it (it had a lot of spurious blank lines at the
2154 2167 end).
2155 2168
2156 2169 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2157 2170 output would be sent 21 times! Obviously people don't use this
2158 2171 too often, or I would have heard about it.
2159 2172
2160 2173 2003-03-24 Fernando Perez <fperez@colorado.edu>
2161 2174
2162 2175 * setup.py (scriptfiles): renamed the data_files parameter from
2163 2176 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2164 2177 for the patch.
2165 2178
2166 2179 2003-03-20 Fernando Perez <fperez@colorado.edu>
2167 2180
2168 2181 * IPython/genutils.py (error): added error() and fatal()
2169 2182 functions.
2170 2183
2171 2184 2003-03-18 *** Released version 0.2.15pre3
2172 2185
2173 2186 2003-03-18 Fernando Perez <fperez@colorado.edu>
2174 2187
2175 2188 * setupext/install_data_ext.py
2176 2189 (install_data_ext.initialize_options): Class contributed by Jack
2177 2190 Moffit for fixing the old distutils hack. He is sending this to
2178 2191 the distutils folks so in the future we may not need it as a
2179 2192 private fix.
2180 2193
2181 2194 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2182 2195 changes for Debian packaging. See his patch for full details.
2183 2196 The old distutils hack of making the ipythonrc* files carry a
2184 2197 bogus .py extension is gone, at last. Examples were moved to a
2185 2198 separate subdir under doc/, and the separate executable scripts
2186 2199 now live in their own directory. Overall a great cleanup. The
2187 2200 manual was updated to use the new files, and setup.py has been
2188 2201 fixed for this setup.
2189 2202
2190 2203 * IPython/PyColorize.py (Parser.usage): made non-executable and
2191 2204 created a pycolor wrapper around it to be included as a script.
2192 2205
2193 2206 2003-03-12 *** Released version 0.2.15pre2
2194 2207
2195 2208 2003-03-12 Fernando Perez <fperez@colorado.edu>
2196 2209
2197 2210 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2198 2211 long-standing problem with garbage characters in some terminals.
2199 2212 The issue was really that the \001 and \002 escapes must _only_ be
2200 2213 passed to input prompts (which call readline), but _never_ to
2201 2214 normal text to be printed on screen. I changed ColorANSI to have
2202 2215 two classes: TermColors and InputTermColors, each with the
2203 2216 appropriate escapes for input prompts or normal text. The code in
2204 2217 Prompts.py got slightly more complicated, but this very old and
2205 2218 annoying bug is finally fixed.
2206 2219
2207 2220 All the credit for nailing down the real origin of this problem
2208 2221 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2209 2222 *Many* thanks to him for spending quite a bit of effort on this.
2210 2223
2211 2224 2003-03-05 *** Released version 0.2.15pre1
2212 2225
2213 2226 2003-03-03 Fernando Perez <fperez@colorado.edu>
2214 2227
2215 2228 * IPython/FakeModule.py: Moved the former _FakeModule to a
2216 2229 separate file, because it's also needed by Magic (to fix a similar
2217 2230 pickle-related issue in @run).
2218 2231
2219 2232 2003-03-02 Fernando Perez <fperez@colorado.edu>
2220 2233
2221 2234 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2222 2235 the autocall option at runtime.
2223 2236 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2224 2237 across Magic.py to start separating Magic from InteractiveShell.
2225 2238 (Magic._ofind): Fixed to return proper namespace for dotted
2226 2239 names. Before, a dotted name would always return 'not currently
2227 2240 defined', because it would find the 'parent'. s.x would be found,
2228 2241 but since 'x' isn't defined by itself, it would get confused.
2229 2242 (Magic.magic_run): Fixed pickling problems reported by Ralf
2230 2243 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2231 2244 that I'd used when Mike Heeter reported similar issues at the
2232 2245 top-level, but now for @run. It boils down to injecting the
2233 2246 namespace where code is being executed with something that looks
2234 2247 enough like a module to fool pickle.dump(). Since a pickle stores
2235 2248 a named reference to the importing module, we need this for
2236 2249 pickles to save something sensible.
2237 2250
2238 2251 * IPython/ipmaker.py (make_IPython): added an autocall option.
2239 2252
2240 2253 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2241 2254 the auto-eval code. Now autocalling is an option, and the code is
2242 2255 also vastly safer. There is no more eval() involved at all.
2243 2256
2244 2257 2003-03-01 Fernando Perez <fperez@colorado.edu>
2245 2258
2246 2259 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2247 2260 dict with named keys instead of a tuple.
2248 2261
2249 2262 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2250 2263
2251 2264 * setup.py (make_shortcut): Fixed message about directories
2252 2265 created during Windows installation (the directories were ok, just
2253 2266 the printed message was misleading). Thanks to Chris Liechti
2254 2267 <cliechti-AT-gmx.net> for the heads up.
2255 2268
2256 2269 2003-02-21 Fernando Perez <fperez@colorado.edu>
2257 2270
2258 2271 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2259 2272 of ValueError exception when checking for auto-execution. This
2260 2273 one is raised by things like Numeric arrays arr.flat when the
2261 2274 array is non-contiguous.
2262 2275
2263 2276 2003-01-31 Fernando Perez <fperez@colorado.edu>
2264 2277
2265 2278 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2266 2279 not return any value at all (even though the command would get
2267 2280 executed).
2268 2281 (xsys): Flush stdout right after printing the command to ensure
2269 2282 proper ordering of commands and command output in the total
2270 2283 output.
2271 2284 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2272 2285 system/getoutput as defaults. The old ones are kept for
2273 2286 compatibility reasons, so no code which uses this library needs
2274 2287 changing.
2275 2288
2276 2289 2003-01-27 *** Released version 0.2.14
2277 2290
2278 2291 2003-01-25 Fernando Perez <fperez@colorado.edu>
2279 2292
2280 2293 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2281 2294 functions defined in previous edit sessions could not be re-edited
2282 2295 (because the temp files were immediately removed). Now temp files
2283 2296 are removed only at IPython's exit.
2284 2297 (Magic.magic_run): Improved @run to perform shell-like expansions
2285 2298 on its arguments (~users and $VARS). With this, @run becomes more
2286 2299 like a normal command-line.
2287 2300
2288 2301 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2289 2302 bugs related to embedding and cleaned up that code. A fairly
2290 2303 important one was the impossibility to access the global namespace
2291 2304 through the embedded IPython (only local variables were visible).
2292 2305
2293 2306 2003-01-14 Fernando Perez <fperez@colorado.edu>
2294 2307
2295 2308 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2296 2309 auto-calling to be a bit more conservative. Now it doesn't get
2297 2310 triggered if any of '!=()<>' are in the rest of the input line, to
2298 2311 allow comparing callables. Thanks to Alex for the heads up.
2299 2312
2300 2313 2003-01-07 Fernando Perez <fperez@colorado.edu>
2301 2314
2302 2315 * IPython/genutils.py (page): fixed estimation of the number of
2303 2316 lines in a string to be paged to simply count newlines. This
2304 2317 prevents over-guessing due to embedded escape sequences. A better
2305 2318 long-term solution would involve stripping out the control chars
2306 2319 for the count, but it's potentially so expensive I just don't
2307 2320 think it's worth doing.
2308 2321
2309 2322 2002-12-19 *** Released version 0.2.14pre50
2310 2323
2311 2324 2002-12-19 Fernando Perez <fperez@colorado.edu>
2312 2325
2313 2326 * tools/release (version): Changed release scripts to inform
2314 2327 Andrea and build a NEWS file with a list of recent changes.
2315 2328
2316 2329 * IPython/ColorANSI.py (__all__): changed terminal detection
2317 2330 code. Seems to work better for xterms without breaking
2318 2331 konsole. Will need more testing to determine if WinXP and Mac OSX
2319 2332 also work ok.
2320 2333
2321 2334 2002-12-18 *** Released version 0.2.14pre49
2322 2335
2323 2336 2002-12-18 Fernando Perez <fperez@colorado.edu>
2324 2337
2325 2338 * Docs: added new info about Mac OSX, from Andrea.
2326 2339
2327 2340 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2328 2341 allow direct plotting of python strings whose format is the same
2329 2342 of gnuplot data files.
2330 2343
2331 2344 2002-12-16 Fernando Perez <fperez@colorado.edu>
2332 2345
2333 2346 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2334 2347 value of exit question to be acknowledged.
2335 2348
2336 2349 2002-12-03 Fernando Perez <fperez@colorado.edu>
2337 2350
2338 2351 * IPython/ipmaker.py: removed generators, which had been added
2339 2352 by mistake in an earlier debugging run. This was causing trouble
2340 2353 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2341 2354 for pointing this out.
2342 2355
2343 2356 2002-11-17 Fernando Perez <fperez@colorado.edu>
2344 2357
2345 2358 * Manual: updated the Gnuplot section.
2346 2359
2347 2360 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2348 2361 a much better split of what goes in Runtime and what goes in
2349 2362 Interactive.
2350 2363
2351 2364 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2352 2365 being imported from iplib.
2353 2366
2354 2367 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2355 2368 for command-passing. Now the global Gnuplot instance is called
2356 2369 'gp' instead of 'g', which was really a far too fragile and
2357 2370 common name.
2358 2371
2359 2372 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2360 2373 bounding boxes generated by Gnuplot for square plots.
2361 2374
2362 2375 * IPython/genutils.py (popkey): new function added. I should
2363 2376 suggest this on c.l.py as a dict method, it seems useful.
2364 2377
2365 2378 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2366 2379 to transparently handle PostScript generation. MUCH better than
2367 2380 the previous plot_eps/replot_eps (which I removed now). The code
2368 2381 is also fairly clean and well documented now (including
2369 2382 docstrings).
2370 2383
2371 2384 2002-11-13 Fernando Perez <fperez@colorado.edu>
2372 2385
2373 2386 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2374 2387 (inconsistent with options).
2375 2388
2376 2389 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2377 2390 manually disabled, I don't know why. Fixed it.
2378 2391 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2379 2392 eps output.
2380 2393
2381 2394 2002-11-12 Fernando Perez <fperez@colorado.edu>
2382 2395
2383 2396 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2384 2397 don't propagate up to caller. Fixes crash reported by François
2385 2398 Pinard.
2386 2399
2387 2400 2002-11-09 Fernando Perez <fperez@colorado.edu>
2388 2401
2389 2402 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2390 2403 history file for new users.
2391 2404 (make_IPython): fixed bug where initial install would leave the
2392 2405 user running in the .ipython dir.
2393 2406 (make_IPython): fixed bug where config dir .ipython would be
2394 2407 created regardless of the given -ipythondir option. Thanks to Cory
2395 2408 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2396 2409
2397 2410 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2398 2411 type confirmations. Will need to use it in all of IPython's code
2399 2412 consistently.
2400 2413
2401 2414 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2402 2415 context to print 31 lines instead of the default 5. This will make
2403 2416 the crash reports extremely detailed in case the problem is in
2404 2417 libraries I don't have access to.
2405 2418
2406 2419 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2407 2420 line of defense' code to still crash, but giving users fair
2408 2421 warning. I don't want internal errors to go unreported: if there's
2409 2422 an internal problem, IPython should crash and generate a full
2410 2423 report.
2411 2424
2412 2425 2002-11-08 Fernando Perez <fperez@colorado.edu>
2413 2426
2414 2427 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2415 2428 otherwise uncaught exceptions which can appear if people set
2416 2429 sys.stdout to something badly broken. Thanks to a crash report
2417 2430 from henni-AT-mail.brainbot.com.
2418 2431
2419 2432 2002-11-04 Fernando Perez <fperez@colorado.edu>
2420 2433
2421 2434 * IPython/iplib.py (InteractiveShell.interact): added
2422 2435 __IPYTHON__active to the builtins. It's a flag which goes on when
2423 2436 the interaction starts and goes off again when it stops. This
2424 2437 allows embedding code to detect being inside IPython. Before this
2425 2438 was done via __IPYTHON__, but that only shows that an IPython
2426 2439 instance has been created.
2427 2440
2428 2441 * IPython/Magic.py (Magic.magic_env): I realized that in a
2429 2442 UserDict, instance.data holds the data as a normal dict. So I
2430 2443 modified @env to return os.environ.data instead of rebuilding a
2431 2444 dict by hand.
2432 2445
2433 2446 2002-11-02 Fernando Perez <fperez@colorado.edu>
2434 2447
2435 2448 * IPython/genutils.py (warn): changed so that level 1 prints no
2436 2449 header. Level 2 is now the default (with 'WARNING' header, as
2437 2450 before). I think I tracked all places where changes were needed in
2438 2451 IPython, but outside code using the old level numbering may have
2439 2452 broken.
2440 2453
2441 2454 * IPython/iplib.py (InteractiveShell.runcode): added this to
2442 2455 handle the tracebacks in SystemExit traps correctly. The previous
2443 2456 code (through interact) was printing more of the stack than
2444 2457 necessary, showing IPython internal code to the user.
2445 2458
2446 2459 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2447 2460 default. Now that the default at the confirmation prompt is yes,
2448 2461 it's not so intrusive. François' argument that ipython sessions
2449 2462 tend to be complex enough not to lose them from an accidental C-d,
2450 2463 is a valid one.
2451 2464
2452 2465 * IPython/iplib.py (InteractiveShell.interact): added a
2453 2466 showtraceback() call to the SystemExit trap, and modified the exit
2454 2467 confirmation to have yes as the default.
2455 2468
2456 2469 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2457 2470 this file. It's been gone from the code for a long time, this was
2458 2471 simply leftover junk.
2459 2472
2460 2473 2002-11-01 Fernando Perez <fperez@colorado.edu>
2461 2474
2462 2475 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2463 2476 added. If set, IPython now traps EOF and asks for
2464 2477 confirmation. After a request by François Pinard.
2465 2478
2466 2479 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2467 2480 of @abort, and with a new (better) mechanism for handling the
2468 2481 exceptions.
2469 2482
2470 2483 2002-10-27 Fernando Perez <fperez@colorado.edu>
2471 2484
2472 2485 * IPython/usage.py (__doc__): updated the --help information and
2473 2486 the ipythonrc file to indicate that -log generates
2474 2487 ./ipython.log. Also fixed the corresponding info in @logstart.
2475 2488 This and several other fixes in the manuals thanks to reports by
2476 2489 François Pinard <pinard-AT-iro.umontreal.ca>.
2477 2490
2478 2491 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2479 2492 refer to @logstart (instead of @log, which doesn't exist).
2480 2493
2481 2494 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2482 2495 AttributeError crash. Thanks to Christopher Armstrong
2483 2496 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2484 2497 introduced recently (in 0.2.14pre37) with the fix to the eval
2485 2498 problem mentioned below.
2486 2499
2487 2500 2002-10-17 Fernando Perez <fperez@colorado.edu>
2488 2501
2489 2502 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2490 2503 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2491 2504
2492 2505 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2493 2506 this function to fix a problem reported by Alex Schmolck. He saw
2494 2507 it with list comprehensions and generators, which were getting
2495 2508 called twice. The real problem was an 'eval' call in testing for
2496 2509 automagic which was evaluating the input line silently.
2497 2510
2498 2511 This is a potentially very nasty bug, if the input has side
2499 2512 effects which must not be repeated. The code is much cleaner now,
2500 2513 without any blanket 'except' left and with a regexp test for
2501 2514 actual function names.
2502 2515
2503 2516 But an eval remains, which I'm not fully comfortable with. I just
2504 2517 don't know how to find out if an expression could be a callable in
2505 2518 the user's namespace without doing an eval on the string. However
2506 2519 that string is now much more strictly checked so that no code
2507 2520 slips by, so the eval should only happen for things that can
2508 2521 really be only function/method names.
2509 2522
2510 2523 2002-10-15 Fernando Perez <fperez@colorado.edu>
2511 2524
2512 2525 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2513 2526 OSX information to main manual, removed README_Mac_OSX file from
2514 2527 distribution. Also updated credits for recent additions.
2515 2528
2516 2529 2002-10-10 Fernando Perez <fperez@colorado.edu>
2517 2530
2518 2531 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2519 2532 terminal-related issues. Many thanks to Andrea Riciputi
2520 2533 <andrea.riciputi-AT-libero.it> for writing it.
2521 2534
2522 2535 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2523 2536 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2524 2537
2525 2538 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2526 2539 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2527 2540 <syver-en-AT-online.no> who both submitted patches for this problem.
2528 2541
2529 2542 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2530 2543 global embedding to make sure that things don't overwrite user
2531 2544 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2532 2545
2533 2546 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2534 2547 compatibility. Thanks to Hayden Callow
2535 2548 <h.callow-AT-elec.canterbury.ac.nz>
2536 2549
2537 2550 2002-10-04 Fernando Perez <fperez@colorado.edu>
2538 2551
2539 2552 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2540 2553 Gnuplot.File objects.
2541 2554
2542 2555 2002-07-23 Fernando Perez <fperez@colorado.edu>
2543 2556
2544 2557 * IPython/genutils.py (timing): Added timings() and timing() for
2545 2558 quick access to the most commonly needed data, the execution
2546 2559 times. Old timing() renamed to timings_out().
2547 2560
2548 2561 2002-07-18 Fernando Perez <fperez@colorado.edu>
2549 2562
2550 2563 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2551 2564 bug with nested instances disrupting the parent's tab completion.
2552 2565
2553 2566 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2554 2567 all_completions code to begin the emacs integration.
2555 2568
2556 2569 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2557 2570 argument to allow titling individual arrays when plotting.
2558 2571
2559 2572 2002-07-15 Fernando Perez <fperez@colorado.edu>
2560 2573
2561 2574 * setup.py (make_shortcut): changed to retrieve the value of
2562 2575 'Program Files' directory from the registry (this value changes in
2563 2576 non-english versions of Windows). Thanks to Thomas Fanslau
2564 2577 <tfanslau-AT-gmx.de> for the report.
2565 2578
2566 2579 2002-07-10 Fernando Perez <fperez@colorado.edu>
2567 2580
2568 2581 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2569 2582 a bug in pdb, which crashes if a line with only whitespace is
2570 2583 entered. Bug report submitted to sourceforge.
2571 2584
2572 2585 2002-07-09 Fernando Perez <fperez@colorado.edu>
2573 2586
2574 2587 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2575 2588 reporting exceptions (it's a bug in inspect.py, I just set a
2576 2589 workaround).
2577 2590
2578 2591 2002-07-08 Fernando Perez <fperez@colorado.edu>
2579 2592
2580 2593 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2581 2594 __IPYTHON__ in __builtins__ to show up in user_ns.
2582 2595
2583 2596 2002-07-03 Fernando Perez <fperez@colorado.edu>
2584 2597
2585 2598 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2586 2599 name from @gp_set_instance to @gp_set_default.
2587 2600
2588 2601 * IPython/ipmaker.py (make_IPython): default editor value set to
2589 2602 '0' (a string), to match the rc file. Otherwise will crash when
2590 2603 .strip() is called on it.
2591 2604
2592 2605
2593 2606 2002-06-28 Fernando Perez <fperez@colorado.edu>
2594 2607
2595 2608 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2596 2609 of files in current directory when a file is executed via
2597 2610 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2598 2611
2599 2612 * setup.py (manfiles): fix for rpm builds, submitted by RA
2600 2613 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2601 2614
2602 2615 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2603 2616 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2604 2617 string!). A. Schmolck caught this one.
2605 2618
2606 2619 2002-06-27 Fernando Perez <fperez@colorado.edu>
2607 2620
2608 2621 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2609 2622 defined files at the cmd line. __name__ wasn't being set to
2610 2623 __main__.
2611 2624
2612 2625 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2613 2626 regular lists and tuples besides Numeric arrays.
2614 2627
2615 2628 * IPython/Prompts.py (CachedOutput.__call__): Added output
2616 2629 supression for input ending with ';'. Similar to Mathematica and
2617 2630 Matlab. The _* vars and Out[] list are still updated, just like
2618 2631 Mathematica behaves.
2619 2632
2620 2633 2002-06-25 Fernando Perez <fperez@colorado.edu>
2621 2634
2622 2635 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2623 2636 .ini extensions for profiels under Windows.
2624 2637
2625 2638 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2626 2639 string form. Fix contributed by Alexander Schmolck
2627 2640 <a.schmolck-AT-gmx.net>
2628 2641
2629 2642 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2630 2643 pre-configured Gnuplot instance.
2631 2644
2632 2645 2002-06-21 Fernando Perez <fperez@colorado.edu>
2633 2646
2634 2647 * IPython/numutils.py (exp_safe): new function, works around the
2635 2648 underflow problems in Numeric.
2636 2649 (log2): New fn. Safe log in base 2: returns exact integer answer
2637 2650 for exact integer powers of 2.
2638 2651
2639 2652 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2640 2653 properly.
2641 2654
2642 2655 2002-06-20 Fernando Perez <fperez@colorado.edu>
2643 2656
2644 2657 * IPython/genutils.py (timing): new function like
2645 2658 Mathematica's. Similar to time_test, but returns more info.
2646 2659
2647 2660 2002-06-18 Fernando Perez <fperez@colorado.edu>
2648 2661
2649 2662 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2650 2663 according to Mike Heeter's suggestions.
2651 2664
2652 2665 2002-06-16 Fernando Perez <fperez@colorado.edu>
2653 2666
2654 2667 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2655 2668 system. GnuplotMagic is gone as a user-directory option. New files
2656 2669 make it easier to use all the gnuplot stuff both from external
2657 2670 programs as well as from IPython. Had to rewrite part of
2658 2671 hardcopy() b/c of a strange bug: often the ps files simply don't
2659 2672 get created, and require a repeat of the command (often several
2660 2673 times).
2661 2674
2662 2675 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2663 2676 resolve output channel at call time, so that if sys.stderr has
2664 2677 been redirected by user this gets honored.
2665 2678
2666 2679 2002-06-13 Fernando Perez <fperez@colorado.edu>
2667 2680
2668 2681 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2669 2682 IPShell. Kept a copy with the old names to avoid breaking people's
2670 2683 embedded code.
2671 2684
2672 2685 * IPython/ipython: simplified it to the bare minimum after
2673 2686 Holger's suggestions. Added info about how to use it in
2674 2687 PYTHONSTARTUP.
2675 2688
2676 2689 * IPython/Shell.py (IPythonShell): changed the options passing
2677 2690 from a string with funky %s replacements to a straight list. Maybe
2678 2691 a bit more typing, but it follows sys.argv conventions, so there's
2679 2692 less special-casing to remember.
2680 2693
2681 2694 2002-06-12 Fernando Perez <fperez@colorado.edu>
2682 2695
2683 2696 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2684 2697 command. Thanks to a suggestion by Mike Heeter.
2685 2698 (Magic.magic_pfile): added behavior to look at filenames if given
2686 2699 arg is not a defined object.
2687 2700 (Magic.magic_save): New @save function to save code snippets. Also
2688 2701 a Mike Heeter idea.
2689 2702
2690 2703 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2691 2704 plot() and replot(). Much more convenient now, especially for
2692 2705 interactive use.
2693 2706
2694 2707 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2695 2708 filenames.
2696 2709
2697 2710 2002-06-02 Fernando Perez <fperez@colorado.edu>
2698 2711
2699 2712 * IPython/Struct.py (Struct.__init__): modified to admit
2700 2713 initialization via another struct.
2701 2714
2702 2715 * IPython/genutils.py (SystemExec.__init__): New stateful
2703 2716 interface to xsys and bq. Useful for writing system scripts.
2704 2717
2705 2718 2002-05-30 Fernando Perez <fperez@colorado.edu>
2706 2719
2707 2720 * MANIFEST.in: Changed docfile selection to exclude all the lyx
2708 2721 documents. This will make the user download smaller (it's getting
2709 2722 too big).
2710 2723
2711 2724 2002-05-29 Fernando Perez <fperez@colorado.edu>
2712 2725
2713 2726 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
2714 2727 fix problems with shelve and pickle. Seems to work, but I don't
2715 2728 know if corner cases break it. Thanks to Mike Heeter
2716 2729 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
2717 2730
2718 2731 2002-05-24 Fernando Perez <fperez@colorado.edu>
2719 2732
2720 2733 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
2721 2734 macros having broken.
2722 2735
2723 2736 2002-05-21 Fernando Perez <fperez@colorado.edu>
2724 2737
2725 2738 * IPython/Magic.py (Magic.magic_logstart): fixed recently
2726 2739 introduced logging bug: all history before logging started was
2727 2740 being written one character per line! This came from the redesign
2728 2741 of the input history as a special list which slices to strings,
2729 2742 not to lists.
2730 2743
2731 2744 2002-05-20 Fernando Perez <fperez@colorado.edu>
2732 2745
2733 2746 * IPython/Prompts.py (CachedOutput.__init__): made the color table
2734 2747 be an attribute of all classes in this module. The design of these
2735 2748 classes needs some serious overhauling.
2736 2749
2737 2750 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
2738 2751 which was ignoring '_' in option names.
2739 2752
2740 2753 * IPython/ultraTB.py (FormattedTB.__init__): Changed
2741 2754 'Verbose_novars' to 'Context' and made it the new default. It's a
2742 2755 bit more readable and also safer than verbose.
2743 2756
2744 2757 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
2745 2758 triple-quoted strings.
2746 2759
2747 2760 * IPython/OInspect.py (__all__): new module exposing the object
2748 2761 introspection facilities. Now the corresponding magics are dummy
2749 2762 wrappers around this. Having this module will make it much easier
2750 2763 to put these functions into our modified pdb.
2751 2764 This new object inspector system uses the new colorizing module,
2752 2765 so source code and other things are nicely syntax highlighted.
2753 2766
2754 2767 2002-05-18 Fernando Perez <fperez@colorado.edu>
2755 2768
2756 2769 * IPython/ColorANSI.py: Split the coloring tools into a separate
2757 2770 module so I can use them in other code easier (they were part of
2758 2771 ultraTB).
2759 2772
2760 2773 2002-05-17 Fernando Perez <fperez@colorado.edu>
2761 2774
2762 2775 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2763 2776 fixed it to set the global 'g' also to the called instance, as
2764 2777 long as 'g' was still a gnuplot instance (so it doesn't overwrite
2765 2778 user's 'g' variables).
2766 2779
2767 2780 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
2768 2781 global variables (aliases to _ih,_oh) so that users which expect
2769 2782 In[5] or Out[7] to work aren't unpleasantly surprised.
2770 2783 (InputList.__getslice__): new class to allow executing slices of
2771 2784 input history directly. Very simple class, complements the use of
2772 2785 macros.
2773 2786
2774 2787 2002-05-16 Fernando Perez <fperez@colorado.edu>
2775 2788
2776 2789 * setup.py (docdirbase): make doc directory be just doc/IPython
2777 2790 without version numbers, it will reduce clutter for users.
2778 2791
2779 2792 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
2780 2793 execfile call to prevent possible memory leak. See for details:
2781 2794 http://mail.python.org/pipermail/python-list/2002-February/088476.html
2782 2795
2783 2796 2002-05-15 Fernando Perez <fperez@colorado.edu>
2784 2797
2785 2798 * IPython/Magic.py (Magic.magic_psource): made the object
2786 2799 introspection names be more standard: pdoc, pdef, pfile and
2787 2800 psource. They all print/page their output, and it makes
2788 2801 remembering them easier. Kept old names for compatibility as
2789 2802 aliases.
2790 2803
2791 2804 2002-05-14 Fernando Perez <fperez@colorado.edu>
2792 2805
2793 2806 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
2794 2807 what the mouse problem was. The trick is to use gnuplot with temp
2795 2808 files and NOT with pipes (for data communication), because having
2796 2809 both pipes and the mouse on is bad news.
2797 2810
2798 2811 2002-05-13 Fernando Perez <fperez@colorado.edu>
2799 2812
2800 2813 * IPython/Magic.py (Magic._ofind): fixed namespace order search
2801 2814 bug. Information would be reported about builtins even when
2802 2815 user-defined functions overrode them.
2803 2816
2804 2817 2002-05-11 Fernando Perez <fperez@colorado.edu>
2805 2818
2806 2819 * IPython/__init__.py (__all__): removed FlexCompleter from
2807 2820 __all__ so that things don't fail in platforms without readline.
2808 2821
2809 2822 2002-05-10 Fernando Perez <fperez@colorado.edu>
2810 2823
2811 2824 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
2812 2825 it requires Numeric, effectively making Numeric a dependency for
2813 2826 IPython.
2814 2827
2815 2828 * Released 0.2.13
2816 2829
2817 2830 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
2818 2831 profiler interface. Now all the major options from the profiler
2819 2832 module are directly supported in IPython, both for single
2820 2833 expressions (@prun) and for full programs (@run -p).
2821 2834
2822 2835 2002-05-09 Fernando Perez <fperez@colorado.edu>
2823 2836
2824 2837 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
2825 2838 magic properly formatted for screen.
2826 2839
2827 2840 * setup.py (make_shortcut): Changed things to put pdf version in
2828 2841 doc/ instead of doc/manual (had to change lyxport a bit).
2829 2842
2830 2843 * IPython/Magic.py (Profile.string_stats): made profile runs go
2831 2844 through pager (they are long and a pager allows searching, saving,
2832 2845 etc.)
2833 2846
2834 2847 2002-05-08 Fernando Perez <fperez@colorado.edu>
2835 2848
2836 2849 * Released 0.2.12
2837 2850
2838 2851 2002-05-06 Fernando Perez <fperez@colorado.edu>
2839 2852
2840 2853 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
2841 2854 introduced); 'hist n1 n2' was broken.
2842 2855 (Magic.magic_pdb): added optional on/off arguments to @pdb
2843 2856 (Magic.magic_run): added option -i to @run, which executes code in
2844 2857 the IPython namespace instead of a clean one. Also added @irun as
2845 2858 an alias to @run -i.
2846 2859
2847 2860 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2848 2861 fixed (it didn't really do anything, the namespaces were wrong).
2849 2862
2850 2863 * IPython/Debugger.py (__init__): Added workaround for python 2.1
2851 2864
2852 2865 * IPython/__init__.py (__all__): Fixed package namespace, now
2853 2866 'import IPython' does give access to IPython.<all> as
2854 2867 expected. Also renamed __release__ to Release.
2855 2868
2856 2869 * IPython/Debugger.py (__license__): created new Pdb class which
2857 2870 functions like a drop-in for the normal pdb.Pdb but does NOT
2858 2871 import readline by default. This way it doesn't muck up IPython's
2859 2872 readline handling, and now tab-completion finally works in the
2860 2873 debugger -- sort of. It completes things globally visible, but the
2861 2874 completer doesn't track the stack as pdb walks it. That's a bit
2862 2875 tricky, and I'll have to implement it later.
2863 2876
2864 2877 2002-05-05 Fernando Perez <fperez@colorado.edu>
2865 2878
2866 2879 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
2867 2880 magic docstrings when printed via ? (explicit \'s were being
2868 2881 printed).
2869 2882
2870 2883 * IPython/ipmaker.py (make_IPython): fixed namespace
2871 2884 identification bug. Now variables loaded via logs or command-line
2872 2885 files are recognized in the interactive namespace by @who.
2873 2886
2874 2887 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
2875 2888 log replay system stemming from the string form of Structs.
2876 2889
2877 2890 * IPython/Magic.py (Macro.__init__): improved macros to properly
2878 2891 handle magic commands in them.
2879 2892 (Magic.magic_logstart): usernames are now expanded so 'logstart
2880 2893 ~/mylog' now works.
2881 2894
2882 2895 * IPython/iplib.py (complete): fixed bug where paths starting with
2883 2896 '/' would be completed as magic names.
2884 2897
2885 2898 2002-05-04 Fernando Perez <fperez@colorado.edu>
2886 2899
2887 2900 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
2888 2901 allow running full programs under the profiler's control.
2889 2902
2890 2903 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
2891 2904 mode to report exceptions verbosely but without formatting
2892 2905 variables. This addresses the issue of ipython 'freezing' (it's
2893 2906 not frozen, but caught in an expensive formatting loop) when huge
2894 2907 variables are in the context of an exception.
2895 2908 (VerboseTB.text): Added '--->' markers at line where exception was
2896 2909 triggered. Much clearer to read, especially in NoColor modes.
2897 2910
2898 2911 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
2899 2912 implemented in reverse when changing to the new parse_options().
2900 2913
2901 2914 2002-05-03 Fernando Perez <fperez@colorado.edu>
2902 2915
2903 2916 * IPython/Magic.py (Magic.parse_options): new function so that
2904 2917 magics can parse options easier.
2905 2918 (Magic.magic_prun): new function similar to profile.run(),
2906 2919 suggested by Chris Hart.
2907 2920 (Magic.magic_cd): fixed behavior so that it only changes if
2908 2921 directory actually is in history.
2909 2922
2910 2923 * IPython/usage.py (__doc__): added information about potential
2911 2924 slowness of Verbose exception mode when there are huge data
2912 2925 structures to be formatted (thanks to Archie Paulson).
2913 2926
2914 2927 * IPython/ipmaker.py (make_IPython): Changed default logging
2915 2928 (when simply called with -log) to use curr_dir/ipython.log in
2916 2929 rotate mode. Fixed crash which was occuring with -log before
2917 2930 (thanks to Jim Boyle).
2918 2931
2919 2932 2002-05-01 Fernando Perez <fperez@colorado.edu>
2920 2933
2921 2934 * Released 0.2.11 for these fixes (mainly the ultraTB one which
2922 2935 was nasty -- though somewhat of a corner case).
2923 2936
2924 2937 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
2925 2938 text (was a bug).
2926 2939
2927 2940 2002-04-30 Fernando Perez <fperez@colorado.edu>
2928 2941
2929 2942 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
2930 2943 a print after ^D or ^C from the user so that the In[] prompt
2931 2944 doesn't over-run the gnuplot one.
2932 2945
2933 2946 2002-04-29 Fernando Perez <fperez@colorado.edu>
2934 2947
2935 2948 * Released 0.2.10
2936 2949
2937 2950 * IPython/__release__.py (version): get date dynamically.
2938 2951
2939 2952 * Misc. documentation updates thanks to Arnd's comments. Also ran
2940 2953 a full spellcheck on the manual (hadn't been done in a while).
2941 2954
2942 2955 2002-04-27 Fernando Perez <fperez@colorado.edu>
2943 2956
2944 2957 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
2945 2958 starting a log in mid-session would reset the input history list.
2946 2959
2947 2960 2002-04-26 Fernando Perez <fperez@colorado.edu>
2948 2961
2949 2962 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
2950 2963 all files were being included in an update. Now anything in
2951 2964 UserConfig that matches [A-Za-z]*.py will go (this excludes
2952 2965 __init__.py)
2953 2966
2954 2967 2002-04-25 Fernando Perez <fperez@colorado.edu>
2955 2968
2956 2969 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
2957 2970 to __builtins__ so that any form of embedded or imported code can
2958 2971 test for being inside IPython.
2959 2972
2960 2973 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
2961 2974 changed to GnuplotMagic because it's now an importable module,
2962 2975 this makes the name follow that of the standard Gnuplot module.
2963 2976 GnuplotMagic can now be loaded at any time in mid-session.
2964 2977
2965 2978 2002-04-24 Fernando Perez <fperez@colorado.edu>
2966 2979
2967 2980 * IPython/numutils.py: removed SIUnits. It doesn't properly set
2968 2981 the globals (IPython has its own namespace) and the
2969 2982 PhysicalQuantity stuff is much better anyway.
2970 2983
2971 2984 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
2972 2985 embedding example to standard user directory for
2973 2986 distribution. Also put it in the manual.
2974 2987
2975 2988 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
2976 2989 instance as first argument (so it doesn't rely on some obscure
2977 2990 hidden global).
2978 2991
2979 2992 * IPython/UserConfig/ipythonrc.py: put () back in accepted
2980 2993 delimiters. While it prevents ().TAB from working, it allows
2981 2994 completions in open (... expressions. This is by far a more common
2982 2995 case.
2983 2996
2984 2997 2002-04-23 Fernando Perez <fperez@colorado.edu>
2985 2998
2986 2999 * IPython/Extensions/InterpreterPasteInput.py: new
2987 3000 syntax-processing module for pasting lines with >>> or ... at the
2988 3001 start.
2989 3002
2990 3003 * IPython/Extensions/PhysicalQ_Interactive.py
2991 3004 (PhysicalQuantityInteractive.__int__): fixed to work with either
2992 3005 Numeric or math.
2993 3006
2994 3007 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
2995 3008 provided profiles. Now we have:
2996 3009 -math -> math module as * and cmath with its own namespace.
2997 3010 -numeric -> Numeric as *, plus gnuplot & grace
2998 3011 -physics -> same as before
2999 3012
3000 3013 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3001 3014 user-defined magics wouldn't be found by @magic if they were
3002 3015 defined as class methods. Also cleaned up the namespace search
3003 3016 logic and the string building (to use %s instead of many repeated
3004 3017 string adds).
3005 3018
3006 3019 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3007 3020 of user-defined magics to operate with class methods (cleaner, in
3008 3021 line with the gnuplot code).
3009 3022
3010 3023 2002-04-22 Fernando Perez <fperez@colorado.edu>
3011 3024
3012 3025 * setup.py: updated dependency list so that manual is updated when
3013 3026 all included files change.
3014 3027
3015 3028 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3016 3029 the delimiter removal option (the fix is ugly right now).
3017 3030
3018 3031 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3019 3032 all of the math profile (quicker loading, no conflict between
3020 3033 g-9.8 and g-gnuplot).
3021 3034
3022 3035 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3023 3036 name of post-mortem files to IPython_crash_report.txt.
3024 3037
3025 3038 * Cleanup/update of the docs. Added all the new readline info and
3026 3039 formatted all lists as 'real lists'.
3027 3040
3028 3041 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3029 3042 tab-completion options, since the full readline parse_and_bind is
3030 3043 now accessible.
3031 3044
3032 3045 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3033 3046 handling of readline options. Now users can specify any string to
3034 3047 be passed to parse_and_bind(), as well as the delimiters to be
3035 3048 removed.
3036 3049 (InteractiveShell.__init__): Added __name__ to the global
3037 3050 namespace so that things like Itpl which rely on its existence
3038 3051 don't crash.
3039 3052 (InteractiveShell._prefilter): Defined the default with a _ so
3040 3053 that prefilter() is easier to override, while the default one
3041 3054 remains available.
3042 3055
3043 3056 2002-04-18 Fernando Perez <fperez@colorado.edu>
3044 3057
3045 3058 * Added information about pdb in the docs.
3046 3059
3047 3060 2002-04-17 Fernando Perez <fperez@colorado.edu>
3048 3061
3049 3062 * IPython/ipmaker.py (make_IPython): added rc_override option to
3050 3063 allow passing config options at creation time which may override
3051 3064 anything set in the config files or command line. This is
3052 3065 particularly useful for configuring embedded instances.
3053 3066
3054 3067 2002-04-15 Fernando Perez <fperez@colorado.edu>
3055 3068
3056 3069 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3057 3070 crash embedded instances because of the input cache falling out of
3058 3071 sync with the output counter.
3059 3072
3060 3073 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3061 3074 mode which calls pdb after an uncaught exception in IPython itself.
3062 3075
3063 3076 2002-04-14 Fernando Perez <fperez@colorado.edu>
3064 3077
3065 3078 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3066 3079 readline, fix it back after each call.
3067 3080
3068 3081 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3069 3082 method to force all access via __call__(), which guarantees that
3070 3083 traceback references are properly deleted.
3071 3084
3072 3085 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3073 3086 improve printing when pprint is in use.
3074 3087
3075 3088 2002-04-13 Fernando Perez <fperez@colorado.edu>
3076 3089
3077 3090 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3078 3091 exceptions aren't caught anymore. If the user triggers one, he
3079 3092 should know why he's doing it and it should go all the way up,
3080 3093 just like any other exception. So now @abort will fully kill the
3081 3094 embedded interpreter and the embedding code (unless that happens
3082 3095 to catch SystemExit).
3083 3096
3084 3097 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3085 3098 and a debugger() method to invoke the interactive pdb debugger
3086 3099 after printing exception information. Also added the corresponding
3087 3100 -pdb option and @pdb magic to control this feature, and updated
3088 3101 the docs. After a suggestion from Christopher Hart
3089 3102 (hart-AT-caltech.edu).
3090 3103
3091 3104 2002-04-12 Fernando Perez <fperez@colorado.edu>
3092 3105
3093 3106 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3094 3107 the exception handlers defined by the user (not the CrashHandler)
3095 3108 so that user exceptions don't trigger an ipython bug report.
3096 3109
3097 3110 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3098 3111 configurable (it should have always been so).
3099 3112
3100 3113 2002-03-26 Fernando Perez <fperez@colorado.edu>
3101 3114
3102 3115 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3103 3116 and there to fix embedding namespace issues. This should all be
3104 3117 done in a more elegant way.
3105 3118
3106 3119 2002-03-25 Fernando Perez <fperez@colorado.edu>
3107 3120
3108 3121 * IPython/genutils.py (get_home_dir): Try to make it work under
3109 3122 win9x also.
3110 3123
3111 3124 2002-03-20 Fernando Perez <fperez@colorado.edu>
3112 3125
3113 3126 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3114 3127 sys.displayhook untouched upon __init__.
3115 3128
3116 3129 2002-03-19 Fernando Perez <fperez@colorado.edu>
3117 3130
3118 3131 * Released 0.2.9 (for embedding bug, basically).
3119 3132
3120 3133 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3121 3134 exceptions so that enclosing shell's state can be restored.
3122 3135
3123 3136 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3124 3137 naming conventions in the .ipython/ dir.
3125 3138
3126 3139 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3127 3140 from delimiters list so filenames with - in them get expanded.
3128 3141
3129 3142 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3130 3143 sys.displayhook not being properly restored after an embedded call.
3131 3144
3132 3145 2002-03-18 Fernando Perez <fperez@colorado.edu>
3133 3146
3134 3147 * Released 0.2.8
3135 3148
3136 3149 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3137 3150 some files weren't being included in a -upgrade.
3138 3151 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3139 3152 on' so that the first tab completes.
3140 3153 (InteractiveShell.handle_magic): fixed bug with spaces around
3141 3154 quotes breaking many magic commands.
3142 3155
3143 3156 * setup.py: added note about ignoring the syntax error messages at
3144 3157 installation.
3145 3158
3146 3159 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3147 3160 streamlining the gnuplot interface, now there's only one magic @gp.
3148 3161
3149 3162 2002-03-17 Fernando Perez <fperez@colorado.edu>
3150 3163
3151 3164 * IPython/UserConfig/magic_gnuplot.py: new name for the
3152 3165 example-magic_pm.py file. Much enhanced system, now with a shell
3153 3166 for communicating directly with gnuplot, one command at a time.
3154 3167
3155 3168 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3156 3169 setting __name__=='__main__'.
3157 3170
3158 3171 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3159 3172 mini-shell for accessing gnuplot from inside ipython. Should
3160 3173 extend it later for grace access too. Inspired by Arnd's
3161 3174 suggestion.
3162 3175
3163 3176 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3164 3177 calling magic functions with () in their arguments. Thanks to Arnd
3165 3178 Baecker for pointing this to me.
3166 3179
3167 3180 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3168 3181 infinitely for integer or complex arrays (only worked with floats).
3169 3182
3170 3183 2002-03-16 Fernando Perez <fperez@colorado.edu>
3171 3184
3172 3185 * setup.py: Merged setup and setup_windows into a single script
3173 3186 which properly handles things for windows users.
3174 3187
3175 3188 2002-03-15 Fernando Perez <fperez@colorado.edu>
3176 3189
3177 3190 * Big change to the manual: now the magics are all automatically
3178 3191 documented. This information is generated from their docstrings
3179 3192 and put in a latex file included by the manual lyx file. This way
3180 3193 we get always up to date information for the magics. The manual
3181 3194 now also has proper version information, also auto-synced.
3182 3195
3183 3196 For this to work, an undocumented --magic_docstrings option was added.
3184 3197
3185 3198 2002-03-13 Fernando Perez <fperez@colorado.edu>
3186 3199
3187 3200 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3188 3201 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3189 3202
3190 3203 2002-03-12 Fernando Perez <fperez@colorado.edu>
3191 3204
3192 3205 * IPython/ultraTB.py (TermColors): changed color escapes again to
3193 3206 fix the (old, reintroduced) line-wrapping bug. Basically, if
3194 3207 \001..\002 aren't given in the color escapes, lines get wrapped
3195 3208 weirdly. But giving those screws up old xterms and emacs terms. So
3196 3209 I added some logic for emacs terms to be ok, but I can't identify old
3197 3210 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3198 3211
3199 3212 2002-03-10 Fernando Perez <fperez@colorado.edu>
3200 3213
3201 3214 * IPython/usage.py (__doc__): Various documentation cleanups and
3202 3215 updates, both in usage docstrings and in the manual.
3203 3216
3204 3217 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3205 3218 handling of caching. Set minimum acceptabe value for having a
3206 3219 cache at 20 values.
3207 3220
3208 3221 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3209 3222 install_first_time function to a method, renamed it and added an
3210 3223 'upgrade' mode. Now people can update their config directory with
3211 3224 a simple command line switch (-upgrade, also new).
3212 3225
3213 3226 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3214 3227 @file (convenient for automagic users under Python >= 2.2).
3215 3228 Removed @files (it seemed more like a plural than an abbrev. of
3216 3229 'file show').
3217 3230
3218 3231 * IPython/iplib.py (install_first_time): Fixed crash if there were
3219 3232 backup files ('~') in .ipython/ install directory.
3220 3233
3221 3234 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3222 3235 system. Things look fine, but these changes are fairly
3223 3236 intrusive. Test them for a few days.
3224 3237
3225 3238 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3226 3239 the prompts system. Now all in/out prompt strings are user
3227 3240 controllable. This is particularly useful for embedding, as one
3228 3241 can tag embedded instances with particular prompts.
3229 3242
3230 3243 Also removed global use of sys.ps1/2, which now allows nested
3231 3244 embeddings without any problems. Added command-line options for
3232 3245 the prompt strings.
3233 3246
3234 3247 2002-03-08 Fernando Perez <fperez@colorado.edu>
3235 3248
3236 3249 * IPython/UserConfig/example-embed-short.py (ipshell): added
3237 3250 example file with the bare minimum code for embedding.
3238 3251
3239 3252 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3240 3253 functionality for the embeddable shell to be activated/deactivated
3241 3254 either globally or at each call.
3242 3255
3243 3256 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3244 3257 rewriting the prompt with '--->' for auto-inputs with proper
3245 3258 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3246 3259 this is handled by the prompts class itself, as it should.
3247 3260
3248 3261 2002-03-05 Fernando Perez <fperez@colorado.edu>
3249 3262
3250 3263 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3251 3264 @logstart to avoid name clashes with the math log function.
3252 3265
3253 3266 * Big updates to X/Emacs section of the manual.
3254 3267
3255 3268 * Removed ipython_emacs. Milan explained to me how to pass
3256 3269 arguments to ipython through Emacs. Some day I'm going to end up
3257 3270 learning some lisp...
3258 3271
3259 3272 2002-03-04 Fernando Perez <fperez@colorado.edu>
3260 3273
3261 3274 * IPython/ipython_emacs: Created script to be used as the
3262 3275 py-python-command Emacs variable so we can pass IPython
3263 3276 parameters. I can't figure out how to tell Emacs directly to pass
3264 3277 parameters to IPython, so a dummy shell script will do it.
3265 3278
3266 3279 Other enhancements made for things to work better under Emacs'
3267 3280 various types of terminals. Many thanks to Milan Zamazal
3268 3281 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3269 3282
3270 3283 2002-03-01 Fernando Perez <fperez@colorado.edu>
3271 3284
3272 3285 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3273 3286 that loading of readline is now optional. This gives better
3274 3287 control to emacs users.
3275 3288
3276 3289 * IPython/ultraTB.py (__date__): Modified color escape sequences
3277 3290 and now things work fine under xterm and in Emacs' term buffers
3278 3291 (though not shell ones). Well, in emacs you get colors, but all
3279 3292 seem to be 'light' colors (no difference between dark and light
3280 3293 ones). But the garbage chars are gone, and also in xterms. It
3281 3294 seems that now I'm using 'cleaner' ansi sequences.
3282 3295
3283 3296 2002-02-21 Fernando Perez <fperez@colorado.edu>
3284 3297
3285 3298 * Released 0.2.7 (mainly to publish the scoping fix).
3286 3299
3287 3300 * IPython/Logger.py (Logger.logstate): added. A corresponding
3288 3301 @logstate magic was created.
3289 3302
3290 3303 * IPython/Magic.py: fixed nested scoping problem under Python
3291 3304 2.1.x (automagic wasn't working).
3292 3305
3293 3306 2002-02-20 Fernando Perez <fperez@colorado.edu>
3294 3307
3295 3308 * Released 0.2.6.
3296 3309
3297 3310 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3298 3311 option so that logs can come out without any headers at all.
3299 3312
3300 3313 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3301 3314 SciPy.
3302 3315
3303 3316 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3304 3317 that embedded IPython calls don't require vars() to be explicitly
3305 3318 passed. Now they are extracted from the caller's frame (code
3306 3319 snatched from Eric Jones' weave). Added better documentation to
3307 3320 the section on embedding and the example file.
3308 3321
3309 3322 * IPython/genutils.py (page): Changed so that under emacs, it just
3310 3323 prints the string. You can then page up and down in the emacs
3311 3324 buffer itself. This is how the builtin help() works.
3312 3325
3313 3326 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3314 3327 macro scoping: macros need to be executed in the user's namespace
3315 3328 to work as if they had been typed by the user.
3316 3329
3317 3330 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3318 3331 execute automatically (no need to type 'exec...'). They then
3319 3332 behave like 'true macros'. The printing system was also modified
3320 3333 for this to work.
3321 3334
3322 3335 2002-02-19 Fernando Perez <fperez@colorado.edu>
3323 3336
3324 3337 * IPython/genutils.py (page_file): new function for paging files
3325 3338 in an OS-independent way. Also necessary for file viewing to work
3326 3339 well inside Emacs buffers.
3327 3340 (page): Added checks for being in an emacs buffer.
3328 3341 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3329 3342 same bug in iplib.
3330 3343
3331 3344 2002-02-18 Fernando Perez <fperez@colorado.edu>
3332 3345
3333 3346 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3334 3347 of readline so that IPython can work inside an Emacs buffer.
3335 3348
3336 3349 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3337 3350 method signatures (they weren't really bugs, but it looks cleaner
3338 3351 and keeps PyChecker happy).
3339 3352
3340 3353 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3341 3354 for implementing various user-defined hooks. Currently only
3342 3355 display is done.
3343 3356
3344 3357 * IPython/Prompts.py (CachedOutput._display): changed display
3345 3358 functions so that they can be dynamically changed by users easily.
3346 3359
3347 3360 * IPython/Extensions/numeric_formats.py (num_display): added an
3348 3361 extension for printing NumPy arrays in flexible manners. It
3349 3362 doesn't do anything yet, but all the structure is in
3350 3363 place. Ultimately the plan is to implement output format control
3351 3364 like in Octave.
3352 3365
3353 3366 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3354 3367 methods are found at run-time by all the automatic machinery.
3355 3368
3356 3369 2002-02-17 Fernando Perez <fperez@colorado.edu>
3357 3370
3358 3371 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3359 3372 whole file a little.
3360 3373
3361 3374 * ToDo: closed this document. Now there's a new_design.lyx
3362 3375 document for all new ideas. Added making a pdf of it for the
3363 3376 end-user distro.
3364 3377
3365 3378 * IPython/Logger.py (Logger.switch_log): Created this to replace
3366 3379 logon() and logoff(). It also fixes a nasty crash reported by
3367 3380 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3368 3381
3369 3382 * IPython/iplib.py (complete): got auto-completion to work with
3370 3383 automagic (I had wanted this for a long time).
3371 3384
3372 3385 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3373 3386 to @file, since file() is now a builtin and clashes with automagic
3374 3387 for @file.
3375 3388
3376 3389 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3377 3390 of this was previously in iplib, which had grown to more than 2000
3378 3391 lines, way too long. No new functionality, but it makes managing
3379 3392 the code a bit easier.
3380 3393
3381 3394 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3382 3395 information to crash reports.
3383 3396
3384 3397 2002-02-12 Fernando Perez <fperez@colorado.edu>
3385 3398
3386 3399 * Released 0.2.5.
3387 3400
3388 3401 2002-02-11 Fernando Perez <fperez@colorado.edu>
3389 3402
3390 3403 * Wrote a relatively complete Windows installer. It puts
3391 3404 everything in place, creates Start Menu entries and fixes the
3392 3405 color issues. Nothing fancy, but it works.
3393 3406
3394 3407 2002-02-10 Fernando Perez <fperez@colorado.edu>
3395 3408
3396 3409 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3397 3410 os.path.expanduser() call so that we can type @run ~/myfile.py and
3398 3411 have thigs work as expected.
3399 3412
3400 3413 * IPython/genutils.py (page): fixed exception handling so things
3401 3414 work both in Unix and Windows correctly. Quitting a pager triggers
3402 3415 an IOError/broken pipe in Unix, and in windows not finding a pager
3403 3416 is also an IOError, so I had to actually look at the return value
3404 3417 of the exception, not just the exception itself. Should be ok now.
3405 3418
3406 3419 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3407 3420 modified to allow case-insensitive color scheme changes.
3408 3421
3409 3422 2002-02-09 Fernando Perez <fperez@colorado.edu>
3410 3423
3411 3424 * IPython/genutils.py (native_line_ends): new function to leave
3412 3425 user config files with os-native line-endings.
3413 3426
3414 3427 * README and manual updates.
3415 3428
3416 3429 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3417 3430 instead of StringType to catch Unicode strings.
3418 3431
3419 3432 * IPython/genutils.py (filefind): fixed bug for paths with
3420 3433 embedded spaces (very common in Windows).
3421 3434
3422 3435 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3423 3436 files under Windows, so that they get automatically associated
3424 3437 with a text editor. Windows makes it a pain to handle
3425 3438 extension-less files.
3426 3439
3427 3440 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3428 3441 warning about readline only occur for Posix. In Windows there's no
3429 3442 way to get readline, so why bother with the warning.
3430 3443
3431 3444 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3432 3445 for __str__ instead of dir(self), since dir() changed in 2.2.
3433 3446
3434 3447 * Ported to Windows! Tested on XP, I suspect it should work fine
3435 3448 on NT/2000, but I don't think it will work on 98 et al. That
3436 3449 series of Windows is such a piece of junk anyway that I won't try
3437 3450 porting it there. The XP port was straightforward, showed a few
3438 3451 bugs here and there (fixed all), in particular some string
3439 3452 handling stuff which required considering Unicode strings (which
3440 3453 Windows uses). This is good, but hasn't been too tested :) No
3441 3454 fancy installer yet, I'll put a note in the manual so people at
3442 3455 least make manually a shortcut.
3443 3456
3444 3457 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3445 3458 into a single one, "colors". This now controls both prompt and
3446 3459 exception color schemes, and can be changed both at startup
3447 3460 (either via command-line switches or via ipythonrc files) and at
3448 3461 runtime, with @colors.
3449 3462 (Magic.magic_run): renamed @prun to @run and removed the old
3450 3463 @run. The two were too similar to warrant keeping both.
3451 3464
3452 3465 2002-02-03 Fernando Perez <fperez@colorado.edu>
3453 3466
3454 3467 * IPython/iplib.py (install_first_time): Added comment on how to
3455 3468 configure the color options for first-time users. Put a <return>
3456 3469 request at the end so that small-terminal users get a chance to
3457 3470 read the startup info.
3458 3471
3459 3472 2002-01-23 Fernando Perez <fperez@colorado.edu>
3460 3473
3461 3474 * IPython/iplib.py (CachedOutput.update): Changed output memory
3462 3475 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3463 3476 input history we still use _i. Did this b/c these variable are
3464 3477 very commonly used in interactive work, so the less we need to
3465 3478 type the better off we are.
3466 3479 (Magic.magic_prun): updated @prun to better handle the namespaces
3467 3480 the file will run in, including a fix for __name__ not being set
3468 3481 before.
3469 3482
3470 3483 2002-01-20 Fernando Perez <fperez@colorado.edu>
3471 3484
3472 3485 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3473 3486 extra garbage for Python 2.2. Need to look more carefully into
3474 3487 this later.
3475 3488
3476 3489 2002-01-19 Fernando Perez <fperez@colorado.edu>
3477 3490
3478 3491 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3479 3492 display SyntaxError exceptions properly formatted when they occur
3480 3493 (they can be triggered by imported code).
3481 3494
3482 3495 2002-01-18 Fernando Perez <fperez@colorado.edu>
3483 3496
3484 3497 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3485 3498 SyntaxError exceptions are reported nicely formatted, instead of
3486 3499 spitting out only offset information as before.
3487 3500 (Magic.magic_prun): Added the @prun function for executing
3488 3501 programs with command line args inside IPython.
3489 3502
3490 3503 2002-01-16 Fernando Perez <fperez@colorado.edu>
3491 3504
3492 3505 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3493 3506 to *not* include the last item given in a range. This brings their
3494 3507 behavior in line with Python's slicing:
3495 3508 a[n1:n2] -> a[n1]...a[n2-1]
3496 3509 It may be a bit less convenient, but I prefer to stick to Python's
3497 3510 conventions *everywhere*, so users never have to wonder.
3498 3511 (Magic.magic_macro): Added @macro function to ease the creation of
3499 3512 macros.
3500 3513
3501 3514 2002-01-05 Fernando Perez <fperez@colorado.edu>
3502 3515
3503 3516 * Released 0.2.4.
3504 3517
3505 3518 * IPython/iplib.py (Magic.magic_pdef):
3506 3519 (InteractiveShell.safe_execfile): report magic lines and error
3507 3520 lines without line numbers so one can easily copy/paste them for
3508 3521 re-execution.
3509 3522
3510 3523 * Updated manual with recent changes.
3511 3524
3512 3525 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3513 3526 docstring printing when class? is called. Very handy for knowing
3514 3527 how to create class instances (as long as __init__ is well
3515 3528 documented, of course :)
3516 3529 (Magic.magic_doc): print both class and constructor docstrings.
3517 3530 (Magic.magic_pdef): give constructor info if passed a class and
3518 3531 __call__ info for callable object instances.
3519 3532
3520 3533 2002-01-04 Fernando Perez <fperez@colorado.edu>
3521 3534
3522 3535 * Made deep_reload() off by default. It doesn't always work
3523 3536 exactly as intended, so it's probably safer to have it off. It's
3524 3537 still available as dreload() anyway, so nothing is lost.
3525 3538
3526 3539 2002-01-02 Fernando Perez <fperez@colorado.edu>
3527 3540
3528 3541 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3529 3542 so I wanted an updated release).
3530 3543
3531 3544 2001-12-27 Fernando Perez <fperez@colorado.edu>
3532 3545
3533 3546 * IPython/iplib.py (InteractiveShell.interact): Added the original
3534 3547 code from 'code.py' for this module in order to change the
3535 3548 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3536 3549 the history cache would break when the user hit Ctrl-C, and
3537 3550 interact() offers no way to add any hooks to it.
3538 3551
3539 3552 2001-12-23 Fernando Perez <fperez@colorado.edu>
3540 3553
3541 3554 * setup.py: added check for 'MANIFEST' before trying to remove
3542 3555 it. Thanks to Sean Reifschneider.
3543 3556
3544 3557 2001-12-22 Fernando Perez <fperez@colorado.edu>
3545 3558
3546 3559 * Released 0.2.2.
3547 3560
3548 3561 * Finished (reasonably) writing the manual. Later will add the
3549 3562 python-standard navigation stylesheets, but for the time being
3550 3563 it's fairly complete. Distribution will include html and pdf
3551 3564 versions.
3552 3565
3553 3566 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3554 3567 (MayaVi author).
3555 3568
3556 3569 2001-12-21 Fernando Perez <fperez@colorado.edu>
3557 3570
3558 3571 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3559 3572 good public release, I think (with the manual and the distutils
3560 3573 installer). The manual can use some work, but that can go
3561 3574 slowly. Otherwise I think it's quite nice for end users. Next
3562 3575 summer, rewrite the guts of it...
3563 3576
3564 3577 * Changed format of ipythonrc files to use whitespace as the
3565 3578 separator instead of an explicit '='. Cleaner.
3566 3579
3567 3580 2001-12-20 Fernando Perez <fperez@colorado.edu>
3568 3581
3569 3582 * Started a manual in LyX. For now it's just a quick merge of the
3570 3583 various internal docstrings and READMEs. Later it may grow into a
3571 3584 nice, full-blown manual.
3572 3585
3573 3586 * Set up a distutils based installer. Installation should now be
3574 3587 trivially simple for end-users.
3575 3588
3576 3589 2001-12-11 Fernando Perez <fperez@colorado.edu>
3577 3590
3578 3591 * Released 0.2.0. First public release, announced it at
3579 3592 comp.lang.python. From now on, just bugfixes...
3580 3593
3581 3594 * Went through all the files, set copyright/license notices and
3582 3595 cleaned up things. Ready for release.
3583 3596
3584 3597 2001-12-10 Fernando Perez <fperez@colorado.edu>
3585 3598
3586 3599 * Changed the first-time installer not to use tarfiles. It's more
3587 3600 robust now and less unix-dependent. Also makes it easier for
3588 3601 people to later upgrade versions.
3589 3602
3590 3603 * Changed @exit to @abort to reflect the fact that it's pretty
3591 3604 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3592 3605 becomes significant only when IPyhton is embedded: in that case,
3593 3606 C-D closes IPython only, but @abort kills the enclosing program
3594 3607 too (unless it had called IPython inside a try catching
3595 3608 SystemExit).
3596 3609
3597 3610 * Created Shell module which exposes the actuall IPython Shell
3598 3611 classes, currently the normal and the embeddable one. This at
3599 3612 least offers a stable interface we won't need to change when
3600 3613 (later) the internals are rewritten. That rewrite will be confined
3601 3614 to iplib and ipmaker, but the Shell interface should remain as is.
3602 3615
3603 3616 * Added embed module which offers an embeddable IPShell object,
3604 3617 useful to fire up IPython *inside* a running program. Great for
3605 3618 debugging or dynamical data analysis.
3606 3619
3607 3620 2001-12-08 Fernando Perez <fperez@colorado.edu>
3608 3621
3609 3622 * Fixed small bug preventing seeing info from methods of defined
3610 3623 objects (incorrect namespace in _ofind()).
3611 3624
3612 3625 * Documentation cleanup. Moved the main usage docstrings to a
3613 3626 separate file, usage.py (cleaner to maintain, and hopefully in the
3614 3627 future some perlpod-like way of producing interactive, man and
3615 3628 html docs out of it will be found).
3616 3629
3617 3630 * Added @profile to see your profile at any time.
3618 3631
3619 3632 * Added @p as an alias for 'print'. It's especially convenient if
3620 3633 using automagic ('p x' prints x).
3621 3634
3622 3635 * Small cleanups and fixes after a pychecker run.
3623 3636
3624 3637 * Changed the @cd command to handle @cd - and @cd -<n> for
3625 3638 visiting any directory in _dh.
3626 3639
3627 3640 * Introduced _dh, a history of visited directories. @dhist prints
3628 3641 it out with numbers.
3629 3642
3630 3643 2001-12-07 Fernando Perez <fperez@colorado.edu>
3631 3644
3632 3645 * Released 0.1.22
3633 3646
3634 3647 * Made initialization a bit more robust against invalid color
3635 3648 options in user input (exit, not traceback-crash).
3636 3649
3637 3650 * Changed the bug crash reporter to write the report only in the
3638 3651 user's .ipython directory. That way IPython won't litter people's
3639 3652 hard disks with crash files all over the place. Also print on
3640 3653 screen the necessary mail command.
3641 3654
3642 3655 * With the new ultraTB, implemented LightBG color scheme for light
3643 3656 background terminals. A lot of people like white backgrounds, so I
3644 3657 guess we should at least give them something readable.
3645 3658
3646 3659 2001-12-06 Fernando Perez <fperez@colorado.edu>
3647 3660
3648 3661 * Modified the structure of ultraTB. Now there's a proper class
3649 3662 for tables of color schemes which allow adding schemes easily and
3650 3663 switching the active scheme without creating a new instance every
3651 3664 time (which was ridiculous). The syntax for creating new schemes
3652 3665 is also cleaner. I think ultraTB is finally done, with a clean
3653 3666 class structure. Names are also much cleaner (now there's proper
3654 3667 color tables, no need for every variable to also have 'color' in
3655 3668 its name).
3656 3669
3657 3670 * Broke down genutils into separate files. Now genutils only
3658 3671 contains utility functions, and classes have been moved to their
3659 3672 own files (they had enough independent functionality to warrant
3660 3673 it): ConfigLoader, OutputTrap, Struct.
3661 3674
3662 3675 2001-12-05 Fernando Perez <fperez@colorado.edu>
3663 3676
3664 3677 * IPython turns 21! Released version 0.1.21, as a candidate for
3665 3678 public consumption. If all goes well, release in a few days.
3666 3679
3667 3680 * Fixed path bug (files in Extensions/ directory wouldn't be found
3668 3681 unless IPython/ was explicitly in sys.path).
3669 3682
3670 3683 * Extended the FlexCompleter class as MagicCompleter to allow
3671 3684 completion of @-starting lines.
3672 3685
3673 3686 * Created __release__.py file as a central repository for release
3674 3687 info that other files can read from.
3675 3688
3676 3689 * Fixed small bug in logging: when logging was turned on in
3677 3690 mid-session, old lines with special meanings (!@?) were being
3678 3691 logged without the prepended comment, which is necessary since
3679 3692 they are not truly valid python syntax. This should make session
3680 3693 restores produce less errors.
3681 3694
3682 3695 * The namespace cleanup forced me to make a FlexCompleter class
3683 3696 which is nothing but a ripoff of rlcompleter, but with selectable
3684 3697 namespace (rlcompleter only works in __main__.__dict__). I'll try
3685 3698 to submit a note to the authors to see if this change can be
3686 3699 incorporated in future rlcompleter releases (Dec.6: done)
3687 3700
3688 3701 * More fixes to namespace handling. It was a mess! Now all
3689 3702 explicit references to __main__.__dict__ are gone (except when
3690 3703 really needed) and everything is handled through the namespace
3691 3704 dicts in the IPython instance. We seem to be getting somewhere
3692 3705 with this, finally...
3693 3706
3694 3707 * Small documentation updates.
3695 3708
3696 3709 * Created the Extensions directory under IPython (with an
3697 3710 __init__.py). Put the PhysicalQ stuff there. This directory should
3698 3711 be used for all special-purpose extensions.
3699 3712
3700 3713 * File renaming:
3701 3714 ipythonlib --> ipmaker
3702 3715 ipplib --> iplib
3703 3716 This makes a bit more sense in terms of what these files actually do.
3704 3717
3705 3718 * Moved all the classes and functions in ipythonlib to ipplib, so
3706 3719 now ipythonlib only has make_IPython(). This will ease up its
3707 3720 splitting in smaller functional chunks later.
3708 3721
3709 3722 * Cleaned up (done, I think) output of @whos. Better column
3710 3723 formatting, and now shows str(var) for as much as it can, which is
3711 3724 typically what one gets with a 'print var'.
3712 3725
3713 3726 2001-12-04 Fernando Perez <fperez@colorado.edu>
3714 3727
3715 3728 * Fixed namespace problems. Now builtin/IPyhton/user names get
3716 3729 properly reported in their namespace. Internal namespace handling
3717 3730 is finally getting decent (not perfect yet, but much better than
3718 3731 the ad-hoc mess we had).
3719 3732
3720 3733 * Removed -exit option. If people just want to run a python
3721 3734 script, that's what the normal interpreter is for. Less
3722 3735 unnecessary options, less chances for bugs.
3723 3736
3724 3737 * Added a crash handler which generates a complete post-mortem if
3725 3738 IPython crashes. This will help a lot in tracking bugs down the
3726 3739 road.
3727 3740
3728 3741 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
3729 3742 which were boud to functions being reassigned would bypass the
3730 3743 logger, breaking the sync of _il with the prompt counter. This
3731 3744 would then crash IPython later when a new line was logged.
3732 3745
3733 3746 2001-12-02 Fernando Perez <fperez@colorado.edu>
3734 3747
3735 3748 * Made IPython a package. This means people don't have to clutter
3736 3749 their sys.path with yet another directory. Changed the INSTALL
3737 3750 file accordingly.
3738 3751
3739 3752 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
3740 3753 sorts its output (so @who shows it sorted) and @whos formats the
3741 3754 table according to the width of the first column. Nicer, easier to
3742 3755 read. Todo: write a generic table_format() which takes a list of
3743 3756 lists and prints it nicely formatted, with optional row/column
3744 3757 separators and proper padding and justification.
3745 3758
3746 3759 * Released 0.1.20
3747 3760
3748 3761 * Fixed bug in @log which would reverse the inputcache list (a
3749 3762 copy operation was missing).
3750 3763
3751 3764 * Code cleanup. @config was changed to use page(). Better, since
3752 3765 its output is always quite long.
3753 3766
3754 3767 * Itpl is back as a dependency. I was having too many problems
3755 3768 getting the parametric aliases to work reliably, and it's just
3756 3769 easier to code weird string operations with it than playing %()s
3757 3770 games. It's only ~6k, so I don't think it's too big a deal.
3758 3771
3759 3772 * Found (and fixed) a very nasty bug with history. !lines weren't
3760 3773 getting cached, and the out of sync caches would crash
3761 3774 IPython. Fixed it by reorganizing the prefilter/handlers/logger
3762 3775 division of labor a bit better. Bug fixed, cleaner structure.
3763 3776
3764 3777 2001-12-01 Fernando Perez <fperez@colorado.edu>
3765 3778
3766 3779 * Released 0.1.19
3767 3780
3768 3781 * Added option -n to @hist to prevent line number printing. Much
3769 3782 easier to copy/paste code this way.
3770 3783
3771 3784 * Created global _il to hold the input list. Allows easy
3772 3785 re-execution of blocks of code by slicing it (inspired by Janko's
3773 3786 comment on 'macros').
3774 3787
3775 3788 * Small fixes and doc updates.
3776 3789
3777 3790 * Rewrote @history function (was @h). Renamed it to @hist, @h is
3778 3791 much too fragile with automagic. Handles properly multi-line
3779 3792 statements and takes parameters.
3780 3793
3781 3794 2001-11-30 Fernando Perez <fperez@colorado.edu>
3782 3795
3783 3796 * Version 0.1.18 released.
3784 3797
3785 3798 * Fixed nasty namespace bug in initial module imports.
3786 3799
3787 3800 * Added copyright/license notes to all code files (except
3788 3801 DPyGetOpt). For the time being, LGPL. That could change.
3789 3802
3790 3803 * Rewrote a much nicer README, updated INSTALL, cleaned up
3791 3804 ipythonrc-* samples.
3792 3805
3793 3806 * Overall code/documentation cleanup. Basically ready for
3794 3807 release. Only remaining thing: licence decision (LGPL?).
3795 3808
3796 3809 * Converted load_config to a class, ConfigLoader. Now recursion
3797 3810 control is better organized. Doesn't include the same file twice.
3798 3811
3799 3812 2001-11-29 Fernando Perez <fperez@colorado.edu>
3800 3813
3801 3814 * Got input history working. Changed output history variables from
3802 3815 _p to _o so that _i is for input and _o for output. Just cleaner
3803 3816 convention.
3804 3817
3805 3818 * Implemented parametric aliases. This pretty much allows the
3806 3819 alias system to offer full-blown shell convenience, I think.
3807 3820
3808 3821 * Version 0.1.17 released, 0.1.18 opened.
3809 3822
3810 3823 * dot_ipython/ipythonrc (alias): added documentation.
3811 3824 (xcolor): Fixed small bug (xcolors -> xcolor)
3812 3825
3813 3826 * Changed the alias system. Now alias is a magic command to define
3814 3827 aliases just like the shell. Rationale: the builtin magics should
3815 3828 be there for things deeply connected to IPython's
3816 3829 architecture. And this is a much lighter system for what I think
3817 3830 is the really important feature: allowing users to define quickly
3818 3831 magics that will do shell things for them, so they can customize
3819 3832 IPython easily to match their work habits. If someone is really
3820 3833 desperate to have another name for a builtin alias, they can
3821 3834 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
3822 3835 works.
3823 3836
3824 3837 2001-11-28 Fernando Perez <fperez@colorado.edu>
3825 3838
3826 3839 * Changed @file so that it opens the source file at the proper
3827 3840 line. Since it uses less, if your EDITOR environment is
3828 3841 configured, typing v will immediately open your editor of choice
3829 3842 right at the line where the object is defined. Not as quick as
3830 3843 having a direct @edit command, but for all intents and purposes it
3831 3844 works. And I don't have to worry about writing @edit to deal with
3832 3845 all the editors, less does that.
3833 3846
3834 3847 * Version 0.1.16 released, 0.1.17 opened.
3835 3848
3836 3849 * Fixed some nasty bugs in the page/page_dumb combo that could
3837 3850 crash IPython.
3838 3851
3839 3852 2001-11-27 Fernando Perez <fperez@colorado.edu>
3840 3853
3841 3854 * Version 0.1.15 released, 0.1.16 opened.
3842 3855
3843 3856 * Finally got ? and ?? to work for undefined things: now it's
3844 3857 possible to type {}.get? and get information about the get method
3845 3858 of dicts, or os.path? even if only os is defined (so technically
3846 3859 os.path isn't). Works at any level. For example, after import os,
3847 3860 os?, os.path?, os.path.abspath? all work. This is great, took some
3848 3861 work in _ofind.
3849 3862
3850 3863 * Fixed more bugs with logging. The sanest way to do it was to add
3851 3864 to @log a 'mode' parameter. Killed two in one shot (this mode
3852 3865 option was a request of Janko's). I think it's finally clean
3853 3866 (famous last words).
3854 3867
3855 3868 * Added a page_dumb() pager which does a decent job of paging on
3856 3869 screen, if better things (like less) aren't available. One less
3857 3870 unix dependency (someday maybe somebody will port this to
3858 3871 windows).
3859 3872
3860 3873 * Fixed problem in magic_log: would lock of logging out if log
3861 3874 creation failed (because it would still think it had succeeded).
3862 3875
3863 3876 * Improved the page() function using curses to auto-detect screen
3864 3877 size. Now it can make a much better decision on whether to print
3865 3878 or page a string. Option screen_length was modified: a value 0
3866 3879 means auto-detect, and that's the default now.
3867 3880
3868 3881 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
3869 3882 go out. I'll test it for a few days, then talk to Janko about
3870 3883 licences and announce it.
3871 3884
3872 3885 * Fixed the length of the auto-generated ---> prompt which appears
3873 3886 for auto-parens and auto-quotes. Getting this right isn't trivial,
3874 3887 with all the color escapes, different prompt types and optional
3875 3888 separators. But it seems to be working in all the combinations.
3876 3889
3877 3890 2001-11-26 Fernando Perez <fperez@colorado.edu>
3878 3891
3879 3892 * Wrote a regexp filter to get option types from the option names
3880 3893 string. This eliminates the need to manually keep two duplicate
3881 3894 lists.
3882 3895
3883 3896 * Removed the unneeded check_option_names. Now options are handled
3884 3897 in a much saner manner and it's easy to visually check that things
3885 3898 are ok.
3886 3899
3887 3900 * Updated version numbers on all files I modified to carry a
3888 3901 notice so Janko and Nathan have clear version markers.
3889 3902
3890 3903 * Updated docstring for ultraTB with my changes. I should send
3891 3904 this to Nathan.
3892 3905
3893 3906 * Lots of small fixes. Ran everything through pychecker again.
3894 3907
3895 3908 * Made loading of deep_reload an cmd line option. If it's not too
3896 3909 kosher, now people can just disable it. With -nodeep_reload it's
3897 3910 still available as dreload(), it just won't overwrite reload().
3898 3911
3899 3912 * Moved many options to the no| form (-opt and -noopt
3900 3913 accepted). Cleaner.
3901 3914
3902 3915 * Changed magic_log so that if called with no parameters, it uses
3903 3916 'rotate' mode. That way auto-generated logs aren't automatically
3904 3917 over-written. For normal logs, now a backup is made if it exists
3905 3918 (only 1 level of backups). A new 'backup' mode was added to the
3906 3919 Logger class to support this. This was a request by Janko.
3907 3920
3908 3921 * Added @logoff/@logon to stop/restart an active log.
3909 3922
3910 3923 * Fixed a lot of bugs in log saving/replay. It was pretty
3911 3924 broken. Now special lines (!@,/) appear properly in the command
3912 3925 history after a log replay.
3913 3926
3914 3927 * Tried and failed to implement full session saving via pickle. My
3915 3928 idea was to pickle __main__.__dict__, but modules can't be
3916 3929 pickled. This would be a better alternative to replaying logs, but
3917 3930 seems quite tricky to get to work. Changed -session to be called
3918 3931 -logplay, which more accurately reflects what it does. And if we
3919 3932 ever get real session saving working, -session is now available.
3920 3933
3921 3934 * Implemented color schemes for prompts also. As for tracebacks,
3922 3935 currently only NoColor and Linux are supported. But now the
3923 3936 infrastructure is in place, based on a generic ColorScheme
3924 3937 class. So writing and activating new schemes both for the prompts
3925 3938 and the tracebacks should be straightforward.
3926 3939
3927 3940 * Version 0.1.13 released, 0.1.14 opened.
3928 3941
3929 3942 * Changed handling of options for output cache. Now counter is
3930 3943 hardwired starting at 1 and one specifies the maximum number of
3931 3944 entries *in the outcache* (not the max prompt counter). This is
3932 3945 much better, since many statements won't increase the cache
3933 3946 count. It also eliminated some confusing options, now there's only
3934 3947 one: cache_size.
3935 3948
3936 3949 * Added 'alias' magic function and magic_alias option in the
3937 3950 ipythonrc file. Now the user can easily define whatever names he
3938 3951 wants for the magic functions without having to play weird
3939 3952 namespace games. This gives IPython a real shell-like feel.
3940 3953
3941 3954 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
3942 3955 @ or not).
3943 3956
3944 3957 This was one of the last remaining 'visible' bugs (that I know
3945 3958 of). I think if I can clean up the session loading so it works
3946 3959 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
3947 3960 about licensing).
3948 3961
3949 3962 2001-11-25 Fernando Perez <fperez@colorado.edu>
3950 3963
3951 3964 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
3952 3965 there's a cleaner distinction between what ? and ?? show.
3953 3966
3954 3967 * Added screen_length option. Now the user can define his own
3955 3968 screen size for page() operations.
3956 3969
3957 3970 * Implemented magic shell-like functions with automatic code
3958 3971 generation. Now adding another function is just a matter of adding
3959 3972 an entry to a dict, and the function is dynamically generated at
3960 3973 run-time. Python has some really cool features!
3961 3974
3962 3975 * Renamed many options to cleanup conventions a little. Now all
3963 3976 are lowercase, and only underscores where needed. Also in the code
3964 3977 option name tables are clearer.
3965 3978
3966 3979 * Changed prompts a little. Now input is 'In [n]:' instead of
3967 3980 'In[n]:='. This allows it the numbers to be aligned with the
3968 3981 Out[n] numbers, and removes usage of ':=' which doesn't exist in
3969 3982 Python (it was a Mathematica thing). The '...' continuation prompt
3970 3983 was also changed a little to align better.
3971 3984
3972 3985 * Fixed bug when flushing output cache. Not all _p<n> variables
3973 3986 exist, so their deletion needs to be wrapped in a try:
3974 3987
3975 3988 * Figured out how to properly use inspect.formatargspec() (it
3976 3989 requires the args preceded by *). So I removed all the code from
3977 3990 _get_pdef in Magic, which was just replicating that.
3978 3991
3979 3992 * Added test to prefilter to allow redefining magic function names
3980 3993 as variables. This is ok, since the @ form is always available,
3981 3994 but whe should allow the user to define a variable called 'ls' if
3982 3995 he needs it.
3983 3996
3984 3997 * Moved the ToDo information from README into a separate ToDo.
3985 3998
3986 3999 * General code cleanup and small bugfixes. I think it's close to a
3987 4000 state where it can be released, obviously with a big 'beta'
3988 4001 warning on it.
3989 4002
3990 4003 * Got the magic function split to work. Now all magics are defined
3991 4004 in a separate class. It just organizes things a bit, and now
3992 4005 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
3993 4006 was too long).
3994 4007
3995 4008 * Changed @clear to @reset to avoid potential confusions with
3996 4009 the shell command clear. Also renamed @cl to @clear, which does
3997 4010 exactly what people expect it to from their shell experience.
3998 4011
3999 4012 Added a check to the @reset command (since it's so
4000 4013 destructive, it's probably a good idea to ask for confirmation).
4001 4014 But now reset only works for full namespace resetting. Since the
4002 4015 del keyword is already there for deleting a few specific
4003 4016 variables, I don't see the point of having a redundant magic
4004 4017 function for the same task.
4005 4018
4006 4019 2001-11-24 Fernando Perez <fperez@colorado.edu>
4007 4020
4008 4021 * Updated the builtin docs (esp. the ? ones).
4009 4022
4010 4023 * Ran all the code through pychecker. Not terribly impressed with
4011 4024 it: lots of spurious warnings and didn't really find anything of
4012 4025 substance (just a few modules being imported and not used).
4013 4026
4014 4027 * Implemented the new ultraTB functionality into IPython. New
4015 4028 option: xcolors. This chooses color scheme. xmode now only selects
4016 4029 between Plain and Verbose. Better orthogonality.
4017 4030
4018 4031 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4019 4032 mode and color scheme for the exception handlers. Now it's
4020 4033 possible to have the verbose traceback with no coloring.
4021 4034
4022 4035 2001-11-23 Fernando Perez <fperez@colorado.edu>
4023 4036
4024 4037 * Version 0.1.12 released, 0.1.13 opened.
4025 4038
4026 4039 * Removed option to set auto-quote and auto-paren escapes by
4027 4040 user. The chances of breaking valid syntax are just too high. If
4028 4041 someone *really* wants, they can always dig into the code.
4029 4042
4030 4043 * Made prompt separators configurable.
4031 4044
4032 4045 2001-11-22 Fernando Perez <fperez@colorado.edu>
4033 4046
4034 4047 * Small bugfixes in many places.
4035 4048
4036 4049 * Removed the MyCompleter class from ipplib. It seemed redundant
4037 4050 with the C-p,C-n history search functionality. Less code to
4038 4051 maintain.
4039 4052
4040 4053 * Moved all the original ipython.py code into ipythonlib.py. Right
4041 4054 now it's just one big dump into a function called make_IPython, so
4042 4055 no real modularity has been gained. But at least it makes the
4043 4056 wrapper script tiny, and since ipythonlib is a module, it gets
4044 4057 compiled and startup is much faster.
4045 4058
4046 4059 This is a reasobably 'deep' change, so we should test it for a
4047 4060 while without messing too much more with the code.
4048 4061
4049 4062 2001-11-21 Fernando Perez <fperez@colorado.edu>
4050 4063
4051 4064 * Version 0.1.11 released, 0.1.12 opened for further work.
4052 4065
4053 4066 * Removed dependency on Itpl. It was only needed in one place. It
4054 4067 would be nice if this became part of python, though. It makes life
4055 4068 *a lot* easier in some cases.
4056 4069
4057 4070 * Simplified the prefilter code a bit. Now all handlers are
4058 4071 expected to explicitly return a value (at least a blank string).
4059 4072
4060 4073 * Heavy edits in ipplib. Removed the help system altogether. Now
4061 4074 obj?/?? is used for inspecting objects, a magic @doc prints
4062 4075 docstrings, and full-blown Python help is accessed via the 'help'
4063 4076 keyword. This cleans up a lot of code (less to maintain) and does
4064 4077 the job. Since 'help' is now a standard Python component, might as
4065 4078 well use it and remove duplicate functionality.
4066 4079
4067 4080 Also removed the option to use ipplib as a standalone program. By
4068 4081 now it's too dependent on other parts of IPython to function alone.
4069 4082
4070 4083 * Fixed bug in genutils.pager. It would crash if the pager was
4071 4084 exited immediately after opening (broken pipe).
4072 4085
4073 4086 * Trimmed down the VerboseTB reporting a little. The header is
4074 4087 much shorter now and the repeated exception arguments at the end
4075 4088 have been removed. For interactive use the old header seemed a bit
4076 4089 excessive.
4077 4090
4078 4091 * Fixed small bug in output of @whos for variables with multi-word
4079 4092 types (only first word was displayed).
4080 4093
4081 4094 2001-11-17 Fernando Perez <fperez@colorado.edu>
4082 4095
4083 4096 * Version 0.1.10 released, 0.1.11 opened for further work.
4084 4097
4085 4098 * Modified dirs and friends. dirs now *returns* the stack (not
4086 4099 prints), so one can manipulate it as a variable. Convenient to
4087 4100 travel along many directories.
4088 4101
4089 4102 * Fixed bug in magic_pdef: would only work with functions with
4090 4103 arguments with default values.
4091 4104
4092 4105 2001-11-14 Fernando Perez <fperez@colorado.edu>
4093 4106
4094 4107 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4095 4108 example with IPython. Various other minor fixes and cleanups.
4096 4109
4097 4110 * Version 0.1.9 released, 0.1.10 opened for further work.
4098 4111
4099 4112 * Added sys.path to the list of directories searched in the
4100 4113 execfile= option. It used to be the current directory and the
4101 4114 user's IPYTHONDIR only.
4102 4115
4103 4116 2001-11-13 Fernando Perez <fperez@colorado.edu>
4104 4117
4105 4118 * Reinstated the raw_input/prefilter separation that Janko had
4106 4119 initially. This gives a more convenient setup for extending the
4107 4120 pre-processor from the outside: raw_input always gets a string,
4108 4121 and prefilter has to process it. We can then redefine prefilter
4109 4122 from the outside and implement extensions for special
4110 4123 purposes.
4111 4124
4112 4125 Today I got one for inputting PhysicalQuantity objects
4113 4126 (from Scientific) without needing any function calls at
4114 4127 all. Extremely convenient, and it's all done as a user-level
4115 4128 extension (no IPython code was touched). Now instead of:
4116 4129 a = PhysicalQuantity(4.2,'m/s**2')
4117 4130 one can simply say
4118 4131 a = 4.2 m/s**2
4119 4132 or even
4120 4133 a = 4.2 m/s^2
4121 4134
4122 4135 I use this, but it's also a proof of concept: IPython really is
4123 4136 fully user-extensible, even at the level of the parsing of the
4124 4137 command line. It's not trivial, but it's perfectly doable.
4125 4138
4126 4139 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4127 4140 the problem of modules being loaded in the inverse order in which
4128 4141 they were defined in
4129 4142
4130 4143 * Version 0.1.8 released, 0.1.9 opened for further work.
4131 4144
4132 4145 * Added magics pdef, source and file. They respectively show the
4133 4146 definition line ('prototype' in C), source code and full python
4134 4147 file for any callable object. The object inspector oinfo uses
4135 4148 these to show the same information.
4136 4149
4137 4150 * Version 0.1.7 released, 0.1.8 opened for further work.
4138 4151
4139 4152 * Separated all the magic functions into a class called Magic. The
4140 4153 InteractiveShell class was becoming too big for Xemacs to handle
4141 4154 (de-indenting a line would lock it up for 10 seconds while it
4142 4155 backtracked on the whole class!)
4143 4156
4144 4157 FIXME: didn't work. It can be done, but right now namespaces are
4145 4158 all messed up. Do it later (reverted it for now, so at least
4146 4159 everything works as before).
4147 4160
4148 4161 * Got the object introspection system (magic_oinfo) working! I
4149 4162 think this is pretty much ready for release to Janko, so he can
4150 4163 test it for a while and then announce it. Pretty much 100% of what
4151 4164 I wanted for the 'phase 1' release is ready. Happy, tired.
4152 4165
4153 4166 2001-11-12 Fernando Perez <fperez@colorado.edu>
4154 4167
4155 4168 * Version 0.1.6 released, 0.1.7 opened for further work.
4156 4169
4157 4170 * Fixed bug in printing: it used to test for truth before
4158 4171 printing, so 0 wouldn't print. Now checks for None.
4159 4172
4160 4173 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4161 4174 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4162 4175 reaches by hand into the outputcache. Think of a better way to do
4163 4176 this later.
4164 4177
4165 4178 * Various small fixes thanks to Nathan's comments.
4166 4179
4167 4180 * Changed magic_pprint to magic_Pprint. This way it doesn't
4168 4181 collide with pprint() and the name is consistent with the command
4169 4182 line option.
4170 4183
4171 4184 * Changed prompt counter behavior to be fully like
4172 4185 Mathematica's. That is, even input that doesn't return a result
4173 4186 raises the prompt counter. The old behavior was kind of confusing
4174 4187 (getting the same prompt number several times if the operation
4175 4188 didn't return a result).
4176 4189
4177 4190 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4178 4191
4179 4192 * Fixed -Classic mode (wasn't working anymore).
4180 4193
4181 4194 * Added colored prompts using Nathan's new code. Colors are
4182 4195 currently hardwired, they can be user-configurable. For
4183 4196 developers, they can be chosen in file ipythonlib.py, at the
4184 4197 beginning of the CachedOutput class def.
4185 4198
4186 4199 2001-11-11 Fernando Perez <fperez@colorado.edu>
4187 4200
4188 4201 * Version 0.1.5 released, 0.1.6 opened for further work.
4189 4202
4190 4203 * Changed magic_env to *return* the environment as a dict (not to
4191 4204 print it). This way it prints, but it can also be processed.
4192 4205
4193 4206 * Added Verbose exception reporting to interactive
4194 4207 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4195 4208 traceback. Had to make some changes to the ultraTB file. This is
4196 4209 probably the last 'big' thing in my mental todo list. This ties
4197 4210 in with the next entry:
4198 4211
4199 4212 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4200 4213 has to specify is Plain, Color or Verbose for all exception
4201 4214 handling.
4202 4215
4203 4216 * Removed ShellServices option. All this can really be done via
4204 4217 the magic system. It's easier to extend, cleaner and has automatic
4205 4218 namespace protection and documentation.
4206 4219
4207 4220 2001-11-09 Fernando Perez <fperez@colorado.edu>
4208 4221
4209 4222 * Fixed bug in output cache flushing (missing parameter to
4210 4223 __init__). Other small bugs fixed (found using pychecker).
4211 4224
4212 4225 * Version 0.1.4 opened for bugfixing.
4213 4226
4214 4227 2001-11-07 Fernando Perez <fperez@colorado.edu>
4215 4228
4216 4229 * Version 0.1.3 released, mainly because of the raw_input bug.
4217 4230
4218 4231 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4219 4232 and when testing for whether things were callable, a call could
4220 4233 actually be made to certain functions. They would get called again
4221 4234 once 'really' executed, with a resulting double call. A disaster
4222 4235 in many cases (list.reverse() would never work!).
4223 4236
4224 4237 * Removed prefilter() function, moved its code to raw_input (which
4225 4238 after all was just a near-empty caller for prefilter). This saves
4226 4239 a function call on every prompt, and simplifies the class a tiny bit.
4227 4240
4228 4241 * Fix _ip to __ip name in magic example file.
4229 4242
4230 4243 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4231 4244 work with non-gnu versions of tar.
4232 4245
4233 4246 2001-11-06 Fernando Perez <fperez@colorado.edu>
4234 4247
4235 4248 * Version 0.1.2. Just to keep track of the recent changes.
4236 4249
4237 4250 * Fixed nasty bug in output prompt routine. It used to check 'if
4238 4251 arg != None...'. Problem is, this fails if arg implements a
4239 4252 special comparison (__cmp__) which disallows comparing to
4240 4253 None. Found it when trying to use the PhysicalQuantity module from
4241 4254 ScientificPython.
4242 4255
4243 4256 2001-11-05 Fernando Perez <fperez@colorado.edu>
4244 4257
4245 4258 * Also added dirs. Now the pushd/popd/dirs family functions
4246 4259 basically like the shell, with the added convenience of going home
4247 4260 when called with no args.
4248 4261
4249 4262 * pushd/popd slightly modified to mimic shell behavior more
4250 4263 closely.
4251 4264
4252 4265 * Added env,pushd,popd from ShellServices as magic functions. I
4253 4266 think the cleanest will be to port all desired functions from
4254 4267 ShellServices as magics and remove ShellServices altogether. This
4255 4268 will provide a single, clean way of adding functionality
4256 4269 (shell-type or otherwise) to IP.
4257 4270
4258 4271 2001-11-04 Fernando Perez <fperez@colorado.edu>
4259 4272
4260 4273 * Added .ipython/ directory to sys.path. This way users can keep
4261 4274 customizations there and access them via import.
4262 4275
4263 4276 2001-11-03 Fernando Perez <fperez@colorado.edu>
4264 4277
4265 4278 * Opened version 0.1.1 for new changes.
4266 4279
4267 4280 * Changed version number to 0.1.0: first 'public' release, sent to
4268 4281 Nathan and Janko.
4269 4282
4270 4283 * Lots of small fixes and tweaks.
4271 4284
4272 4285 * Minor changes to whos format. Now strings are shown, snipped if
4273 4286 too long.
4274 4287
4275 4288 * Changed ShellServices to work on __main__ so they show up in @who
4276 4289
4277 4290 * Help also works with ? at the end of a line:
4278 4291 ?sin and sin?
4279 4292 both produce the same effect. This is nice, as often I use the
4280 4293 tab-complete to find the name of a method, but I used to then have
4281 4294 to go to the beginning of the line to put a ? if I wanted more
4282 4295 info. Now I can just add the ? and hit return. Convenient.
4283 4296
4284 4297 2001-11-02 Fernando Perez <fperez@colorado.edu>
4285 4298
4286 4299 * Python version check (>=2.1) added.
4287 4300
4288 4301 * Added LazyPython documentation. At this point the docs are quite
4289 4302 a mess. A cleanup is in order.
4290 4303
4291 4304 * Auto-installer created. For some bizarre reason, the zipfiles
4292 4305 module isn't working on my system. So I made a tar version
4293 4306 (hopefully the command line options in various systems won't kill
4294 4307 me).
4295 4308
4296 4309 * Fixes to Struct in genutils. Now all dictionary-like methods are
4297 4310 protected (reasonably).
4298 4311
4299 4312 * Added pager function to genutils and changed ? to print usage
4300 4313 note through it (it was too long).
4301 4314
4302 4315 * Added the LazyPython functionality. Works great! I changed the
4303 4316 auto-quote escape to ';', it's on home row and next to '. But
4304 4317 both auto-quote and auto-paren (still /) escapes are command-line
4305 4318 parameters.
4306 4319
4307 4320
4308 4321 2001-11-01 Fernando Perez <fperez@colorado.edu>
4309 4322
4310 4323 * Version changed to 0.0.7. Fairly large change: configuration now
4311 4324 is all stored in a directory, by default .ipython. There, all
4312 4325 config files have normal looking names (not .names)
4313 4326
4314 4327 * Version 0.0.6 Released first to Lucas and Archie as a test
4315 4328 run. Since it's the first 'semi-public' release, change version to
4316 4329 > 0.0.6 for any changes now.
4317 4330
4318 4331 * Stuff I had put in the ipplib.py changelog:
4319 4332
4320 4333 Changes to InteractiveShell:
4321 4334
4322 4335 - Made the usage message a parameter.
4323 4336
4324 4337 - Require the name of the shell variable to be given. It's a bit
4325 4338 of a hack, but allows the name 'shell' not to be hardwire in the
4326 4339 magic (@) handler, which is problematic b/c it requires
4327 4340 polluting the global namespace with 'shell'. This in turn is
4328 4341 fragile: if a user redefines a variable called shell, things
4329 4342 break.
4330 4343
4331 4344 - magic @: all functions available through @ need to be defined
4332 4345 as magic_<name>, even though they can be called simply as
4333 4346 @<name>. This allows the special command @magic to gather
4334 4347 information automatically about all existing magic functions,
4335 4348 even if they are run-time user extensions, by parsing the shell
4336 4349 instance __dict__ looking for special magic_ names.
4337 4350
4338 4351 - mainloop: added *two* local namespace parameters. This allows
4339 4352 the class to differentiate between parameters which were there
4340 4353 before and after command line initialization was processed. This
4341 4354 way, later @who can show things loaded at startup by the
4342 4355 user. This trick was necessary to make session saving/reloading
4343 4356 really work: ideally after saving/exiting/reloading a session,
4344 4357 *everythin* should look the same, including the output of @who. I
4345 4358 was only able to make this work with this double namespace
4346 4359 trick.
4347 4360
4348 4361 - added a header to the logfile which allows (almost) full
4349 4362 session restoring.
4350 4363
4351 4364 - prepend lines beginning with @ or !, with a and log
4352 4365 them. Why? !lines: may be useful to know what you did @lines:
4353 4366 they may affect session state. So when restoring a session, at
4354 4367 least inform the user of their presence. I couldn't quite get
4355 4368 them to properly re-execute, but at least the user is warned.
4356 4369
4357 4370 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now