##// END OF EJS Templates
- thread-safety fixes...
fperez -
Show More
@@ -0,0 +1,23 b''
1 """Support for interactive macros in IPython"""
2
3 #*****************************************************************************
4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
5 #
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
8 #*****************************************************************************
9
10 class Macro:
11 """Simple class to store the value of macros as strings.
12
13 This allows us to later exec them by checking when something is an
14 instance of this class."""
15
16 def __init__(self,data):
17
18 # store the macro value, as a single string which can be evaluated by
19 # runlines()
20 self.value = ''.join(data).rstrip()+'\n'
21
22 def __str__(self):
23 return self.value
@@ -1,2676 +1,2672 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 974 2005-12-29 19:48:33Z fperez $"""
4 $Id: Magic.py 975 2005-12-29 23:50:22Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import bdb
25 25 import inspect
26 26 import os
27 27 import pdb
28 28 import pydoc
29 29 import sys
30 30 import re
31 31 import tempfile
32 32 import time
33 33 import cPickle as pickle
34 34 from cStringIO import StringIO
35 35 from getopt import getopt
36 36 from pprint import pprint, pformat
37 37
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 # Homebrewed
45 45 from IPython import Debugger, OInspect, wildcard
46 46 from IPython.FakeModule import FakeModule
47 47 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 48 from IPython.PyColorize import Parser
49 49 from IPython.Struct import Struct
50 from IPython.macro import Macro
50 51 from IPython.genutils import *
51 52
52 53 #***************************************************************************
53 54 # Utility functions
54 55 def on_off(tag):
55 56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 57 return ['OFF','ON'][tag]
57 58
58 59
59 #****************************************************************************
60 # Utility classes
61 class Macro(list):
62 """Simple class to store the value of macros as strings.
63
64 This allows us to later exec them by checking when something is an
65 instance of this class."""
66
67 def __init__(self,data):
68 list.__init__(self,data)
69 self.value = ''.join(data)
70
71 60 #***************************************************************************
72 61 # Main class implementing Magic functionality
73 62 class Magic:
74 63 """Magic functions for InteractiveShell.
75 64
76 65 Shell functions which can be reached as %function_name. All magic
77 66 functions should accept a string, which they can parse for their own
78 67 needs. This can make some functions easier to type, eg `%cd ../`
79 68 vs. `%cd("../")`
80 69
81 70 ALL definitions MUST begin with the prefix magic_. The user won't need it
82 71 at the command line, but it is is needed in the definition. """
83 72
84 73 # class globals
85 74 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
86 75 'Automagic is ON, % prefix NOT needed for magic functions.']
87 76
88 77 #......................................................................
89 78 # some utility functions
90 79
91 80 def __init__(self,shell):
92 81
93 82 self.options_table = {}
94 83 if profile is None:
95 84 self.magic_prun = self.profile_missing_notice
96 85 self.shell = shell
97 86
98 87 def profile_missing_notice(self, *args, **kwargs):
99 88 error("""\
100 89 The profile module could not be found. If you are a Debian user,
101 90 it has been removed from the standard Debian package because of its non-free
102 91 license. To use profiling, please install"python2.3-profiler" from non-free.""")
103 92
104 93 def default_option(self,fn,optstr):
105 94 """Make an entry in the options_table for fn, with value optstr"""
106 95
107 96 if fn not in self.lsmagic():
108 97 error("%s is not a magic function" % fn)
109 98 self.options_table[fn] = optstr
110 99
111 100 def lsmagic(self):
112 101 """Return a list of currently available magic functions.
113 102
114 103 Gives a list of the bare names after mangling (['ls','cd', ...], not
115 104 ['magic_ls','magic_cd',...]"""
116 105
117 106 # FIXME. This needs a cleanup, in the way the magics list is built.
118 107
119 108 # magics in class definition
120 109 class_magic = lambda fn: fn.startswith('magic_') and \
121 110 callable(Magic.__dict__[fn])
122 111 # in instance namespace (run-time user additions)
123 112 inst_magic = lambda fn: fn.startswith('magic_') and \
124 113 callable(self.__dict__[fn])
125 114 # and bound magics by user (so they can access self):
126 115 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
127 116 callable(self.__class__.__dict__[fn])
128 117 magics = filter(class_magic,Magic.__dict__.keys()) + \
129 118 filter(inst_magic,self.__dict__.keys()) + \
130 119 filter(inst_bound_magic,self.__class__.__dict__.keys())
131 120 out = []
132 121 for fn in magics:
133 122 out.append(fn.replace('magic_','',1))
134 123 out.sort()
135 124 return out
136 125
137 126 def extract_input_slices(self,slices):
138 127 """Return as a string a set of input history slices.
139 128
140 129 The set of slices is given as a list of strings (like ['1','4:8','9'],
141 130 since this function is for use by magic functions which get their
142 131 arguments as strings."""
143 132
144 133 cmds = []
145 134 for chunk in slices:
146 135 if ':' in chunk:
147 136 ini,fin = map(int,chunk.split(':'))
148 137 else:
149 138 ini = int(chunk)
150 139 fin = ini+1
151 140 cmds.append(self.shell.input_hist[ini:fin])
152 141 return cmds
153 142
154 143 def _ofind(self,oname):
155 144 """Find an object in the available namespaces.
156 145
157 146 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
158 147
159 148 Has special code to detect magic functions.
160 149 """
161 150
162 151 oname = oname.strip()
163 152
164 153 # Namespaces to search in:
165 154 user_ns = self.shell.user_ns
166 155 internal_ns = self.shell.internal_ns
167 156 builtin_ns = __builtin__.__dict__
168 157 alias_ns = self.shell.alias_table
169 158
170 159 # Put them in a list. The order is important so that we find things in
171 160 # the same order that Python finds them.
172 161 namespaces = [ ('Interactive',user_ns),
173 162 ('IPython internal',internal_ns),
174 163 ('Python builtin',builtin_ns),
175 164 ('Alias',alias_ns),
176 165 ]
177 166
178 167 # initialize results to 'null'
179 168 found = 0; obj = None; ospace = None; ds = None;
180 169 ismagic = 0; isalias = 0
181 170
182 171 # Look for the given name by splitting it in parts. If the head is
183 172 # found, then we look for all the remaining parts as members, and only
184 173 # declare success if we can find them all.
185 174 oname_parts = oname.split('.')
186 175 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
187 176 for nsname,ns in namespaces:
188 177 try:
189 178 obj = ns[oname_head]
190 179 except KeyError:
191 180 continue
192 181 else:
193 182 for part in oname_rest:
194 183 try:
195 184 obj = getattr(obj,part)
196 185 except:
197 186 # Blanket except b/c some badly implemented objects
198 187 # allow __getattr__ to raise exceptions other than
199 188 # AttributeError, which then crashes IPython.
200 189 break
201 190 else:
202 191 # If we finish the for loop (no break), we got all members
203 192 found = 1
204 193 ospace = nsname
205 194 if ns == alias_ns:
206 195 isalias = 1
207 196 break # namespace loop
208 197
209 198 # Try to see if it's magic
210 199 if not found:
211 200 if oname.startswith(self.shell.ESC_MAGIC):
212 201 oname = oname[1:]
213 202 obj = getattr(self,'magic_'+oname,None)
214 203 if obj is not None:
215 204 found = 1
216 205 ospace = 'IPython internal'
217 206 ismagic = 1
218 207
219 208 # Last try: special-case some literals like '', [], {}, etc:
220 209 if not found and oname_head in ["''",'""','[]','{}','()']:
221 210 obj = eval(oname_head)
222 211 found = 1
223 212 ospace = 'Interactive'
224 213
225 214 return {'found':found, 'obj':obj, 'namespace':ospace,
226 215 'ismagic':ismagic, 'isalias':isalias}
227
216
228 217 def arg_err(self,func):
229 218 """Print docstring if incorrect arguments were passed"""
230 219 print 'Error in arguments:'
231 220 print OInspect.getdoc(func)
232 221
233
234 222 def format_latex(self,strng):
235 223 """Format a string for latex inclusion."""
236 224
237 225 # Characters that need to be escaped for latex:
238 226 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
239 227 # Magic command names as headers:
240 228 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
241 229 re.MULTILINE)
242 230 # Magic commands
243 231 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
244 232 re.MULTILINE)
245 233 # Paragraph continue
246 234 par_re = re.compile(r'\\$',re.MULTILINE)
247 235
248 236 # The "\n" symbol
249 237 newline_re = re.compile(r'\\n')
250 238
251 239 # Now build the string for output:
252 240 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
253 241 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
254 242 strng = par_re.sub(r'\\\\',strng)
255 243 strng = escape_re.sub(r'\\\1',strng)
256 244 strng = newline_re.sub(r'\\textbackslash{}n',strng)
257 245 return strng
258 246
259 247 def format_screen(self,strng):
260 248 """Format a string for screen printing.
261 249
262 250 This removes some latex-type format codes."""
263 251 # Paragraph continue
264 252 par_re = re.compile(r'\\$',re.MULTILINE)
265 253 strng = par_re.sub('',strng)
266 254 return strng
267 255
268 256 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
269 257 """Parse options passed to an argument string.
270 258
271 259 The interface is similar to that of getopt(), but it returns back a
272 260 Struct with the options as keys and the stripped argument string still
273 261 as a string.
274 262
275 263 arg_str is quoted as a true sys.argv vector by using shlex.split.
276 264 This allows us to easily expand variables, glob files, quote
277 265 arguments, etc.
278 266
279 267 Options:
280 268 -mode: default 'string'. If given as 'list', the argument string is
281 269 returned as a list (split on whitespace) instead of a string.
282 270
283 271 -list_all: put all option values in lists. Normally only options
284 272 appearing more than once are put in a list."""
285 273
286 274 # inject default options at the beginning of the input line
287 275 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
288 276 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
289 277
290 278 mode = kw.get('mode','string')
291 279 if mode not in ['string','list']:
292 280 raise ValueError,'incorrect mode given: %s' % mode
293 281 # Get options
294 282 list_all = kw.get('list_all',0)
295 283
296 284 # Check if we have more than one argument to warrant extra processing:
297 285 odict = {} # Dictionary with options
298 286 args = arg_str.split()
299 287 if len(args) >= 1:
300 288 # If the list of inputs only has 0 or 1 thing in it, there's no
301 289 # need to look for options
302 290 argv = shlex_split(arg_str)
303 291 # Do regular option processing
304 292 opts,args = getopt(argv,opt_str,*long_opts)
305 293 for o,a in opts:
306 294 if o.startswith('--'):
307 295 o = o[2:]
308 296 else:
309 297 o = o[1:]
310 298 try:
311 299 odict[o].append(a)
312 300 except AttributeError:
313 301 odict[o] = [odict[o],a]
314 302 except KeyError:
315 303 if list_all:
316 304 odict[o] = [a]
317 305 else:
318 306 odict[o] = a
319 307
320 308 # Prepare opts,args for return
321 309 opts = Struct(odict)
322 310 if mode == 'string':
323 311 args = ' '.join(args)
324 312
325 313 return opts,args
326 314
327 315 #......................................................................
328 316 # And now the actual magic functions
329 317
330 318 # Functions for IPython shell work (vars,funcs, config, etc)
331 319 def magic_lsmagic(self, parameter_s = ''):
332 320 """List currently available magic functions."""
333 321 mesc = self.shell.ESC_MAGIC
334 322 print 'Available magic functions:\n'+mesc+\
335 323 (' '+mesc).join(self.lsmagic())
336 324 print '\n' + Magic.auto_status[self.shell.rc.automagic]
337 325 return None
338 326
339 327 def magic_magic(self, parameter_s = ''):
340 328 """Print information about the magic function system."""
341 329
342 330 mode = ''
343 331 try:
344 332 if parameter_s.split()[0] == '-latex':
345 333 mode = 'latex'
346 334 except:
347 335 pass
348 336
349 337 magic_docs = []
350 338 for fname in self.lsmagic():
351 339 mname = 'magic_' + fname
352 340 for space in (Magic,self,self.__class__):
353 341 try:
354 342 fn = space.__dict__[mname]
355 343 except KeyError:
356 344 pass
357 345 else:
358 346 break
359 347 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
360 348 fname,fn.__doc__))
361 349 magic_docs = ''.join(magic_docs)
362 350
363 351 if mode == 'latex':
364 352 print self.format_latex(magic_docs)
365 353 return
366 354 else:
367 355 magic_docs = self.format_screen(magic_docs)
368 356
369 357 outmsg = """
370 358 IPython's 'magic' functions
371 359 ===========================
372 360
373 361 The magic function system provides a series of functions which allow you to
374 362 control the behavior of IPython itself, plus a lot of system-type
375 363 features. All these functions are prefixed with a % character, but parameters
376 364 are given without parentheses or quotes.
377 365
378 366 NOTE: If you have 'automagic' enabled (via the command line option or with the
379 367 %automagic function), you don't need to type in the % explicitly. By default,
380 368 IPython ships with automagic on, so you should only rarely need the % escape.
381 369
382 370 Example: typing '%cd mydir' (without the quotes) changes you working directory
383 371 to 'mydir', if it exists.
384 372
385 373 You can define your own magic functions to extend the system. See the supplied
386 374 ipythonrc and example-magic.py files for details (in your ipython
387 375 configuration directory, typically $HOME/.ipython/).
388 376
389 377 You can also define your own aliased names for magic functions. In your
390 378 ipythonrc file, placing a line like:
391 379
392 380 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
393 381
394 382 will define %pf as a new name for %profile.
395 383
396 384 You can also call magics in code using the ipmagic() function, which IPython
397 385 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
398 386
399 387 For a list of the available magic functions, use %lsmagic. For a description
400 388 of any of them, type %magic_name?, e.g. '%cd?'.
401 389
402 390 Currently the magic system has the following functions:\n"""
403 391
404 392 mesc = self.shell.ESC_MAGIC
405 393 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
406 394 "\n\n%s%s\n\n%s" % (outmsg,
407 395 magic_docs,mesc,mesc,
408 396 (' '+mesc).join(self.lsmagic()),
409 397 Magic.auto_status[self.shell.rc.automagic] ) )
410 398
411 399 page(outmsg,screen_lines=self.shell.rc.screen_length)
412 400
413 401 def magic_automagic(self, parameter_s = ''):
414 402 """Make magic functions callable without having to type the initial %.
415 403
416 404 Toggles on/off (when off, you must call it as %automagic, of
417 405 course). Note that magic functions have lowest priority, so if there's
418 406 a variable whose name collides with that of a magic fn, automagic
419 407 won't work for that function (you get the variable instead). However,
420 408 if you delete the variable (del var), the previously shadowed magic
421 409 function becomes visible to automagic again."""
422 410
423 411 rc = self.shell.rc
424 412 rc.automagic = not rc.automagic
425 413 print '\n' + Magic.auto_status[rc.automagic]
426 414
427 415 def magic_autocall(self, parameter_s = ''):
428 416 """Make functions callable without having to type parentheses.
429 417
430 418 This toggles the autocall command line option on and off."""
431 419
432 420 rc = self.shell.rc
433 421 rc.autocall = not rc.autocall
434 422 print "Automatic calling is:",['OFF','ON'][rc.autocall]
435 423
436 424 def magic_autoindent(self, parameter_s = ''):
437 425 """Toggle autoindent on/off (if available)."""
438 426
439 427 self.shell.set_autoindent()
440 428 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
441 429
442 430 def magic_system_verbose(self, parameter_s = ''):
443 431 """Toggle verbose printing of system calls on/off."""
444 432
445 433 self.shell.rc_set_toggle('system_verbose')
446 434 print "System verbose printing is:",\
447 435 ['OFF','ON'][self.shell.rc.system_verbose]
448 436
449 437 def magic_history(self, parameter_s = ''):
450 438 """Print input history (_i<n> variables), with most recent last.
451 439
452 440 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
453 441 %history [-n] n -> print at most n inputs\\
454 442 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
455 443
456 444 Each input's number <n> is shown, and is accessible as the
457 445 automatically generated variable _i<n>. Multi-line statements are
458 446 printed starting at a new line for easy copy/paste.
459 447
460 448 If option -n is used, input numbers are not printed. This is useful if
461 449 you want to get a printout of many lines which can be directly pasted
462 450 into a text editor.
463 451
464 452 This feature is only available if numbered prompts are in use."""
465 453
466 454 if not self.shell.outputcache.do_full_cache:
467 455 print 'This feature is only available if numbered prompts are in use.'
468 456 return
469 457 opts,args = self.parse_options(parameter_s,'n',mode='list')
470 458
471 459 default_length = 40
472 460 if len(args) == 0:
473 461 final = self.shell.outputcache.prompt_count
474 462 init = max(1,final-default_length)
475 463 elif len(args) == 1:
476 464 final = self.shell.outputcache.prompt_count
477 465 init = max(1,final-int(args[0]))
478 466 elif len(args) == 2:
479 467 init,final = map(int,args)
480 468 else:
481 469 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
482 470 print self.magic_hist.__doc__
483 471 return
484 472 width = len(str(final))
485 473 line_sep = ['','\n']
486 474 input_hist = self.shell.input_hist
487 475 print_nums = not opts.has_key('n')
488 476 for in_num in range(init,final):
489 477 inline = input_hist[in_num]
490 478 multiline = inline.count('\n') > 1
491 479 if print_nums:
492 480 print str(in_num).ljust(width)+':'+ line_sep[multiline],
493 481 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
494 482 inline.startswith('#!'):
495 483 print inline[1:],
496 484 else:
497 485 print inline,
498 486
499 487 def magic_hist(self, parameter_s=''):
500 488 """Alternate name for %history."""
501 489 return self.magic_history(parameter_s)
502 490
503 491 def magic_p(self, parameter_s=''):
504 492 """Just a short alias for Python's 'print'."""
505 493 exec 'print ' + parameter_s in self.shell.user_ns
506 494
507 495 def magic_r(self, parameter_s=''):
508 496 """Repeat previous input.
509 497
510 498 If given an argument, repeats the previous command which starts with
511 499 the same string, otherwise it just repeats the previous input.
512 500
513 501 Shell escaped commands (with ! as first character) are not recognized
514 502 by this system, only pure python code and magic commands.
515 503 """
516 504
517 505 start = parameter_s.strip()
518 506 esc_magic = self.shell.ESC_MAGIC
519 507 # Identify magic commands even if automagic is on (which means
520 508 # the in-memory version is different from that typed by the user).
521 509 if self.shell.rc.automagic:
522 510 start_magic = esc_magic+start
523 511 else:
524 512 start_magic = start
525 513 # Look through the input history in reverse
526 514 for n in range(len(self.shell.input_hist)-2,0,-1):
527 515 input = self.shell.input_hist[n]
528 516 # skip plain 'r' lines so we don't recurse to infinity
529 517 if input != 'ipmagic("r")\n' and \
530 518 (input.startswith(start) or input.startswith(start_magic)):
531 519 #print 'match',`input` # dbg
532 520 print 'Executing:',input,
533 521 self.shell.runlines(input)
534 522 return
535 523 print 'No previous input matching `%s` found.' % start
536 524
537 525 def magic_page(self, parameter_s=''):
538 526 """Pretty print the object and display it through a pager.
539 527
540 528 If no parameter is given, use _ (last output)."""
541 529 # After a function contributed by Olivier Aubert, slightly modified.
542 530
543 531 oname = parameter_s and parameter_s or '_'
544 532 info = self._ofind(oname)
545 533 if info['found']:
546 534 page(pformat(info['obj']))
547 535 else:
548 536 print 'Object `%s` not found' % oname
549 537
550 538 def magic_profile(self, parameter_s=''):
551 539 """Print your currently active IPyhton profile."""
552 540 if self.shell.rc.profile:
553 541 printpl('Current IPython profile: $self.shell.rc.profile.')
554 542 else:
555 543 print 'No profile active.'
556 544
557 545 def _inspect(self,meth,oname,**kw):
558 546 """Generic interface to the inspector system.
559 547
560 548 This function is meant to be called by pdef, pdoc & friends."""
561 549
562 550 oname = oname.strip()
563 551 info = Struct(self._ofind(oname))
564 552 if info.found:
565 553 pmethod = getattr(self.shell.inspector,meth)
566 554 formatter = info.ismagic and self.format_screen or None
567 555 if meth == 'pdoc':
568 556 pmethod(info.obj,oname,formatter)
569 557 elif meth == 'pinfo':
570 558 pmethod(info.obj,oname,formatter,info,**kw)
571 559 else:
572 560 pmethod(info.obj,oname)
573 561 else:
574 562 print 'Object `%s` not found.' % oname
575 563 return 'not found' # so callers can take other action
576 564
577 565 def magic_pdef(self, parameter_s=''):
578 566 """Print the definition header for any callable object.
579 567
580 568 If the object is a class, print the constructor information."""
581 569 self._inspect('pdef',parameter_s)
582 570
583 571 def magic_pdoc(self, parameter_s=''):
584 572 """Print the docstring for an object.
585 573
586 574 If the given object is a class, it will print both the class and the
587 575 constructor docstrings."""
588 576 self._inspect('pdoc',parameter_s)
589 577
590 578 def magic_psource(self, parameter_s=''):
591 579 """Print (or run through pager) the source code for an object."""
592 580 self._inspect('psource',parameter_s)
593 581
594 582 def magic_pfile(self, parameter_s=''):
595 583 """Print (or run through pager) the file where an object is defined.
596 584
597 585 The file opens at the line where the object definition begins. IPython
598 586 will honor the environment variable PAGER if set, and otherwise will
599 587 do its best to print the file in a convenient form.
600 588
601 589 If the given argument is not an object currently defined, IPython will
602 590 try to interpret it as a filename (automatically adding a .py extension
603 591 if needed). You can thus use %pfile as a syntax highlighting code
604 592 viewer."""
605 593
606 594 # first interpret argument as an object name
607 595 out = self._inspect('pfile',parameter_s)
608 596 # if not, try the input as a filename
609 597 if out == 'not found':
610 598 try:
611 599 filename = get_py_filename(parameter_s)
612 600 except IOError,msg:
613 601 print msg
614 602 return
615 603 page(self.shell.inspector.format(file(filename).read()))
616 604
617 605 def magic_pinfo(self, parameter_s=''):
618 606 """Provide detailed information about an object.
619 607
620 608 '%pinfo object' is just a synonym for object? or ?object."""
621 609
622 610 #print 'pinfo par: <%s>' % parameter_s # dbg
623 611
624 612 # detail_level: 0 -> obj? , 1 -> obj??
625 613 detail_level = 0
626 614 # We need to detect if we got called as 'pinfo pinfo foo', which can
627 615 # happen if the user types 'pinfo foo?' at the cmd line.
628 616 pinfo,qmark1,oname,qmark2 = \
629 617 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
630 618 if pinfo or qmark1 or qmark2:
631 619 detail_level = 1
632 620 if "*" in oname:
633 621 self.magic_psearch(oname)
634 622 else:
635 623 self._inspect('pinfo',oname,detail_level=detail_level)
636 624
637 625 def magic_psearch(self, parameter_s=''):
638 626 """Search for object in namespaces by wildcard.
639 627
640 628 %psearch [options] PATTERN [OBJECT TYPE]
641 629
642 630 Note: ? can be used as a synonym for %psearch, at the beginning or at
643 631 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
644 632 rest of the command line must be unchanged (options come first), so
645 633 for example the following forms are equivalent
646 634
647 635 %psearch -i a* function
648 636 -i a* function?
649 637 ?-i a* function
650 638
651 639 Arguments:
652 640
653 641 PATTERN
654 642
655 643 where PATTERN is a string containing * as a wildcard similar to its
656 644 use in a shell. The pattern is matched in all namespaces on the
657 645 search path. By default objects starting with a single _ are not
658 646 matched, many IPython generated objects have a single
659 647 underscore. The default is case insensitive matching. Matching is
660 648 also done on the attributes of objects and not only on the objects
661 649 in a module.
662 650
663 651 [OBJECT TYPE]
664 652
665 653 Is the name of a python type from the types module. The name is
666 654 given in lowercase without the ending type, ex. StringType is
667 655 written string. By adding a type here only objects matching the
668 656 given type are matched. Using all here makes the pattern match all
669 657 types (this is the default).
670 658
671 659 Options:
672 660
673 661 -a: makes the pattern match even objects whose names start with a
674 662 single underscore. These names are normally ommitted from the
675 663 search.
676 664
677 665 -i/-c: make the pattern case insensitive/sensitive. If neither of
678 666 these options is given, the default is read from your ipythonrc
679 667 file. The option name which sets this value is
680 668 'wildcards_case_sensitive'. If this option is not specified in your
681 669 ipythonrc file, IPython's internal default is to do a case sensitive
682 670 search.
683 671
684 672 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
685 673 specifiy can be searched in any of the following namespaces:
686 674 'builtin', 'user', 'user_global','internal', 'alias', where
687 675 'builtin' and 'user' are the search defaults. Note that you should
688 676 not use quotes when specifying namespaces.
689 677
690 678 'Builtin' contains the python module builtin, 'user' contains all
691 679 user data, 'alias' only contain the shell aliases and no python
692 680 objects, 'internal' contains objects used by IPython. The
693 681 'user_global' namespace is only used by embedded IPython instances,
694 682 and it contains module-level globals. You can add namespaces to the
695 683 search with -s or exclude them with -e (these options can be given
696 684 more than once).
697 685
698 686 Examples:
699 687
700 688 %psearch a* -> objects beginning with an a
701 689 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
702 690 %psearch a* function -> all functions beginning with an a
703 691 %psearch re.e* -> objects beginning with an e in module re
704 692 %psearch r*.e* -> objects that start with e in modules starting in r
705 693 %psearch r*.* string -> all strings in modules beginning with r
706 694
707 695 Case sensitve search:
708 696
709 697 %psearch -c a* list all object beginning with lower case a
710 698
711 699 Show objects beginning with a single _:
712 700
713 701 %psearch -a _* list objects beginning with a single underscore"""
714 702
715 703 # default namespaces to be searched
716 704 def_search = ['user','builtin']
717 705
718 706 # Process options/args
719 707 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
720 708 opt = opts.get
721 709 shell = self.shell
722 710 psearch = shell.inspector.psearch
723 711
724 712 # select case options
725 713 if opts.has_key('i'):
726 714 ignore_case = True
727 715 elif opts.has_key('c'):
728 716 ignore_case = False
729 717 else:
730 718 ignore_case = not shell.rc.wildcards_case_sensitive
731 719
732 720 # Build list of namespaces to search from user options
733 721 def_search.extend(opt('s',[]))
734 722 ns_exclude = ns_exclude=opt('e',[])
735 723 ns_search = [nm for nm in def_search if nm not in ns_exclude]
736 724
737 725 # Call the actual search
738 726 try:
739 727 psearch(args,shell.ns_table,ns_search,
740 728 show_all=opt('a'),ignore_case=ignore_case)
741 729 except:
742 730 shell.showtraceback()
743 731
744 732 def magic_who_ls(self, parameter_s=''):
745 733 """Return a sorted list of all interactive variables.
746 734
747 735 If arguments are given, only variables of types matching these
748 736 arguments are returned."""
749 737
750 738 user_ns = self.shell.user_ns
751 739 out = []
752 740 typelist = parameter_s.split()
753 741 for i in self.shell.user_ns.keys():
754 742 if not (i.startswith('_') or i.startswith('_i')) \
755 743 and not (self.shell.internal_ns.has_key(i) or
756 744 self.shell.user_config_ns.has_key(i)):
757 745 if typelist:
758 746 if type(user_ns[i]).__name__ in typelist:
759 747 out.append(i)
760 748 else:
761 749 out.append(i)
762 750 out.sort()
763 751 return out
764 752
765 753 def magic_who(self, parameter_s=''):
766 754 """Print all interactive variables, with some minimal formatting.
767 755
768 756 If any arguments are given, only variables whose type matches one of
769 757 these are printed. For example:
770 758
771 759 %who function str
772 760
773 761 will only list functions and strings, excluding all other types of
774 762 variables. To find the proper type names, simply use type(var) at a
775 763 command line to see how python prints type names. For example:
776 764
777 765 In [1]: type('hello')\\
778 766 Out[1]: <type 'str'>
779 767
780 768 indicates that the type name for strings is 'str'.
781 769
782 770 %who always excludes executed names loaded through your configuration
783 771 file and things which are internal to IPython.
784 772
785 773 This is deliberate, as typically you may load many modules and the
786 774 purpose of %who is to show you only what you've manually defined."""
787 775
788 776 varlist = self.magic_who_ls(parameter_s)
789 777 if not varlist:
790 778 print 'Interactive namespace is empty.'
791 779 return
792 780
793 781 # if we have variables, move on...
794 782
795 783 # stupid flushing problem: when prompts have no separators, stdout is
796 784 # getting lost. I'm starting to think this is a python bug. I'm having
797 785 # to force a flush with a print because even a sys.stdout.flush
798 786 # doesn't seem to do anything!
799 787
800 788 count = 0
801 789 for i in varlist:
802 790 print i+'\t',
803 791 count += 1
804 792 if count > 8:
805 793 count = 0
806 794 print
807 795 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
808 796
809 797 print # well, this does force a flush at the expense of an extra \n
810 798
811 799 def magic_whos(self, parameter_s=''):
812 800 """Like %who, but gives some extra information about each variable.
813 801
814 802 The same type filtering of %who can be applied here.
815 803
816 804 For all variables, the type is printed. Additionally it prints:
817 805
818 806 - For {},[],(): their length.
819 807
820 808 - For Numeric arrays, a summary with shape, number of elements,
821 809 typecode and size in memory.
822 810
823 811 - Everything else: a string representation, snipping their middle if
824 812 too long."""
825 813
826 814 varnames = self.magic_who_ls(parameter_s)
827 815 if not varnames:
828 816 print 'Interactive namespace is empty.'
829 817 return
830 818
831 819 # if we have variables, move on...
832 820
833 821 # for these types, show len() instead of data:
834 822 seq_types = [types.DictType,types.ListType,types.TupleType]
835 823
836 824 # for Numeric arrays, display summary info
837 825 try:
838 826 import Numeric
839 827 except ImportError:
840 828 array_type = None
841 829 else:
842 830 array_type = Numeric.ArrayType.__name__
843 831
844 832 # Find all variable names and types so we can figure out column sizes
845 833 get_vars = lambda i: self.shell.user_ns[i]
846 834 type_name = lambda v: type(v).__name__
847 835 varlist = map(get_vars,varnames)
848 typelist = map(type_name,varlist)
836
837 typelist = []
838 for vv in varlist:
839 tt = type_name(vv)
840 if tt=='instance':
841 typelist.append(str(vv.__class__))
842 else:
843 typelist.append(tt)
844
849 845 # column labels and # of spaces as separator
850 846 varlabel = 'Variable'
851 847 typelabel = 'Type'
852 848 datalabel = 'Data/Info'
853 849 colsep = 3
854 850 # variable format strings
855 851 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
856 852 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
857 853 aformat = "%s: %s elems, type `%s`, %s bytes"
858 854 # find the size of the columns to format the output nicely
859 855 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
860 856 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
861 857 # table header
862 858 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
863 859 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
864 860 # and the table itself
865 861 kb = 1024
866 862 Mb = 1048576 # kb**2
867 863 for vname,var,vtype in zip(varnames,varlist,typelist):
868 864 print itpl(vformat),
869 865 if vtype in seq_types:
870 866 print len(var)
871 867 elif vtype==array_type:
872 868 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
873 869 vsize = Numeric.size(var)
874 870 vbytes = vsize*var.itemsize()
875 871 if vbytes < 100000:
876 872 print aformat % (vshape,vsize,var.typecode(),vbytes)
877 873 else:
878 874 print aformat % (vshape,vsize,var.typecode(),vbytes),
879 875 if vbytes < Mb:
880 876 print '(%s kb)' % (vbytes/kb,)
881 877 else:
882 878 print '(%s Mb)' % (vbytes/Mb,)
883 879 else:
884 vstr = str(var)
880 vstr = str(var).replace('\n','\\n')
885 881 if len(vstr) < 50:
886 882 print vstr
887 883 else:
888 884 printpl(vfmt_short)
889 885
890 886 def magic_reset(self, parameter_s=''):
891 887 """Resets the namespace by removing all names defined by the user.
892 888
893 889 Input/Output history are left around in case you need them."""
894 890
895 891 ans = raw_input(
896 892 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
897 893 if not ans.lower() == 'y':
898 894 print 'Nothing done.'
899 895 return
900 896 user_ns = self.shell.user_ns
901 897 for i in self.magic_who_ls():
902 898 del(user_ns[i])
903 899
904 900 def magic_config(self,parameter_s=''):
905 901 """Show IPython's internal configuration."""
906 902
907 903 page('Current configuration structure:\n'+
908 904 pformat(self.shell.rc.dict()))
909 905
910 906 def magic_logstart(self,parameter_s=''):
911 907 """Start logging anywhere in a session.
912 908
913 909 %logstart [-o|-t] [log_name [log_mode]]
914 910
915 911 If no name is given, it defaults to a file named 'ipython_log.py' in your
916 912 current directory, in 'rotate' mode (see below).
917 913
918 914 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
919 915 history up to that point and then continues logging.
920 916
921 917 %logstart takes a second optional parameter: logging mode. This can be one
922 918 of (note that the modes are given unquoted):\\
923 919 append: well, that says it.\\
924 920 backup: rename (if exists) to name~ and start name.\\
925 921 global: single logfile in your home dir, appended to.\\
926 922 over : overwrite existing log.\\
927 923 rotate: create rotating logs name.1~, name.2~, etc.
928 924
929 925 Options:
930 926
931 927 -o: log also IPython's output. In this mode, all commands which
932 928 generate an Out[NN] prompt are recorded to the logfile, right after
933 929 their corresponding input line. The output lines are always
934 930 prepended with a '#[Out]# ' marker, so that the log remains valid
935 931 Python code.
936 932
937 933 Since this marker is always the same, filtering only the output from
938 934 a log is very easy, using for example a simple awk call:
939 935
940 936 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
941 937
942 938 -t: put timestamps before each input line logged (these are put in
943 939 comments)."""
944 940
945 941 opts,par = self.parse_options(parameter_s,'ot')
946 942 log_output = 'o' in opts
947 943 timestamp = 't' in opts
948 944
949 945 rc = self.shell.rc
950 946 logger = self.shell.logger
951 947
952 948 # if no args are given, the defaults set in the logger constructor by
953 949 # ipytohn remain valid
954 950 if par:
955 951 try:
956 952 logfname,logmode = par.split()
957 953 except:
958 954 logfname = par
959 955 logmode = 'backup'
960 956 else:
961 957 logfname = logger.logfname
962 958 logmode = logger.logmode
963 959 # put logfname into rc struct as if it had been called on the command
964 960 # line, so it ends up saved in the log header Save it in case we need
965 961 # to restore it...
966 962 old_logfile = rc.opts.get('logfile','')
967 963 if logfname:
968 964 logfname = os.path.expanduser(logfname)
969 965 rc.opts.logfile = logfname
970 966 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
971 967 try:
972 968 started = logger.logstart(logfname,loghead,logmode,
973 969 log_output,timestamp)
974 970 except:
975 971 rc.opts.logfile = old_logfile
976 972 warn("Couldn't start log: %s" % sys.exc_info()[1])
977 973 else:
978 974 # log input history up to this point, optionally interleaving
979 975 # output if requested
980 976
981 977 if timestamp:
982 978 # disable timestamping for the previous history, since we've
983 979 # lost those already (no time machine here).
984 980 logger.timestamp = False
985 981 if log_output:
986 982 log_write = logger.log_write
987 983 input_hist = self.shell.input_hist
988 984 output_hist = self.shell.output_hist
989 985 for n in range(1,len(input_hist)-1):
990 986 log_write(input_hist[n].rstrip())
991 987 if n in output_hist:
992 988 log_write(repr(output_hist[n]),'output')
993 989 else:
994 990 logger.log_write(self.shell.input_hist[1:])
995 991 if timestamp:
996 992 # re-enable timestamping
997 993 logger.timestamp = True
998 994
999 995 print ('Activating auto-logging. '
1000 996 'Current session state plus future input saved.')
1001 997 logger.logstate()
1002 998
1003 999 def magic_logoff(self,parameter_s=''):
1004 1000 """Temporarily stop logging.
1005 1001
1006 1002 You must have previously started logging."""
1007 1003 self.shell.logger.switch_log(0)
1008 1004
1009 1005 def magic_logon(self,parameter_s=''):
1010 1006 """Restart logging.
1011 1007
1012 1008 This function is for restarting logging which you've temporarily
1013 1009 stopped with %logoff. For starting logging for the first time, you
1014 1010 must use the %logstart function, which allows you to specify an
1015 1011 optional log filename."""
1016 1012
1017 1013 self.shell.logger.switch_log(1)
1018 1014
1019 1015 def magic_logstate(self,parameter_s=''):
1020 1016 """Print the status of the logging system."""
1021 1017
1022 1018 self.shell.logger.logstate()
1023 1019
1024 1020 def magic_pdb(self, parameter_s=''):
1025 1021 """Control the calling of the pdb interactive debugger.
1026 1022
1027 1023 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1028 1024 argument it works as a toggle.
1029 1025
1030 1026 When an exception is triggered, IPython can optionally call the
1031 1027 interactive pdb debugger after the traceback printout. %pdb toggles
1032 1028 this feature on and off."""
1033 1029
1034 1030 par = parameter_s.strip().lower()
1035 1031
1036 1032 if par:
1037 1033 try:
1038 1034 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1039 1035 except KeyError:
1040 1036 print ('Incorrect argument. Use on/1, off/0, '
1041 1037 'or nothing for a toggle.')
1042 1038 return
1043 1039 else:
1044 1040 # toggle
1045 1041 new_pdb = not self.shell.InteractiveTB.call_pdb
1046 1042
1047 1043 # set on the shell
1048 1044 self.shell.call_pdb = new_pdb
1049 1045 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1050 1046
1051 1047 def magic_prun(self, parameter_s ='',user_mode=1,
1052 1048 opts=None,arg_lst=None,prog_ns=None):
1053 1049
1054 1050 """Run a statement through the python code profiler.
1055 1051
1056 1052 Usage:\\
1057 1053 %prun [options] statement
1058 1054
1059 1055 The given statement (which doesn't require quote marks) is run via the
1060 1056 python profiler in a manner similar to the profile.run() function.
1061 1057 Namespaces are internally managed to work correctly; profile.run
1062 1058 cannot be used in IPython because it makes certain assumptions about
1063 1059 namespaces which do not hold under IPython.
1064 1060
1065 1061 Options:
1066 1062
1067 1063 -l <limit>: you can place restrictions on what or how much of the
1068 1064 profile gets printed. The limit value can be:
1069 1065
1070 1066 * A string: only information for function names containing this string
1071 1067 is printed.
1072 1068
1073 1069 * An integer: only these many lines are printed.
1074 1070
1075 1071 * A float (between 0 and 1): this fraction of the report is printed
1076 1072 (for example, use a limit of 0.4 to see the topmost 40% only).
1077 1073
1078 1074 You can combine several limits with repeated use of the option. For
1079 1075 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1080 1076 information about class constructors.
1081 1077
1082 1078 -r: return the pstats.Stats object generated by the profiling. This
1083 1079 object has all the information about the profile in it, and you can
1084 1080 later use it for further analysis or in other functions.
1085 1081
1086 1082 Since magic functions have a particular form of calling which prevents
1087 1083 you from writing something like:\\
1088 1084 In [1]: p = %prun -r print 4 # invalid!\\
1089 1085 you must instead use IPython's automatic variables to assign this:\\
1090 1086 In [1]: %prun -r print 4 \\
1091 1087 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1092 1088 In [2]: stats = _
1093 1089
1094 1090 If you really need to assign this value via an explicit function call,
1095 1091 you can always tap directly into the true name of the magic function
1096 1092 by using the ipmagic function (which IPython automatically adds to the
1097 1093 builtins):\\
1098 1094 In [3]: stats = ipmagic('prun','-r print 4')
1099 1095
1100 1096 You can type ipmagic? for more details on ipmagic.
1101 1097
1102 1098 -s <key>: sort profile by given key. You can provide more than one key
1103 1099 by using the option several times: '-s key1 -s key2 -s key3...'. The
1104 1100 default sorting key is 'time'.
1105 1101
1106 1102 The following is copied verbatim from the profile documentation
1107 1103 referenced below:
1108 1104
1109 1105 When more than one key is provided, additional keys are used as
1110 1106 secondary criteria when the there is equality in all keys selected
1111 1107 before them.
1112 1108
1113 1109 Abbreviations can be used for any key names, as long as the
1114 1110 abbreviation is unambiguous. The following are the keys currently
1115 1111 defined:
1116 1112
1117 1113 Valid Arg Meaning\\
1118 1114 "calls" call count\\
1119 1115 "cumulative" cumulative time\\
1120 1116 "file" file name\\
1121 1117 "module" file name\\
1122 1118 "pcalls" primitive call count\\
1123 1119 "line" line number\\
1124 1120 "name" function name\\
1125 1121 "nfl" name/file/line\\
1126 1122 "stdname" standard name\\
1127 1123 "time" internal time
1128 1124
1129 1125 Note that all sorts on statistics are in descending order (placing
1130 1126 most time consuming items first), where as name, file, and line number
1131 1127 searches are in ascending order (i.e., alphabetical). The subtle
1132 1128 distinction between "nfl" and "stdname" is that the standard name is a
1133 1129 sort of the name as printed, which means that the embedded line
1134 1130 numbers get compared in an odd way. For example, lines 3, 20, and 40
1135 1131 would (if the file names were the same) appear in the string order
1136 1132 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1137 1133 line numbers. In fact, sort_stats("nfl") is the same as
1138 1134 sort_stats("name", "file", "line").
1139 1135
1140 1136 -T <filename>: save profile results as shown on screen to a text
1141 1137 file. The profile is still shown on screen.
1142 1138
1143 1139 -D <filename>: save (via dump_stats) profile statistics to given
1144 1140 filename. This data is in a format understod by the pstats module, and
1145 1141 is generated by a call to the dump_stats() method of profile
1146 1142 objects. The profile is still shown on screen.
1147 1143
1148 1144 If you want to run complete programs under the profiler's control, use
1149 1145 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1150 1146 contains profiler specific options as described here.
1151 1147
1152 1148 You can read the complete documentation for the profile module with:\\
1153 1149 In [1]: import profile; profile.help() """
1154 1150
1155 1151 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1156 1152 # protect user quote marks
1157 1153 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1158 1154
1159 1155 if user_mode: # regular user call
1160 1156 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1161 1157 list_all=1)
1162 1158 namespace = self.shell.user_ns
1163 1159 else: # called to run a program by %run -p
1164 1160 try:
1165 1161 filename = get_py_filename(arg_lst[0])
1166 1162 except IOError,msg:
1167 1163 error(msg)
1168 1164 return
1169 1165
1170 1166 arg_str = 'execfile(filename,prog_ns)'
1171 1167 namespace = locals()
1172 1168
1173 1169 opts.merge(opts_def)
1174 1170
1175 1171 prof = profile.Profile()
1176 1172 try:
1177 1173 prof = prof.runctx(arg_str,namespace,namespace)
1178 1174 sys_exit = ''
1179 1175 except SystemExit:
1180 1176 sys_exit = """*** SystemExit exception caught in code being profiled."""
1181 1177
1182 1178 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1183 1179
1184 1180 lims = opts.l
1185 1181 if lims:
1186 1182 lims = [] # rebuild lims with ints/floats/strings
1187 1183 for lim in opts.l:
1188 1184 try:
1189 1185 lims.append(int(lim))
1190 1186 except ValueError:
1191 1187 try:
1192 1188 lims.append(float(lim))
1193 1189 except ValueError:
1194 1190 lims.append(lim)
1195 1191
1196 1192 # trap output
1197 1193 sys_stdout = sys.stdout
1198 1194 stdout_trap = StringIO()
1199 1195 try:
1200 1196 sys.stdout = stdout_trap
1201 1197 stats.print_stats(*lims)
1202 1198 finally:
1203 1199 sys.stdout = sys_stdout
1204 1200 output = stdout_trap.getvalue()
1205 1201 output = output.rstrip()
1206 1202
1207 1203 page(output,screen_lines=self.shell.rc.screen_length)
1208 1204 print sys_exit,
1209 1205
1210 1206 dump_file = opts.D[0]
1211 1207 text_file = opts.T[0]
1212 1208 if dump_file:
1213 1209 prof.dump_stats(dump_file)
1214 1210 print '\n*** Profile stats marshalled to file',\
1215 1211 `dump_file`+'.',sys_exit
1216 1212 if text_file:
1217 1213 file(text_file,'w').write(output)
1218 1214 print '\n*** Profile printout saved to text file',\
1219 1215 `text_file`+'.',sys_exit
1220 1216
1221 1217 if opts.has_key('r'):
1222 1218 return stats
1223 1219 else:
1224 1220 return None
1225 1221
1226 1222 def magic_run(self, parameter_s ='',runner=None):
1227 1223 """Run the named file inside IPython as a program.
1228 1224
1229 1225 Usage:\\
1230 1226 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1231 1227
1232 1228 Parameters after the filename are passed as command-line arguments to
1233 1229 the program (put in sys.argv). Then, control returns to IPython's
1234 1230 prompt.
1235 1231
1236 1232 This is similar to running at a system prompt:\\
1237 1233 $ python file args\\
1238 1234 but with the advantage of giving you IPython's tracebacks, and of
1239 1235 loading all variables into your interactive namespace for further use
1240 1236 (unless -p is used, see below).
1241 1237
1242 1238 The file is executed in a namespace initially consisting only of
1243 1239 __name__=='__main__' and sys.argv constructed as indicated. It thus
1244 1240 sees its environment as if it were being run as a stand-alone
1245 1241 program. But after execution, the IPython interactive namespace gets
1246 1242 updated with all variables defined in the program (except for __name__
1247 1243 and sys.argv). This allows for very convenient loading of code for
1248 1244 interactive work, while giving each program a 'clean sheet' to run in.
1249 1245
1250 1246 Options:
1251 1247
1252 1248 -n: __name__ is NOT set to '__main__', but to the running file's name
1253 1249 without extension (as python does under import). This allows running
1254 1250 scripts and reloading the definitions in them without calling code
1255 1251 protected by an ' if __name__ == "__main__" ' clause.
1256 1252
1257 1253 -i: run the file in IPython's namespace instead of an empty one. This
1258 1254 is useful if you are experimenting with code written in a text editor
1259 1255 which depends on variables defined interactively.
1260 1256
1261 1257 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1262 1258 being run. This is particularly useful if IPython is being used to
1263 1259 run unittests, which always exit with a sys.exit() call. In such
1264 1260 cases you are interested in the output of the test results, not in
1265 1261 seeing a traceback of the unittest module.
1266 1262
1267 1263 -t: print timing information at the end of the run. IPython will give
1268 1264 you an estimated CPU time consumption for your script, which under
1269 1265 Unix uses the resource module to avoid the wraparound problems of
1270 1266 time.clock(). Under Unix, an estimate of time spent on system tasks
1271 1267 is also given (for Windows platforms this is reported as 0.0).
1272 1268
1273 1269 If -t is given, an additional -N<N> option can be given, where <N>
1274 1270 must be an integer indicating how many times you want the script to
1275 1271 run. The final timing report will include total and per run results.
1276 1272
1277 1273 For example (testing the script uniq_stable.py):
1278 1274
1279 1275 In [1]: run -t uniq_stable
1280 1276
1281 1277 IPython CPU timings (estimated):\\
1282 1278 User : 0.19597 s.\\
1283 1279 System: 0.0 s.\\
1284 1280
1285 1281 In [2]: run -t -N5 uniq_stable
1286 1282
1287 1283 IPython CPU timings (estimated):\\
1288 1284 Total runs performed: 5\\
1289 1285 Times : Total Per run\\
1290 1286 User : 0.910862 s, 0.1821724 s.\\
1291 1287 System: 0.0 s, 0.0 s.
1292 1288
1293 1289 -d: run your program under the control of pdb, the Python debugger.
1294 1290 This allows you to execute your program step by step, watch variables,
1295 1291 etc. Internally, what IPython does is similar to calling:
1296 1292
1297 1293 pdb.run('execfile("YOURFILENAME")')
1298 1294
1299 1295 with a breakpoint set on line 1 of your file. You can change the line
1300 1296 number for this automatic breakpoint to be <N> by using the -bN option
1301 1297 (where N must be an integer). For example:
1302 1298
1303 1299 %run -d -b40 myscript
1304 1300
1305 1301 will set the first breakpoint at line 40 in myscript.py. Note that
1306 1302 the first breakpoint must be set on a line which actually does
1307 1303 something (not a comment or docstring) for it to stop execution.
1308 1304
1309 1305 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1310 1306 first enter 'c' (without qoutes) to start execution up to the first
1311 1307 breakpoint.
1312 1308
1313 1309 Entering 'help' gives information about the use of the debugger. You
1314 1310 can easily see pdb's full documentation with "import pdb;pdb.help()"
1315 1311 at a prompt.
1316 1312
1317 1313 -p: run program under the control of the Python profiler module (which
1318 1314 prints a detailed report of execution times, function calls, etc).
1319 1315
1320 1316 You can pass other options after -p which affect the behavior of the
1321 1317 profiler itself. See the docs for %prun for details.
1322 1318
1323 1319 In this mode, the program's variables do NOT propagate back to the
1324 1320 IPython interactive namespace (because they remain in the namespace
1325 1321 where the profiler executes them).
1326 1322
1327 1323 Internally this triggers a call to %prun, see its documentation for
1328 1324 details on the options available specifically for profiling."""
1329 1325
1330 1326 # get arguments and set sys.argv for program to be run.
1331 1327 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1332 1328 mode='list',list_all=1)
1333 1329
1334 1330 try:
1335 1331 filename = get_py_filename(arg_lst[0])
1336 1332 except IndexError:
1337 1333 warn('you must provide at least a filename.')
1338 1334 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1339 1335 return
1340 1336 except IOError,msg:
1341 1337 error(msg)
1342 1338 return
1343 1339
1344 1340 # Control the response to exit() calls made by the script being run
1345 1341 exit_ignore = opts.has_key('e')
1346 1342
1347 1343 # Make sure that the running script gets a proper sys.argv as if it
1348 1344 # were run from a system shell.
1349 1345 save_argv = sys.argv # save it for later restoring
1350 1346 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1351 1347
1352 1348 if opts.has_key('i'):
1353 1349 prog_ns = self.shell.user_ns
1354 1350 __name__save = self.shell.user_ns['__name__']
1355 1351 prog_ns['__name__'] = '__main__'
1356 1352 else:
1357 1353 if opts.has_key('n'):
1358 1354 name = os.path.splitext(os.path.basename(filename))[0]
1359 1355 else:
1360 1356 name = '__main__'
1361 1357 prog_ns = {'__name__':name}
1362 1358
1363 1359 # pickle fix. See iplib for an explanation
1364 1360 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1365 1361
1366 1362 stats = None
1367 1363 try:
1368 1364 if opts.has_key('p'):
1369 1365 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1370 1366 else:
1371 1367 if opts.has_key('d'):
1372 1368 deb = Debugger.Pdb(self.shell.rc.colors)
1373 1369 # reset Breakpoint state, which is moronically kept
1374 1370 # in a class
1375 1371 bdb.Breakpoint.next = 1
1376 1372 bdb.Breakpoint.bplist = {}
1377 1373 bdb.Breakpoint.bpbynumber = [None]
1378 1374 # Set an initial breakpoint to stop execution
1379 1375 maxtries = 10
1380 1376 bp = int(opts.get('b',[1])[0])
1381 1377 checkline = deb.checkline(filename,bp)
1382 1378 if not checkline:
1383 1379 for bp in range(bp+1,bp+maxtries+1):
1384 1380 if deb.checkline(filename,bp):
1385 1381 break
1386 1382 else:
1387 1383 msg = ("\nI failed to find a valid line to set "
1388 1384 "a breakpoint\n"
1389 1385 "after trying up to line: %s.\n"
1390 1386 "Please set a valid breakpoint manually "
1391 1387 "with the -b option." % bp)
1392 1388 error(msg)
1393 1389 return
1394 1390 # if we find a good linenumber, set the breakpoint
1395 1391 deb.do_break('%s:%s' % (filename,bp))
1396 1392 # Start file run
1397 1393 print "NOTE: Enter 'c' at the",
1398 1394 print "ipdb> prompt to start your script."
1399 1395 try:
1400 1396 deb.run('execfile("%s")' % filename,prog_ns)
1401 1397 except:
1402 1398 etype, value, tb = sys.exc_info()
1403 1399 # Skip three frames in the traceback: the %run one,
1404 1400 # one inside bdb.py, and the command-line typed by the
1405 1401 # user (run by exec in pdb itself).
1406 1402 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1407 1403 else:
1408 1404 if runner is None:
1409 1405 runner = self.shell.safe_execfile
1410 1406 if opts.has_key('t'):
1411 1407 try:
1412 1408 nruns = int(opts['N'][0])
1413 1409 if nruns < 1:
1414 1410 error('Number of runs must be >=1')
1415 1411 return
1416 1412 except (KeyError):
1417 1413 nruns = 1
1418 1414 if nruns == 1:
1419 1415 t0 = clock2()
1420 1416 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1421 1417 t1 = clock2()
1422 1418 t_usr = t1[0]-t0[0]
1423 1419 t_sys = t1[1]-t1[1]
1424 1420 print "\nIPython CPU timings (estimated):"
1425 1421 print " User : %10s s." % t_usr
1426 1422 print " System: %10s s." % t_sys
1427 1423 else:
1428 1424 runs = range(nruns)
1429 1425 t0 = clock2()
1430 1426 for nr in runs:
1431 1427 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1432 1428 t1 = clock2()
1433 1429 t_usr = t1[0]-t0[0]
1434 1430 t_sys = t1[1]-t1[1]
1435 1431 print "\nIPython CPU timings (estimated):"
1436 1432 print "Total runs performed:",nruns
1437 1433 print " Times : %10s %10s" % ('Total','Per run')
1438 1434 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1439 1435 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1440 1436
1441 1437 else:
1442 1438 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1443 1439 if opts.has_key('i'):
1444 1440 self.shell.user_ns['__name__'] = __name__save
1445 1441 else:
1446 1442 # update IPython interactive namespace
1447 1443 del prog_ns['__name__']
1448 1444 self.shell.user_ns.update(prog_ns)
1449 1445 finally:
1450 1446 sys.argv = save_argv
1451 1447 return stats
1452 1448
1453 1449 def magic_runlog(self, parameter_s =''):
1454 1450 """Run files as logs.
1455 1451
1456 1452 Usage:\\
1457 1453 %runlog file1 file2 ...
1458 1454
1459 1455 Run the named files (treating them as log files) in sequence inside
1460 1456 the interpreter, and return to the prompt. This is much slower than
1461 1457 %run because each line is executed in a try/except block, but it
1462 1458 allows running files with syntax errors in them.
1463 1459
1464 1460 Normally IPython will guess when a file is one of its own logfiles, so
1465 1461 you can typically use %run even for logs. This shorthand allows you to
1466 1462 force any file to be treated as a log file."""
1467 1463
1468 1464 for f in parameter_s.split():
1469 1465 self.shell.safe_execfile(f,self.shell.user_ns,
1470 1466 self.shell.user_ns,islog=1)
1471 1467
1472 1468 def magic_time(self,parameter_s = ''):
1473 1469 """Time execution of a Python statement or expression.
1474 1470
1475 1471 The CPU and wall clock times are printed, and the value of the
1476 1472 expression (if any) is returned. Note that under Win32, system time
1477 1473 is always reported as 0, since it can not be measured.
1478 1474
1479 1475 This function provides very basic timing functionality. In Python
1480 1476 2.3, the timeit module offers more control and sophistication, but for
1481 1477 now IPython supports Python 2.2, so we can not rely on timeit being
1482 1478 present.
1483 1479
1484 1480 Some examples:
1485 1481
1486 1482 In [1]: time 2**128
1487 1483 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1488 1484 Wall time: 0.00
1489 1485 Out[1]: 340282366920938463463374607431768211456L
1490 1486
1491 1487 In [2]: n = 1000000
1492 1488
1493 1489 In [3]: time sum(range(n))
1494 1490 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1495 1491 Wall time: 1.37
1496 1492 Out[3]: 499999500000L
1497 1493
1498 1494 In [4]: time print 'hello world'
1499 1495 hello world
1500 1496 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1501 1497 Wall time: 0.00
1502 1498 """
1503 1499
1504 1500 # fail immediately if the given expression can't be compiled
1505 1501 try:
1506 1502 mode = 'eval'
1507 1503 code = compile(parameter_s,'<timed eval>',mode)
1508 1504 except SyntaxError:
1509 1505 mode = 'exec'
1510 1506 code = compile(parameter_s,'<timed exec>',mode)
1511 1507 # skew measurement as little as possible
1512 1508 glob = self.shell.user_ns
1513 1509 clk = clock2
1514 1510 wtime = time.time
1515 1511 # time execution
1516 1512 wall_st = wtime()
1517 1513 if mode=='eval':
1518 1514 st = clk()
1519 1515 out = eval(code,glob)
1520 1516 end = clk()
1521 1517 else:
1522 1518 st = clk()
1523 1519 exec code in glob
1524 1520 end = clk()
1525 1521 out = None
1526 1522 wall_end = wtime()
1527 1523 # Compute actual times and report
1528 1524 wall_time = wall_end-wall_st
1529 1525 cpu_user = end[0]-st[0]
1530 1526 cpu_sys = end[1]-st[1]
1531 1527 cpu_tot = cpu_user+cpu_sys
1532 1528 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1533 1529 (cpu_user,cpu_sys,cpu_tot)
1534 1530 print "Wall time: %.2f" % wall_time
1535 1531 return out
1536 1532
1537 1533 def magic_macro(self,parameter_s = ''):
1538 1534 """Define a set of input lines as a macro for future re-execution.
1539 1535
1540 1536 Usage:\\
1541 1537 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1542 1538
1543 1539 This will define a global variable called `name` which is a string
1544 1540 made of joining the slices and lines you specify (n1,n2,... numbers
1545 1541 above) from your input history into a single string. This variable
1546 1542 acts like an automatic function which re-executes those lines as if
1547 1543 you had typed them. You just type 'name' at the prompt and the code
1548 1544 executes.
1549 1545
1550 1546 Note that the slices use the standard Python slicing notation (5:8
1551 1547 means include lines numbered 5,6,7).
1552 1548
1553 1549 For example, if your history contains (%hist prints it):
1554 1550
1555 1551 44: x=1\\
1556 1552 45: y=3\\
1557 1553 46: z=x+y\\
1558 1554 47: print x\\
1559 1555 48: a=5\\
1560 1556 49: print 'x',x,'y',y\\
1561 1557
1562 1558 you can create a macro with lines 44 through 47 (included) and line 49
1563 1559 called my_macro with:
1564 1560
1565 1561 In [51]: %macro my_macro 44:48 49
1566 1562
1567 1563 Now, typing `my_macro` (without quotes) will re-execute all this code
1568 1564 in one pass.
1569 1565
1570 1566 You don't need to give the line-numbers in order, and any given line
1571 1567 number can appear multiple times. You can assemble macros with any
1572 1568 lines from your input history in any order.
1573 1569
1574 1570 The macro is a simple object which holds its value in an attribute,
1575 1571 but IPython's display system checks for macros and executes them as
1576 1572 code instead of printing them when you type their name.
1577 1573
1578 1574 You can view a macro's contents by explicitly printing it with:
1579 1575
1580 1576 'print macro_name'.
1581 1577
1582 1578 For one-off cases which DON'T contain magic function calls in them you
1583 1579 can obtain similar results by explicitly executing slices from your
1584 1580 input history with:
1585 1581
1586 1582 In [60]: exec In[44:48]+In[49]"""
1587 1583
1588 1584 args = parameter_s.split()
1589 1585 name,ranges = args[0], args[1:]
1590 1586 #print 'rng',ranges # dbg
1591 1587 lines = self.extract_input_slices(ranges)
1592 1588 macro = Macro(lines)
1593 1589 self.shell.user_ns.update({name:macro})
1594 1590 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1595 1591 print 'Macro contents:'
1596 print macro
1592 print macro,
1597 1593
1598 1594 def magic_save(self,parameter_s = ''):
1599 1595 """Save a set of lines to a given filename.
1600 1596
1601 1597 Usage:\\
1602 1598 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1603 1599
1604 1600 This function uses the same syntax as %macro for line extraction, but
1605 1601 instead of creating a macro it saves the resulting string to the
1606 1602 filename you specify.
1607 1603
1608 1604 It adds a '.py' extension to the file if you don't do so yourself, and
1609 1605 it asks for confirmation before overwriting existing files."""
1610 1606
1611 1607 args = parameter_s.split()
1612 1608 fname,ranges = args[0], args[1:]
1613 1609 if not fname.endswith('.py'):
1614 1610 fname += '.py'
1615 1611 if os.path.isfile(fname):
1616 1612 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1617 1613 if ans.lower() not in ['y','yes']:
1618 1614 print 'Operation cancelled.'
1619 1615 return
1620 1616 cmds = ''.join(self.extract_input_slices(ranges))
1621 1617 f = file(fname,'w')
1622 1618 f.write(cmds)
1623 1619 f.close()
1624 1620 print 'The following commands were written to file `%s`:' % fname
1625 1621 print cmds
1626 1622
1627 1623 def magic_ed(self,parameter_s = ''):
1628 1624 """Alias to %edit."""
1629 1625 return self.magic_edit(parameter_s)
1630 1626
1631 1627 def magic_edit(self,parameter_s = '',last_call=['','']):
1632 1628 """Bring up an editor and execute the resulting code.
1633 1629
1634 1630 Usage:
1635 1631 %edit [options] [args]
1636 1632
1637 1633 %edit runs IPython's editor hook. The default version of this hook is
1638 1634 set to call the __IPYTHON__.rc.editor command. This is read from your
1639 1635 environment variable $EDITOR. If this isn't found, it will default to
1640 1636 vi under Linux/Unix and to notepad under Windows. See the end of this
1641 1637 docstring for how to change the editor hook.
1642 1638
1643 1639 You can also set the value of this editor via the command line option
1644 1640 '-editor' or in your ipythonrc file. This is useful if you wish to use
1645 1641 specifically for IPython an editor different from your typical default
1646 1642 (and for Windows users who typically don't set environment variables).
1647 1643
1648 1644 This command allows you to conveniently edit multi-line code right in
1649 1645 your IPython session.
1650 1646
1651 1647 If called without arguments, %edit opens up an empty editor with a
1652 1648 temporary file and will execute the contents of this file when you
1653 1649 close it (don't forget to save it!).
1654 1650
1655 1651 Options:
1656 1652
1657 1653 -p: this will call the editor with the same data as the previous time
1658 1654 it was used, regardless of how long ago (in your current session) it
1659 1655 was.
1660 1656
1661 1657 -x: do not execute the edited code immediately upon exit. This is
1662 1658 mainly useful if you are editing programs which need to be called with
1663 1659 command line arguments, which you can then do using %run.
1664 1660
1665 1661 Arguments:
1666 1662
1667 1663 If arguments are given, the following possibilites exist:
1668 1664
1669 1665 - The arguments are numbers or pairs of colon-separated numbers (like
1670 1666 1 4:8 9). These are interpreted as lines of previous input to be
1671 1667 loaded into the editor. The syntax is the same of the %macro command.
1672 1668
1673 1669 - If the argument doesn't start with a number, it is evaluated as a
1674 1670 variable and its contents loaded into the editor. You can thus edit
1675 1671 any string which contains python code (including the result of
1676 1672 previous edits).
1677 1673
1678 1674 - If the argument is the name of an object (other than a string),
1679 1675 IPython will try to locate the file where it was defined and open the
1680 1676 editor at the point where it is defined. You can use `%edit function`
1681 1677 to load an editor exactly at the point where 'function' is defined,
1682 1678 edit it and have the file be executed automatically.
1683 1679
1684 1680 Note: opening at an exact line is only supported under Unix, and some
1685 1681 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1686 1682 '+NUMBER' parameter necessary for this feature. Good editors like
1687 1683 (X)Emacs, vi, jed, pico and joe all do.
1688 1684
1689 1685 - If the argument is not found as a variable, IPython will look for a
1690 1686 file with that name (adding .py if necessary) and load it into the
1691 1687 editor. It will execute its contents with execfile() when you exit,
1692 1688 loading any code in the file into your interactive namespace.
1693 1689
1694 1690 After executing your code, %edit will return as output the code you
1695 1691 typed in the editor (except when it was an existing file). This way
1696 1692 you can reload the code in further invocations of %edit as a variable,
1697 1693 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1698 1694 the output.
1699 1695
1700 1696 Note that %edit is also available through the alias %ed.
1701 1697
1702 1698 This is an example of creating a simple function inside the editor and
1703 1699 then modifying it. First, start up the editor:
1704 1700
1705 1701 In [1]: ed\\
1706 1702 Editing... done. Executing edited code...\\
1707 1703 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1708 1704
1709 1705 We can then call the function foo():
1710 1706
1711 1707 In [2]: foo()\\
1712 1708 foo() was defined in an editing session
1713 1709
1714 1710 Now we edit foo. IPython automatically loads the editor with the
1715 1711 (temporary) file where foo() was previously defined:
1716 1712
1717 1713 In [3]: ed foo\\
1718 1714 Editing... done. Executing edited code...
1719 1715
1720 1716 And if we call foo() again we get the modified version:
1721 1717
1722 1718 In [4]: foo()\\
1723 1719 foo() has now been changed!
1724 1720
1725 1721 Here is an example of how to edit a code snippet successive
1726 1722 times. First we call the editor:
1727 1723
1728 1724 In [8]: ed\\
1729 1725 Editing... done. Executing edited code...\\
1730 1726 hello\\
1731 1727 Out[8]: "print 'hello'\\n"
1732 1728
1733 1729 Now we call it again with the previous output (stored in _):
1734 1730
1735 1731 In [9]: ed _\\
1736 1732 Editing... done. Executing edited code...\\
1737 1733 hello world\\
1738 1734 Out[9]: "print 'hello world'\\n"
1739 1735
1740 1736 Now we call it with the output #8 (stored in _8, also as Out[8]):
1741 1737
1742 1738 In [10]: ed _8\\
1743 1739 Editing... done. Executing edited code...\\
1744 1740 hello again\\
1745 1741 Out[10]: "print 'hello again'\\n"
1746 1742
1747 1743
1748 1744 Changing the default editor hook:
1749 1745
1750 1746 If you wish to write your own editor hook, you can put it in a
1751 1747 configuration file which you load at startup time. The default hook
1752 1748 is defined in the IPython.hooks module, and you can use that as a
1753 1749 starting example for further modifications. That file also has
1754 1750 general instructions on how to set a new hook for use once you've
1755 1751 defined it."""
1756 1752
1757 1753 # FIXME: This function has become a convoluted mess. It needs a
1758 1754 # ground-up rewrite with clean, simple logic.
1759 1755
1760 1756 def make_filename(arg):
1761 1757 "Make a filename from the given args"
1762 1758 try:
1763 1759 filename = get_py_filename(arg)
1764 1760 except IOError:
1765 1761 if args.endswith('.py'):
1766 1762 filename = arg
1767 1763 else:
1768 1764 filename = None
1769 1765 return filename
1770 1766
1771 1767 # custom exceptions
1772 1768 class DataIsObject(Exception): pass
1773 1769
1774 1770 opts,args = self.parse_options(parameter_s,'px')
1775 1771
1776 1772 # Default line number value
1777 1773 lineno = None
1778 1774 if opts.has_key('p'):
1779 1775 args = '_%s' % last_call[0]
1780 1776 if not self.shell.user_ns.has_key(args):
1781 1777 args = last_call[1]
1782 1778
1783 1779 # use last_call to remember the state of the previous call, but don't
1784 1780 # let it be clobbered by successive '-p' calls.
1785 1781 try:
1786 1782 last_call[0] = self.shell.outputcache.prompt_count
1787 1783 if not opts.has_key('p'):
1788 1784 last_call[1] = parameter_s
1789 1785 except:
1790 1786 pass
1791 1787
1792 1788 # by default this is done with temp files, except when the given
1793 1789 # arg is a filename
1794 1790 use_temp = 1
1795 1791
1796 1792 if re.match(r'\d',args):
1797 1793 # Mode where user specifies ranges of lines, like in %macro.
1798 1794 # This means that you can't edit files whose names begin with
1799 1795 # numbers this way. Tough.
1800 1796 ranges = args.split()
1801 1797 data = ''.join(self.extract_input_slices(ranges))
1802 1798 elif args.endswith('.py'):
1803 1799 filename = make_filename(args)
1804 1800 data = ''
1805 1801 use_temp = 0
1806 1802 elif args:
1807 1803 try:
1808 1804 # Load the parameter given as a variable. If not a string,
1809 1805 # process it as an object instead (below)
1810 1806
1811 1807 #print '*** args',args,'type',type(args) # dbg
1812 1808 data = eval(args,self.shell.user_ns)
1813 1809 if not type(data) in StringTypes:
1814 1810 raise DataIsObject
1815 1811 except (NameError,SyntaxError):
1816 1812 # given argument is not a variable, try as a filename
1817 1813 filename = make_filename(args)
1818 1814 if filename is None:
1819 1815 warn("Argument given (%s) can't be found as a variable "
1820 1816 "or as a filename." % args)
1821 1817 return
1822 1818 data = ''
1823 1819 use_temp = 0
1824 1820 except DataIsObject:
1825 1821 # For objects, try to edit the file where they are defined
1826 1822 try:
1827 1823 filename = inspect.getabsfile(data)
1828 1824 datafile = 1
1829 1825 except TypeError:
1830 1826 filename = make_filename(args)
1831 1827 datafile = 1
1832 1828 warn('Could not find file where `%s` is defined.\n'
1833 1829 'Opening a file named `%s`' % (args,filename))
1834 1830 # Now, make sure we can actually read the source (if it was in
1835 1831 # a temp file it's gone by now).
1836 1832 if datafile:
1837 1833 try:
1838 1834 lineno = inspect.getsourcelines(data)[1]
1839 1835 except IOError:
1840 1836 filename = make_filename(args)
1841 1837 if filename is None:
1842 1838 warn('The file `%s` where `%s` was defined cannot '
1843 1839 'be read.' % (filename,data))
1844 1840 return
1845 1841 use_temp = 0
1846 1842 else:
1847 1843 data = ''
1848 1844
1849 1845 if use_temp:
1850 1846 filename = tempfile.mktemp('.py')
1851 1847 self.shell.tempfiles.append(filename)
1852 1848
1853 1849 if data and use_temp:
1854 1850 tmp_file = open(filename,'w')
1855 1851 tmp_file.write(data)
1856 1852 tmp_file.close()
1857 1853
1858 1854 # do actual editing here
1859 1855 print 'Editing...',
1860 1856 sys.stdout.flush()
1861 1857 self.shell.hooks.editor(filename,lineno)
1862 1858 if opts.has_key('x'): # -x prevents actual execution
1863 1859 print
1864 1860 else:
1865 1861 print 'done. Executing edited code...'
1866 1862 try:
1867 1863 self.shell.safe_execfile(filename,self.shell.user_ns)
1868 1864 except IOError,msg:
1869 1865 if msg.filename == filename:
1870 1866 warn('File not found. Did you forget to save?')
1871 1867 return
1872 1868 else:
1873 1869 self.shell.showtraceback()
1874 1870 except:
1875 1871 self.shell.showtraceback()
1876 1872 if use_temp:
1877 1873 contents = open(filename).read()
1878 1874 return contents
1879 1875
1880 1876 def magic_xmode(self,parameter_s = ''):
1881 1877 """Switch modes for the exception handlers.
1882 1878
1883 1879 Valid modes: Plain, Context and Verbose.
1884 1880
1885 1881 If called without arguments, acts as a toggle."""
1886 1882
1887 1883 def xmode_switch_err(name):
1888 1884 warn('Error changing %s exception modes.\n%s' %
1889 1885 (name,sys.exc_info()[1]))
1890 1886
1891 1887 shell = self.shell
1892 1888 new_mode = parameter_s.strip().capitalize()
1893 1889 try:
1894 1890 shell.InteractiveTB.set_mode(mode=new_mode)
1895 1891 print 'Exception reporting mode:',shell.InteractiveTB.mode
1896 1892 except:
1897 1893 xmode_switch_err('user')
1898 1894
1899 1895 # threaded shells use a special handler in sys.excepthook
1900 1896 if shell.isthreaded:
1901 1897 try:
1902 1898 shell.sys_excepthook.set_mode(mode=new_mode)
1903 1899 except:
1904 1900 xmode_switch_err('threaded')
1905 1901
1906 1902 def magic_colors(self,parameter_s = ''):
1907 1903 """Switch color scheme for prompts, info system and exception handlers.
1908 1904
1909 1905 Currently implemented schemes: NoColor, Linux, LightBG.
1910 1906
1911 1907 Color scheme names are not case-sensitive."""
1912 1908
1913 1909 def color_switch_err(name):
1914 1910 warn('Error changing %s color schemes.\n%s' %
1915 1911 (name,sys.exc_info()[1]))
1916 1912
1917 1913
1918 1914 new_scheme = parameter_s.strip()
1919 1915 if not new_scheme:
1920 1916 print 'You must specify a color scheme.'
1921 1917 return
1922 1918 # Under Windows, check for Gary Bishop's readline, which is necessary
1923 1919 # for ANSI coloring
1924 1920 if os.name in ['nt','dos']:
1925 1921 try:
1926 1922 import readline
1927 1923 except ImportError:
1928 1924 has_readline = 0
1929 1925 else:
1930 1926 try:
1931 1927 readline.GetOutputFile()
1932 1928 except AttributeError:
1933 1929 has_readline = 0
1934 1930 else:
1935 1931 has_readline = 1
1936 1932 if not has_readline:
1937 1933 msg = """\
1938 1934 Proper color support under MS Windows requires Gary Bishop's readline library.
1939 1935 You can find it at:
1940 1936 http://sourceforge.net/projects/uncpythontools
1941 1937 Gary's readline needs the ctypes module, from:
1942 1938 http://starship.python.net/crew/theller/ctypes
1943 1939
1944 1940 Defaulting color scheme to 'NoColor'"""
1945 1941 new_scheme = 'NoColor'
1946 1942 warn(msg)
1947 1943 # local shortcut
1948 1944 shell = self.shell
1949 1945
1950 1946 # Set prompt colors
1951 1947 try:
1952 1948 shell.outputcache.set_colors(new_scheme)
1953 1949 except:
1954 1950 color_switch_err('prompt')
1955 1951 else:
1956 1952 shell.rc.colors = \
1957 1953 shell.outputcache.color_table.active_scheme_name
1958 1954 # Set exception colors
1959 1955 try:
1960 1956 shell.InteractiveTB.set_colors(scheme = new_scheme)
1961 1957 shell.SyntaxTB.set_colors(scheme = new_scheme)
1962 1958 except:
1963 1959 color_switch_err('exception')
1964 1960
1965 1961 # threaded shells use a verbose traceback in sys.excepthook
1966 1962 if shell.isthreaded:
1967 1963 try:
1968 1964 shell.sys_excepthook.set_colors(scheme=new_scheme)
1969 1965 except:
1970 1966 color_switch_err('system exception handler')
1971 1967
1972 1968 # Set info (for 'object?') colors
1973 1969 if shell.rc.color_info:
1974 1970 try:
1975 1971 shell.inspector.set_active_scheme(new_scheme)
1976 1972 except:
1977 1973 color_switch_err('object inspector')
1978 1974 else:
1979 1975 shell.inspector.set_active_scheme('NoColor')
1980 1976
1981 1977 def magic_color_info(self,parameter_s = ''):
1982 1978 """Toggle color_info.
1983 1979
1984 1980 The color_info configuration parameter controls whether colors are
1985 1981 used for displaying object details (by things like %psource, %pfile or
1986 1982 the '?' system). This function toggles this value with each call.
1987 1983
1988 1984 Note that unless you have a fairly recent pager (less works better
1989 1985 than more) in your system, using colored object information displays
1990 1986 will not work properly. Test it and see."""
1991 1987
1992 1988 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1993 1989 self.magic_colors(self.shell.rc.colors)
1994 1990 print 'Object introspection functions have now coloring:',
1995 1991 print ['OFF','ON'][self.shell.rc.color_info]
1996 1992
1997 1993 def magic_Pprint(self, parameter_s=''):
1998 1994 """Toggle pretty printing on/off."""
1999 1995
2000 1996 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2001 1997 print 'Pretty printing has been turned', \
2002 1998 ['OFF','ON'][self.shell.outputcache.Pprint]
2003 1999
2004 2000 def magic_exit(self, parameter_s=''):
2005 2001 """Exit IPython, confirming if configured to do so.
2006 2002
2007 2003 You can configure whether IPython asks for confirmation upon exit by
2008 2004 setting the confirm_exit flag in the ipythonrc file."""
2009 2005
2010 2006 self.shell.exit()
2011 2007
2012 2008 def magic_quit(self, parameter_s=''):
2013 2009 """Exit IPython, confirming if configured to do so (like %exit)"""
2014 2010
2015 2011 self.shell.exit()
2016 2012
2017 2013 def magic_Exit(self, parameter_s=''):
2018 2014 """Exit IPython without confirmation."""
2019 2015
2020 2016 self.shell.exit_now = True
2021 2017
2022 2018 def magic_Quit(self, parameter_s=''):
2023 2019 """Exit IPython without confirmation (like %Exit)."""
2024 2020
2025 2021 self.shell.exit_now = True
2026 2022
2027 2023 #......................................................................
2028 2024 # Functions to implement unix shell-type things
2029 2025
2030 2026 def magic_alias(self, parameter_s = ''):
2031 2027 """Define an alias for a system command.
2032 2028
2033 2029 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2034 2030
2035 2031 Then, typing 'alias_name params' will execute the system command 'cmd
2036 2032 params' (from your underlying operating system).
2037 2033
2038 2034 Aliases have lower precedence than magic functions and Python normal
2039 2035 variables, so if 'foo' is both a Python variable and an alias, the
2040 2036 alias can not be executed until 'del foo' removes the Python variable.
2041 2037
2042 2038 You can use the %l specifier in an alias definition to represent the
2043 2039 whole line when the alias is called. For example:
2044 2040
2045 2041 In [2]: alias all echo "Input in brackets: <%l>"\\
2046 2042 In [3]: all hello world\\
2047 2043 Input in brackets: <hello world>
2048 2044
2049 2045 You can also define aliases with parameters using %s specifiers (one
2050 2046 per parameter):
2051 2047
2052 2048 In [1]: alias parts echo first %s second %s\\
2053 2049 In [2]: %parts A B\\
2054 2050 first A second B\\
2055 2051 In [3]: %parts A\\
2056 2052 Incorrect number of arguments: 2 expected.\\
2057 2053 parts is an alias to: 'echo first %s second %s'
2058 2054
2059 2055 Note that %l and %s are mutually exclusive. You can only use one or
2060 2056 the other in your aliases.
2061 2057
2062 2058 Aliases expand Python variables just like system calls using ! or !!
2063 2059 do: all expressions prefixed with '$' get expanded. For details of
2064 2060 the semantic rules, see PEP-215:
2065 2061 http://www.python.org/peps/pep-0215.html. This is the library used by
2066 2062 IPython for variable expansion. If you want to access a true shell
2067 2063 variable, an extra $ is necessary to prevent its expansion by IPython:
2068 2064
2069 2065 In [6]: alias show echo\\
2070 2066 In [7]: PATH='A Python string'\\
2071 2067 In [8]: show $PATH\\
2072 2068 A Python string\\
2073 2069 In [9]: show $$PATH\\
2074 2070 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2075 2071
2076 2072 You can use the alias facility to acess all of $PATH. See the %rehash
2077 2073 and %rehashx functions, which automatically create aliases for the
2078 2074 contents of your $PATH.
2079 2075
2080 2076 If called with no parameters, %alias prints the current alias table."""
2081 2077
2082 2078 par = parameter_s.strip()
2083 2079 if not par:
2084 2080 if self.shell.rc.automagic:
2085 2081 prechar = ''
2086 2082 else:
2087 2083 prechar = self.shell.ESC_MAGIC
2088 2084 print 'Alias\t\tSystem Command\n'+'-'*30
2089 2085 atab = self.shell.alias_table
2090 2086 aliases = atab.keys()
2091 2087 aliases.sort()
2092 2088 for alias in aliases:
2093 2089 print prechar+alias+'\t\t'+atab[alias][1]
2094 2090 print '-'*30+'\nTotal number of aliases:',len(aliases)
2095 2091 return
2096 2092 try:
2097 2093 alias,cmd = par.split(None,1)
2098 2094 except:
2099 2095 print OInspect.getdoc(self.magic_alias)
2100 2096 else:
2101 2097 nargs = cmd.count('%s')
2102 2098 if nargs>0 and cmd.find('%l')>=0:
2103 2099 error('The %s and %l specifiers are mutually exclusive '
2104 2100 'in alias definitions.')
2105 2101 else: # all looks OK
2106 2102 self.shell.alias_table[alias] = (nargs,cmd)
2107 2103 self.shell.alias_table_validate(verbose=1)
2108 2104 # end magic_alias
2109 2105
2110 2106 def magic_unalias(self, parameter_s = ''):
2111 2107 """Remove an alias"""
2112 2108
2113 2109 aname = parameter_s.strip()
2114 2110 if aname in self.shell.alias_table:
2115 2111 del self.shell.alias_table[aname]
2116 2112
2117 2113 def magic_rehash(self, parameter_s = ''):
2118 2114 """Update the alias table with all entries in $PATH.
2119 2115
2120 2116 This version does no checks on execute permissions or whether the
2121 2117 contents of $PATH are truly files (instead of directories or something
2122 2118 else). For such a safer (but slower) version, use %rehashx."""
2123 2119
2124 2120 # This function (and rehashx) manipulate the alias_table directly
2125 2121 # rather than calling magic_alias, for speed reasons. A rehash on a
2126 2122 # typical Linux box involves several thousand entries, so efficiency
2127 2123 # here is a top concern.
2128 2124
2129 2125 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2130 2126 alias_table = self.shell.alias_table
2131 2127 for pdir in path:
2132 2128 for ff in os.listdir(pdir):
2133 2129 # each entry in the alias table must be (N,name), where
2134 2130 # N is the number of positional arguments of the alias.
2135 2131 alias_table[ff] = (0,ff)
2136 2132 # Make sure the alias table doesn't contain keywords or builtins
2137 2133 self.shell.alias_table_validate()
2138 2134 # Call again init_auto_alias() so we get 'rm -i' and other modified
2139 2135 # aliases since %rehash will probably clobber them
2140 2136 self.shell.init_auto_alias()
2141 2137
2142 2138 def magic_rehashx(self, parameter_s = ''):
2143 2139 """Update the alias table with all executable files in $PATH.
2144 2140
2145 2141 This version explicitly checks that every entry in $PATH is a file
2146 2142 with execute access (os.X_OK), so it is much slower than %rehash.
2147 2143
2148 2144 Under Windows, it checks executability as a match agains a
2149 2145 '|'-separated string of extensions, stored in the IPython config
2150 2146 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2151 2147
2152 2148 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2153 2149 alias_table = self.shell.alias_table
2154 2150
2155 2151 if os.name == 'posix':
2156 2152 isexec = lambda fname:os.path.isfile(fname) and \
2157 2153 os.access(fname,os.X_OK)
2158 2154 else:
2159 2155
2160 2156 try:
2161 2157 winext = os.environ['pathext'].replace(';','|').replace('.','')
2162 2158 except KeyError:
2163 2159 winext = 'exe|com|bat'
2164 2160
2165 2161 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2166 2162 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2167 2163 savedir = os.getcwd()
2168 2164 try:
2169 2165 # write the whole loop for posix/Windows so we don't have an if in
2170 2166 # the innermost part
2171 2167 if os.name == 'posix':
2172 2168 for pdir in path:
2173 2169 os.chdir(pdir)
2174 2170 for ff in os.listdir(pdir):
2175 2171 if isexec(ff):
2176 2172 # each entry in the alias table must be (N,name),
2177 2173 # where N is the number of positional arguments of the
2178 2174 # alias.
2179 2175 alias_table[ff] = (0,ff)
2180 2176 else:
2181 2177 for pdir in path:
2182 2178 os.chdir(pdir)
2183 2179 for ff in os.listdir(pdir):
2184 2180 if isexec(ff):
2185 2181 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2186 2182 # Make sure the alias table doesn't contain keywords or builtins
2187 2183 self.shell.alias_table_validate()
2188 2184 # Call again init_auto_alias() so we get 'rm -i' and other
2189 2185 # modified aliases since %rehashx will probably clobber them
2190 2186 self.shell.init_auto_alias()
2191 2187 finally:
2192 2188 os.chdir(savedir)
2193 2189
2194 2190 def magic_pwd(self, parameter_s = ''):
2195 2191 """Return the current working directory path."""
2196 2192 return os.getcwd()
2197 2193
2198 2194 def magic_cd(self, parameter_s=''):
2199 2195 """Change the current working directory.
2200 2196
2201 2197 This command automatically maintains an internal list of directories
2202 2198 you visit during your IPython session, in the variable _dh. The
2203 2199 command %dhist shows this history nicely formatted.
2204 2200
2205 2201 Usage:
2206 2202
2207 2203 cd 'dir': changes to directory 'dir'.
2208 2204
2209 2205 cd -: changes to the last visited directory.
2210 2206
2211 2207 cd -<n>: changes to the n-th directory in the directory history.
2212 2208
2213 2209 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2214 2210 (note: cd <bookmark_name> is enough if there is no
2215 2211 directory <bookmark_name>, but a bookmark with the name exists.)
2216 2212
2217 2213 Options:
2218 2214
2219 2215 -q: quiet. Do not print the working directory after the cd command is
2220 2216 executed. By default IPython's cd command does print this directory,
2221 2217 since the default prompts do not display path information.
2222 2218
2223 2219 Note that !cd doesn't work for this purpose because the shell where
2224 2220 !command runs is immediately discarded after executing 'command'."""
2225 2221
2226 2222 parameter_s = parameter_s.strip()
2227 2223 bkms = self.shell.persist.get("bookmarks",{})
2228 2224
2229 2225 numcd = re.match(r'(-)(\d+)$',parameter_s)
2230 2226 # jump in directory history by number
2231 2227 if numcd:
2232 2228 nn = int(numcd.group(2))
2233 2229 try:
2234 2230 ps = self.shell.user_ns['_dh'][nn]
2235 2231 except IndexError:
2236 2232 print 'The requested directory does not exist in history.'
2237 2233 return
2238 2234 else:
2239 2235 opts = {}
2240 2236 else:
2241 2237 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2242 2238 # jump to previous
2243 2239 if ps == '-':
2244 2240 try:
2245 2241 ps = self.shell.user_ns['_dh'][-2]
2246 2242 except IndexError:
2247 2243 print 'No previous directory to change to.'
2248 2244 return
2249 2245 # jump to bookmark
2250 2246 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2251 2247 if bkms.has_key(ps):
2252 2248 target = bkms[ps]
2253 2249 print '(bookmark:%s) -> %s' % (ps,target)
2254 2250 ps = target
2255 2251 else:
2256 2252 if bkms:
2257 2253 error("Bookmark '%s' not found. "
2258 2254 "Use '%bookmark -l' to see your bookmarks." % ps)
2259 2255 else:
2260 2256 print "Bookmarks not set - use %bookmark <bookmarkname>"
2261 2257 return
2262 2258
2263 2259 # at this point ps should point to the target dir
2264 2260 if ps:
2265 2261 try:
2266 2262 os.chdir(os.path.expanduser(ps))
2267 2263 except OSError:
2268 2264 print sys.exc_info()[1]
2269 2265 else:
2270 2266 self.shell.user_ns['_dh'].append(os.getcwd())
2271 2267 else:
2272 2268 os.chdir(self.shell.home_dir)
2273 2269 self.shell.user_ns['_dh'].append(os.getcwd())
2274 2270 if not 'q' in opts:
2275 2271 print self.shell.user_ns['_dh'][-1]
2276 2272
2277 2273 def magic_dhist(self, parameter_s=''):
2278 2274 """Print your history of visited directories.
2279 2275
2280 2276 %dhist -> print full history\\
2281 2277 %dhist n -> print last n entries only\\
2282 2278 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2283 2279
2284 2280 This history is automatically maintained by the %cd command, and
2285 2281 always available as the global list variable _dh. You can use %cd -<n>
2286 2282 to go to directory number <n>."""
2287 2283
2288 2284 dh = self.shell.user_ns['_dh']
2289 2285 if parameter_s:
2290 2286 try:
2291 2287 args = map(int,parameter_s.split())
2292 2288 except:
2293 2289 self.arg_err(Magic.magic_dhist)
2294 2290 return
2295 2291 if len(args) == 1:
2296 2292 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2297 2293 elif len(args) == 2:
2298 2294 ini,fin = args
2299 2295 else:
2300 2296 self.arg_err(Magic.magic_dhist)
2301 2297 return
2302 2298 else:
2303 2299 ini,fin = 0,len(dh)
2304 2300 nlprint(dh,
2305 2301 header = 'Directory history (kept in _dh)',
2306 2302 start=ini,stop=fin)
2307 2303
2308 2304 def magic_env(self, parameter_s=''):
2309 2305 """List environment variables."""
2310 2306
2311 2307 return os.environ.data
2312 2308
2313 2309 def magic_pushd(self, parameter_s=''):
2314 2310 """Place the current dir on stack and change directory.
2315 2311
2316 2312 Usage:\\
2317 2313 %pushd ['dirname']
2318 2314
2319 2315 %pushd with no arguments does a %pushd to your home directory.
2320 2316 """
2321 2317 if parameter_s == '': parameter_s = '~'
2322 2318 dir_s = self.shell.dir_stack
2323 2319 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2324 2320 os.path.expanduser(self.shell.dir_stack[0]):
2325 2321 try:
2326 2322 self.magic_cd(parameter_s)
2327 2323 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2328 2324 self.magic_dirs()
2329 2325 except:
2330 2326 print 'Invalid directory'
2331 2327 else:
2332 2328 print 'You are already there!'
2333 2329
2334 2330 def magic_popd(self, parameter_s=''):
2335 2331 """Change to directory popped off the top of the stack.
2336 2332 """
2337 2333 if len (self.shell.dir_stack) > 1:
2338 2334 self.shell.dir_stack.pop(0)
2339 2335 self.magic_cd(self.shell.dir_stack[0])
2340 2336 print self.shell.dir_stack[0]
2341 2337 else:
2342 2338 print "You can't remove the starting directory from the stack:",\
2343 2339 self.shell.dir_stack
2344 2340
2345 2341 def magic_dirs(self, parameter_s=''):
2346 2342 """Return the current directory stack."""
2347 2343
2348 2344 return self.shell.dir_stack[:]
2349 2345
2350 2346 def magic_sc(self, parameter_s=''):
2351 2347 """Shell capture - execute a shell command and capture its output.
2352 2348
2353 2349 %sc [options] varname=command
2354 2350
2355 2351 IPython will run the given command using commands.getoutput(), and
2356 2352 will then update the user's interactive namespace with a variable
2357 2353 called varname, containing the value of the call. Your command can
2358 2354 contain shell wildcards, pipes, etc.
2359 2355
2360 2356 The '=' sign in the syntax is mandatory, and the variable name you
2361 2357 supply must follow Python's standard conventions for valid names.
2362 2358
2363 2359 Options:
2364 2360
2365 2361 -l: list output. Split the output on newlines into a list before
2366 2362 assigning it to the given variable. By default the output is stored
2367 2363 as a single string.
2368 2364
2369 2365 -v: verbose. Print the contents of the variable.
2370 2366
2371 2367 In most cases you should not need to split as a list, because the
2372 2368 returned value is a special type of string which can automatically
2373 2369 provide its contents either as a list (split on newlines) or as a
2374 2370 space-separated string. These are convenient, respectively, either
2375 2371 for sequential processing or to be passed to a shell command.
2376 2372
2377 2373 For example:
2378 2374
2379 2375 # Capture into variable a
2380 2376 In [9]: sc a=ls *py
2381 2377
2382 2378 # a is a string with embedded newlines
2383 2379 In [10]: a
2384 2380 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2385 2381
2386 2382 # which can be seen as a list:
2387 2383 In [11]: a.l
2388 2384 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2389 2385
2390 2386 # or as a whitespace-separated string:
2391 2387 In [12]: a.s
2392 2388 Out[12]: 'setup.py win32_manual_post_install.py'
2393 2389
2394 2390 # a.s is useful to pass as a single command line:
2395 2391 In [13]: !wc -l $a.s
2396 2392 146 setup.py
2397 2393 130 win32_manual_post_install.py
2398 2394 276 total
2399 2395
2400 2396 # while the list form is useful to loop over:
2401 2397 In [14]: for f in a.l:
2402 2398 ....: !wc -l $f
2403 2399 ....:
2404 2400 146 setup.py
2405 2401 130 win32_manual_post_install.py
2406 2402
2407 2403 Similiarly, the lists returned by the -l option are also special, in
2408 2404 the sense that you can equally invoke the .s attribute on them to
2409 2405 automatically get a whitespace-separated string from their contents:
2410 2406
2411 2407 In [1]: sc -l b=ls *py
2412 2408
2413 2409 In [2]: b
2414 2410 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2415 2411
2416 2412 In [3]: b.s
2417 2413 Out[3]: 'setup.py win32_manual_post_install.py'
2418 2414
2419 2415 In summary, both the lists and strings used for ouptut capture have
2420 2416 the following special attributes:
2421 2417
2422 2418 .l (or .list) : value as list.
2423 2419 .n (or .nlstr): value as newline-separated string.
2424 2420 .s (or .spstr): value as space-separated string.
2425 2421 """
2426 2422
2427 2423 opts,args = self.parse_options(parameter_s,'lv')
2428 2424 # Try to get a variable name and command to run
2429 2425 try:
2430 2426 # the variable name must be obtained from the parse_options
2431 2427 # output, which uses shlex.split to strip options out.
2432 2428 var,_ = args.split('=',1)
2433 2429 var = var.strip()
2434 2430 # But the the command has to be extracted from the original input
2435 2431 # parameter_s, not on what parse_options returns, to avoid the
2436 2432 # quote stripping which shlex.split performs on it.
2437 2433 _,cmd = parameter_s.split('=',1)
2438 2434 except ValueError:
2439 2435 var,cmd = '',''
2440 2436 if not var:
2441 2437 error('you must specify a variable to assign the command to.')
2442 2438 return
2443 2439 # If all looks ok, proceed
2444 2440 out,err = self.shell.getoutputerror(cmd)
2445 2441 if err:
2446 2442 print >> Term.cerr,err
2447 2443 if opts.has_key('l'):
2448 2444 out = SList(out.split('\n'))
2449 2445 else:
2450 2446 out = LSString(out)
2451 2447 if opts.has_key('v'):
2452 2448 print '%s ==\n%s' % (var,pformat(out))
2453 2449 self.shell.user_ns.update({var:out})
2454 2450
2455 2451 def magic_sx(self, parameter_s=''):
2456 2452 """Shell execute - run a shell command and capture its output.
2457 2453
2458 2454 %sx command
2459 2455
2460 2456 IPython will run the given command using commands.getoutput(), and
2461 2457 return the result formatted as a list (split on '\\n'). Since the
2462 2458 output is _returned_, it will be stored in ipython's regular output
2463 2459 cache Out[N] and in the '_N' automatic variables.
2464 2460
2465 2461 Notes:
2466 2462
2467 2463 1) If an input line begins with '!!', then %sx is automatically
2468 2464 invoked. That is, while:
2469 2465 !ls
2470 2466 causes ipython to simply issue system('ls'), typing
2471 2467 !!ls
2472 2468 is a shorthand equivalent to:
2473 2469 %sx ls
2474 2470
2475 2471 2) %sx differs from %sc in that %sx automatically splits into a list,
2476 2472 like '%sc -l'. The reason for this is to make it as easy as possible
2477 2473 to process line-oriented shell output via further python commands.
2478 2474 %sc is meant to provide much finer control, but requires more
2479 2475 typing.
2480 2476
2481 2477 3) Just like %sc -l, this is a list with special attributes:
2482 2478
2483 2479 .l (or .list) : value as list.
2484 2480 .n (or .nlstr): value as newline-separated string.
2485 2481 .s (or .spstr): value as whitespace-separated string.
2486 2482
2487 2483 This is very useful when trying to use such lists as arguments to
2488 2484 system commands."""
2489 2485
2490 2486 if parameter_s:
2491 2487 out,err = self.shell.getoutputerror(parameter_s)
2492 2488 if err:
2493 2489 print >> Term.cerr,err
2494 2490 return SList(out.split('\n'))
2495 2491
2496 2492 def magic_bg(self, parameter_s=''):
2497 2493 """Run a job in the background, in a separate thread.
2498 2494
2499 2495 For example,
2500 2496
2501 2497 %bg myfunc(x,y,z=1)
2502 2498
2503 2499 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2504 2500 execution starts, a message will be printed indicating the job
2505 2501 number. If your job number is 5, you can use
2506 2502
2507 2503 myvar = jobs.result(5) or myvar = jobs[5].result
2508 2504
2509 2505 to assign this result to variable 'myvar'.
2510 2506
2511 2507 IPython has a job manager, accessible via the 'jobs' object. You can
2512 2508 type jobs? to get more information about it, and use jobs.<TAB> to see
2513 2509 its attributes. All attributes not starting with an underscore are
2514 2510 meant for public use.
2515 2511
2516 2512 In particular, look at the jobs.new() method, which is used to create
2517 2513 new jobs. This magic %bg function is just a convenience wrapper
2518 2514 around jobs.new(), for expression-based jobs. If you want to create a
2519 2515 new job with an explicit function object and arguments, you must call
2520 2516 jobs.new() directly.
2521 2517
2522 2518 The jobs.new docstring also describes in detail several important
2523 2519 caveats associated with a thread-based model for background job
2524 2520 execution. Type jobs.new? for details.
2525 2521
2526 2522 You can check the status of all jobs with jobs.status().
2527 2523
2528 2524 The jobs variable is set by IPython into the Python builtin namespace.
2529 2525 If you ever declare a variable named 'jobs', you will shadow this
2530 2526 name. You can either delete your global jobs variable to regain
2531 2527 access to the job manager, or make a new name and assign it manually
2532 2528 to the manager (stored in IPython's namespace). For example, to
2533 2529 assign the job manager to the Jobs name, use:
2534 2530
2535 2531 Jobs = __builtins__.jobs"""
2536 2532
2537 2533 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2538 2534
2539 2535 def magic_store(self, parameter_s=''):
2540 2536 """Lightweight persistence for python variables.
2541 2537
2542 2538 Example:
2543 2539
2544 2540 ville@badger[~]|1> A = ['hello',10,'world']\\
2545 2541 ville@badger[~]|2> %store A\\
2546 2542 ville@badger[~]|3> Exit
2547 2543
2548 2544 (IPython session is closed and started again...)
2549 2545
2550 2546 ville@badger:~$ ipython -p pysh\\
2551 2547 ville@badger[~]|1> print A
2552 2548
2553 2549 ['hello', 10, 'world']
2554 2550
2555 2551 Usage:
2556 2552
2557 2553 %store - Show list of all variables and their current values\\
2558 2554 %store <var> - Store the *current* value of the variable to disk\\
2559 2555 %store -d - Remove the variable and its value from storage\\
2560 2556 %store -r - Remove all variables from storage
2561 2557
2562 2558 It should be noted that if you change the value of a variable, you
2563 2559 need to %store it again if you want to persist the new value.
2564 2560
2565 2561 Note also that the variables will need to be pickleable; most basic
2566 2562 python types can be safely %stored.
2567 2563 """
2568 2564
2569 2565 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2570 2566 # delete
2571 2567 if opts.has_key('d'):
2572 2568 try:
2573 2569 todel = args[0]
2574 2570 except IndexError:
2575 2571 error('You must provide the variable to forget')
2576 2572 else:
2577 2573 try:
2578 2574 del self.shell.persist['S:' + todel]
2579 2575 except:
2580 2576 error("Can't delete variable '%s'" % todel)
2581 2577 # reset
2582 2578 elif opts.has_key('r'):
2583 2579 for k in self.shell.persist.keys():
2584 2580 if k.startswith('S:'):
2585 2581 del self.shell.persist[k]
2586 2582
2587 2583 # run without arguments -> list variables & values
2588 2584 elif not args:
2589 2585 vars = [v[2:] for v in self.shell.persist.keys()
2590 2586 if v.startswith('S:')]
2591 2587 vars.sort()
2592 2588 if vars:
2593 2589 size = max(map(len,vars))
2594 2590 else:
2595 2591 size = 0
2596 2592
2597 2593 print 'Stored variables and their in-memory values:'
2598 2594 fmt = '%-'+str(size)+'s -> %s'
2599 2595 get = self.shell.user_ns.get
2600 2596 for var in vars:
2601 2597 # print 30 first characters from every var
2602 2598 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2603 2599
2604 2600 # default action - store the variable
2605 2601 else:
2606 2602 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2607 2603 self.shell.persist[ 'S:' + args[0] ] = pickled
2608 2604 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2609 2605
2610 2606 def magic_bookmark(self, parameter_s=''):
2611 2607 """Manage IPython's bookmark system.
2612 2608
2613 2609 %bookmark <name> - set bookmark to current dir
2614 2610 %bookmark <name> <dir> - set bookmark to <dir>
2615 2611 %bookmark -l - list all bookmarks
2616 2612 %bookmark -d <name> - remove bookmark
2617 2613 %bookmark -r - remove all bookmarks
2618 2614
2619 2615 You can later on access a bookmarked folder with:
2620 2616 %cd -b <name>
2621 2617 or simply '%cd <name>' if there is no directory called <name> AND
2622 2618 there is such a bookmark defined.
2623 2619
2624 2620 Your bookmarks persist through IPython sessions, but they are
2625 2621 associated with each profile."""
2626 2622
2627 2623 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2628 2624 if len(args) > 2:
2629 2625 error('You can only give at most two arguments')
2630 2626 return
2631 2627
2632 2628 bkms = self.shell.persist.get('bookmarks',{})
2633 2629
2634 2630 if opts.has_key('d'):
2635 2631 try:
2636 2632 todel = args[0]
2637 2633 except IndexError:
2638 2634 error('You must provide a bookmark to delete')
2639 2635 else:
2640 2636 try:
2641 2637 del bkms[todel]
2642 2638 except:
2643 2639 error("Can't delete bookmark '%s'" % todel)
2644 2640 elif opts.has_key('r'):
2645 2641 bkms = {}
2646 2642 elif opts.has_key('l'):
2647 2643 bks = bkms.keys()
2648 2644 bks.sort()
2649 2645 if bks:
2650 2646 size = max(map(len,bks))
2651 2647 else:
2652 2648 size = 0
2653 2649 fmt = '%-'+str(size)+'s -> %s'
2654 2650 print 'Current bookmarks:'
2655 2651 for bk in bks:
2656 2652 print fmt % (bk,bkms[bk])
2657 2653 else:
2658 2654 if not args:
2659 2655 error("You must specify the bookmark name")
2660 2656 elif len(args)==1:
2661 2657 bkms[args[0]] = os.getcwd()
2662 2658 elif len(args)==2:
2663 2659 bkms[args[0]] = args[1]
2664 2660 self.shell.persist['bookmarks'] = bkms
2665 2661
2666 2662 def magic_pycat(self, parameter_s=''):
2667 2663 """Show a syntax-highlighted file through a pager.
2668 2664
2669 2665 This magic is similar to the cat utility, but it will assume the file
2670 2666 to be Python source and will show it with syntax highlighting. """
2671 2667
2672 2668 filename = get_py_filename(parameter_s)
2673 2669 page(self.shell.colorize(file_read(filename)),
2674 2670 screen_lines=self.shell.rc.screen_length)
2675 2671
2676 2672 # end Magic
@@ -1,583 +1,583 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Classes for handling input/output prompts.
4 4
5 $Id: Prompts.py 966 2005-12-29 08:34:07Z fperez $"""
5 $Id: Prompts.py 975 2005-12-29 23:50:22Z fperez $"""
6 6
7 7 #*****************************************************************************
8 8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 from IPython import Release
15 15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 16 __license__ = Release.license
17 17 __version__ = Release.version
18 18
19 19 #****************************************************************************
20 20 # Required modules
21 21 import __builtin__
22 22 import os
23 23 import socket
24 24 import sys
25 25 import time
26 26 from pprint import pprint,pformat
27 27
28 28 # IPython's own
29 from IPython.genutils import *
30 from IPython.Struct import Struct
31 from IPython.Magic import Macro
32 from IPython.Itpl import ItplNS
33 29 from IPython import ColorANSI
30 from IPython.Itpl import ItplNS
31 from IPython.Struct import Struct
32 from IPython.macro import Macro
33 from IPython.genutils import *
34 34
35 35 #****************************************************************************
36 36 #Color schemes for Prompts.
37 37
38 38 PromptColors = ColorANSI.ColorSchemeTable()
39 39 InputColors = ColorANSI.InputTermColors # just a shorthand
40 40 Colors = ColorANSI.TermColors # just a shorthand
41 41
42 42 PromptColors.add_scheme(ColorANSI.ColorScheme(
43 43 'NoColor',
44 44 in_prompt = InputColors.NoColor, # Input prompt
45 45 in_number = InputColors.NoColor, # Input prompt number
46 46 in_prompt2 = InputColors.NoColor, # Continuation prompt
47 47 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
48 48
49 49 out_prompt = Colors.NoColor, # Output prompt
50 50 out_number = Colors.NoColor, # Output prompt number
51 51
52 52 normal = Colors.NoColor # color off (usu. Colors.Normal)
53 53 ))
54 54
55 55 # make some schemes as instances so we can copy them for modification easily:
56 56 __PColLinux = ColorANSI.ColorScheme(
57 57 'Linux',
58 58 in_prompt = InputColors.Green,
59 59 in_number = InputColors.LightGreen,
60 60 in_prompt2 = InputColors.Green,
61 61 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
62 62
63 63 out_prompt = Colors.Red,
64 64 out_number = Colors.LightRed,
65 65
66 66 normal = Colors.Normal
67 67 )
68 68 # Don't forget to enter it into the table!
69 69 PromptColors.add_scheme(__PColLinux)
70 70
71 71 # Slightly modified Linux for light backgrounds
72 72 __PColLightBG = __PColLinux.copy('LightBG')
73 73
74 74 __PColLightBG.colors.update(
75 75 in_prompt = InputColors.Blue,
76 76 in_number = InputColors.LightBlue,
77 77 in_prompt2 = InputColors.Blue
78 78 )
79 79 PromptColors.add_scheme(__PColLightBG)
80 80
81 81 del Colors,InputColors
82 82
83 83 #-----------------------------------------------------------------------------
84 84 def multiple_replace(dict, text):
85 85 """ Replace in 'text' all occurences of any key in the given
86 86 dictionary by its corresponding value. Returns the new string."""
87 87
88 88 # Function by Xavier Defrang, originally found at:
89 89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
90 90
91 91 # Create a regular expression from the dictionary keys
92 92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
93 93 # For each match, look-up corresponding value in dictionary
94 94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
95 95
96 96 #-----------------------------------------------------------------------------
97 97 # Special characters that can be used in prompt templates, mainly bash-like
98 98
99 99 # If $HOME isn't defined (Windows), make it an absurd string so that it can
100 100 # never be expanded out into '~'. Basically anything which can never be a
101 101 # reasonable directory name will do, we just want the $HOME -> '~' operation
102 102 # to become a no-op. We pre-compute $HOME here so it's not done on every
103 103 # prompt call.
104 104
105 105 # FIXME:
106 106
107 107 # - This should be turned into a class which does proper namespace management,
108 108 # since the prompt specials need to be evaluated in a certain namespace.
109 109 # Currently it's just globals, which need to be managed manually by code
110 110 # below.
111 111
112 112 # - I also need to split up the color schemes from the prompt specials
113 113 # somehow. I don't have a clean design for that quite yet.
114 114
115 115 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
116 116
117 117 # We precompute a few more strings here for the prompt_specials, which are
118 118 # fixed once ipython starts. This reduces the runtime overhead of computing
119 119 # prompt strings.
120 120 USER = os.environ.get("USER")
121 121 HOSTNAME = socket.gethostname()
122 122 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
123 123 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
124 124
125 125 prompt_specials_color = {
126 126 # Prompt/history count
127 127 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 128 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
129 129 # Prompt/history count, with the actual digits replaced by dots. Used
130 130 # mainly in continuation prompts (prompt_in2)
131 131 '\\D': '${"."*len(str(self.cache.prompt_count))}',
132 132 # Current working directory
133 133 '\\w': '${os.getcwd()}',
134 134 # Current time
135 135 '\\t' : '${time.strftime("%H:%M:%S")}',
136 136 # Basename of current working directory.
137 137 # (use os.sep to make this portable across OSes)
138 138 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
139 139 # These X<N> are an extension to the normal bash prompts. They return
140 140 # N terms of the path, after replacing $HOME with '~'
141 141 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
142 142 '\\X1': '${self.cwd_filt(1)}',
143 143 '\\X2': '${self.cwd_filt(2)}',
144 144 '\\X3': '${self.cwd_filt(3)}',
145 145 '\\X4': '${self.cwd_filt(4)}',
146 146 '\\X5': '${self.cwd_filt(5)}',
147 147 # Y<N> are similar to X<N>, but they show '~' if it's the directory
148 148 # N+1 in the list. Somewhat like %cN in tcsh.
149 149 '\\Y0': '${self.cwd_filt2(0)}',
150 150 '\\Y1': '${self.cwd_filt2(1)}',
151 151 '\\Y2': '${self.cwd_filt2(2)}',
152 152 '\\Y3': '${self.cwd_filt2(3)}',
153 153 '\\Y4': '${self.cwd_filt2(4)}',
154 154 '\\Y5': '${self.cwd_filt2(5)}',
155 155 # Hostname up to first .
156 156 '\\h': HOSTNAME_SHORT,
157 157 # Full hostname
158 158 '\\H': HOSTNAME,
159 159 # Username of current user
160 160 '\\u': USER,
161 161 # Escaped '\'
162 162 '\\\\': '\\',
163 163 # Newline
164 164 '\\n': '\n',
165 165 # Carriage return
166 166 '\\r': '\r',
167 167 # Release version
168 168 '\\v': __version__,
169 169 # Root symbol ($ or #)
170 170 '\\$': ROOT_SYMBOL,
171 171 }
172 172
173 173 # A copy of the prompt_specials dictionary but with all color escapes removed,
174 174 # so we can correctly compute the prompt length for the auto_rewrite method.
175 175 prompt_specials_nocolor = prompt_specials_color.copy()
176 176 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
177 177 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
178 178
179 179 # Add in all the InputTermColors color escapes as valid prompt characters.
180 180 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
181 181 # with a color name which may begin with a letter used by any other of the
182 182 # allowed specials. This of course means that \\C will never be allowed for
183 183 # anything else.
184 184 input_colors = ColorANSI.InputTermColors
185 185 for _color in dir(input_colors):
186 186 if _color[0] != '_':
187 187 c_name = '\\C_'+_color
188 188 prompt_specials_color[c_name] = getattr(input_colors,_color)
189 189 prompt_specials_nocolor[c_name] = ''
190 190
191 191 # we default to no color for safety. Note that prompt_specials is a global
192 192 # variable used by all prompt objects.
193 193 prompt_specials = prompt_specials_nocolor
194 194
195 195 #-----------------------------------------------------------------------------
196 196 def str_safe(arg):
197 197 """Convert to a string, without ever raising an exception.
198 198
199 199 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
200 200 error message."""
201 201
202 202 try:
203 203 out = str(arg)
204 204 except UnicodeError:
205 205 try:
206 206 out = arg.encode('utf_8','replace')
207 207 except Exception,msg:
208 208 # let's keep this little duplication here, so that the most common
209 209 # case doesn't suffer from a double try wrapping.
210 210 out = '<ERROR: %s>' % msg
211 211 except Exception,msg:
212 212 out = '<ERROR: %s>' % msg
213 213 return out
214 214
215 215 class BasePrompt:
216 216 """Interactive prompt similar to Mathematica's."""
217 217 def __init__(self,cache,sep,prompt,pad_left=False):
218 218
219 219 # Hack: we access information about the primary prompt through the
220 220 # cache argument. We need this, because we want the secondary prompt
221 221 # to be aligned with the primary one. Color table info is also shared
222 222 # by all prompt classes through the cache. Nice OO spaghetti code!
223 223 self.cache = cache
224 224 self.sep = sep
225 225
226 226 # regexp to count the number of spaces at the end of a prompt
227 227 # expression, useful for prompt auto-rewriting
228 228 self.rspace = re.compile(r'(\s*)$')
229 229 # Flag to left-pad prompt strings to match the length of the primary
230 230 # prompt
231 231 self.pad_left = pad_left
232 232 # Set template to create each actual prompt (where numbers change)
233 233 self.p_template = prompt
234 234 self.set_p_str()
235 235
236 236 def set_p_str(self):
237 237 """ Set the interpolating prompt strings.
238 238
239 239 This must be called every time the color settings change, because the
240 240 prompt_specials global may have changed."""
241 241
242 242 import os,time # needed in locals for prompt string handling
243 243 loc = locals()
244 244 self.p_str = ItplNS('%s%s%s' %
245 245 ('${self.sep}${self.col_p}',
246 246 multiple_replace(prompt_specials, self.p_template),
247 247 '${self.col_norm}'),self.cache.user_ns,loc)
248 248
249 249 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
250 250 self.p_template),
251 251 self.cache.user_ns,loc)
252 252
253 253 def write(self,msg): # dbg
254 254 sys.stdout.write(msg)
255 255 return ''
256 256
257 257 def __str__(self):
258 258 """Return a string form of the prompt.
259 259
260 260 This for is useful for continuation and output prompts, since it is
261 261 left-padded to match lengths with the primary one (if the
262 262 self.pad_left attribute is set)."""
263 263
264 264 out_str = str_safe(self.p_str)
265 265 if self.pad_left:
266 266 # We must find the amount of padding required to match lengths,
267 267 # taking the color escapes (which are invisible on-screen) into
268 268 # account.
269 269 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
270 270 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
271 271 return format % out_str
272 272 else:
273 273 return out_str
274 274
275 275 # these path filters are put in as methods so that we can control the
276 276 # namespace where the prompt strings get evaluated
277 277 def cwd_filt(self,depth):
278 278 """Return the last depth elements of the current working directory.
279 279
280 280 $HOME is always replaced with '~'.
281 281 If depth==0, the full path is returned."""
282 282
283 283 cwd = os.getcwd().replace(HOME,"~")
284 284 out = os.sep.join(cwd.split(os.sep)[-depth:])
285 285 if out:
286 286 return out
287 287 else:
288 288 return os.sep
289 289
290 290 def cwd_filt2(self,depth):
291 291 """Return the last depth elements of the current working directory.
292 292
293 293 $HOME is always replaced with '~'.
294 294 If depth==0, the full path is returned."""
295 295
296 296 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
297 297 if '~' in cwd and len(cwd) == depth+1:
298 298 depth += 1
299 299 out = os.sep.join(cwd[-depth:])
300 300 if out:
301 301 return out
302 302 else:
303 303 return os.sep
304 304
305 305 class Prompt1(BasePrompt):
306 306 """Input interactive prompt similar to Mathematica's."""
307 307
308 308 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
309 309 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
310 310
311 311 def set_colors(self):
312 312 self.set_p_str()
313 313 Colors = self.cache.color_table.active_colors # shorthand
314 314 self.col_p = Colors.in_prompt
315 315 self.col_num = Colors.in_number
316 316 self.col_norm = Colors.in_normal
317 317 # We need a non-input version of these escapes for the '--->'
318 318 # auto-call prompts used in the auto_rewrite() method.
319 319 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
320 320 self.col_norm_ni = Colors.normal
321 321
322 322 def __str__(self):
323 323 self.cache.prompt_count += 1
324 324 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
325 325 return str_safe(self.p_str)
326 326
327 327 def auto_rewrite(self):
328 328 """Print a string of the form '--->' which lines up with the previous
329 329 input string. Useful for systems which re-write the user input when
330 330 handling automatically special syntaxes."""
331 331
332 332 curr = str(self.cache.last_prompt)
333 333 nrspaces = len(self.rspace.search(curr).group())
334 334 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
335 335 ' '*nrspaces,self.col_norm_ni)
336 336
337 337 class PromptOut(BasePrompt):
338 338 """Output interactive prompt similar to Mathematica's."""
339 339
340 340 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
341 341 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
342 342 if not self.p_template:
343 343 self.__str__ = lambda: ''
344 344
345 345 def set_colors(self):
346 346 self.set_p_str()
347 347 Colors = self.cache.color_table.active_colors # shorthand
348 348 self.col_p = Colors.out_prompt
349 349 self.col_num = Colors.out_number
350 350 self.col_norm = Colors.normal
351 351
352 352 class Prompt2(BasePrompt):
353 353 """Interactive continuation prompt."""
354 354
355 355 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
356 356 self.cache = cache
357 357 self.p_template = prompt
358 358 self.pad_left = pad_left
359 359 self.set_p_str()
360 360
361 361 def set_p_str(self):
362 362 import os,time # needed in locals for prompt string handling
363 363 loc = locals()
364 364 self.p_str = ItplNS('%s%s%s' %
365 365 ('${self.col_p2}',
366 366 multiple_replace(prompt_specials, self.p_template),
367 367 '$self.col_norm'),
368 368 self.cache.user_ns,loc)
369 369 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
370 370 self.p_template),
371 371 self.cache.user_ns,loc)
372 372
373 373 def set_colors(self):
374 374 self.set_p_str()
375 375 Colors = self.cache.color_table.active_colors
376 376 self.col_p2 = Colors.in_prompt2
377 377 self.col_norm = Colors.in_normal
378 378 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
379 379 # updated their prompt_in2 definitions. Remove eventually.
380 380 self.col_p = Colors.out_prompt
381 381 self.col_num = Colors.out_number
382 382
383 383 #-----------------------------------------------------------------------------
384 384 class CachedOutput:
385 385 """Class for printing output from calculations while keeping a cache of
386 386 reults. It dynamically creates global variables prefixed with _ which
387 387 contain these results.
388 388
389 389 Meant to be used as a sys.displayhook replacement, providing numbered
390 390 prompts and cache services.
391 391
392 392 Initialize with initial and final values for cache counter (this defines
393 393 the maximum size of the cache."""
394 394
395 395 def __init__(self,shell,cache_size,Pprint,
396 396 colors='NoColor',input_sep='\n',
397 397 output_sep='\n',output_sep2='',
398 398 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
399 399
400 400 cache_size_min = 20
401 401 if cache_size <= 0:
402 402 self.do_full_cache = 0
403 403 cache_size = 0
404 404 elif cache_size < cache_size_min:
405 405 self.do_full_cache = 0
406 406 cache_size = 0
407 407 warn('caching was disabled (min value for cache size is %s).' %
408 408 cache_size_min,level=3)
409 409 else:
410 410 self.do_full_cache = 1
411 411
412 412 self.cache_size = cache_size
413 413 self.input_sep = input_sep
414 414
415 415 # we need a reference to the user-level namespace
416 416 self.shell = shell
417 417 self.user_ns = shell.user_ns
418 418 # and to the user's input
419 419 self.input_hist = shell.input_hist
420 420 # and to the user's logger, for logging output
421 421 self.logger = shell.logger
422 422
423 423 # Set input prompt strings and colors
424 424 if cache_size == 0:
425 425 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
426 426 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
427 427 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
428 428 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
429 429 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
430 430
431 431 self.color_table = PromptColors
432 432 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
433 433 pad_left=pad_left)
434 434 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
435 435 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
436 436 pad_left=pad_left)
437 437 self.set_colors(colors)
438 438
439 439 # other more normal stuff
440 440 # b/c each call to the In[] prompt raises it by 1, even the first.
441 441 self.prompt_count = 0
442 442 self.cache_count = 1
443 443 # Store the last prompt string each time, we need it for aligning
444 444 # continuation and auto-rewrite prompts
445 445 self.last_prompt = ''
446 446 self.entries = [None] # output counter starts at 1 for the user
447 447 self.Pprint = Pprint
448 448 self.output_sep = output_sep
449 449 self.output_sep2 = output_sep2
450 450 self._,self.__,self.___ = '','',''
451 451 self.pprint_types = map(type,[(),[],{}])
452 452
453 453 # these are deliberately global:
454 454 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
455 455 self.user_ns.update(to_user_ns)
456 456
457 457 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
458 458 if p_str is None:
459 459 if self.do_full_cache:
460 460 return cache_def
461 461 else:
462 462 return no_cache_def
463 463 else:
464 464 return p_str
465 465
466 466 def set_colors(self,colors):
467 467 """Set the active color scheme and configure colors for the three
468 468 prompt subsystems."""
469 469
470 470 # FIXME: the prompt_specials global should be gobbled inside this
471 471 # class instead. Do it when cleaning up the whole 3-prompt system.
472 472 global prompt_specials
473 473 if colors.lower()=='nocolor':
474 474 prompt_specials = prompt_specials_nocolor
475 475 else:
476 476 prompt_specials = prompt_specials_color
477 477
478 478 self.color_table.set_active_scheme(colors)
479 479 self.prompt1.set_colors()
480 480 self.prompt2.set_colors()
481 481 self.prompt_out.set_colors()
482 482
483 483 def __call__(self,arg=None):
484 484 """Printing with history cache management.
485 485
486 486 This is invoked everytime the interpreter needs to print, and is
487 487 activated by setting the variable sys.displayhook to it."""
488 488
489 489 # If something injected a '_' variable in __builtin__, delete
490 490 # ipython's automatic one so we don't clobber that. gettext() in
491 491 # particular uses _, so we need to stay away from it.
492 492 if '_' in __builtin__.__dict__:
493 493 try:
494 494 del self.user_ns['_']
495 495 except KeyError:
496 496 pass
497 497 if arg is not None:
498 498 cout_write = Term.cout.write # fast lookup
499 499 # first handle the cache and counters
500 500 # but avoid recursive reference when displaying _oh/Out
501 501 if arg is not self.user_ns['_oh']:
502 502 self.update(arg)
503 503 # do not print output if input ends in ';'
504 504 if self.input_hist[self.prompt_count].endswith(';\n'):
505 505 return
506 506 # don't use print, puts an extra space
507 507 cout_write(self.output_sep)
508 508 if self.do_full_cache:
509 509 cout_write(str(self.prompt_out))
510 510
511 511 if isinstance(arg,Macro):
512 512 print 'Executing Macro...'
513 513 # in case the macro takes a long time to execute
514 514 Term.cout.flush()
515 515 self.shell.runlines(arg.value)
516 516 return None
517 517
518 518 # and now call a possibly user-defined print mechanism
519 519 self.display(arg)
520 520 if self.logger.log_output:
521 521 self.logger.log_write(repr(arg),'output')
522 522 cout_write(self.output_sep2)
523 523 Term.cout.flush()
524 524
525 525 def _display(self,arg):
526 526 """Default printer method, uses pprint.
527 527
528 528 This can be over-ridden by the users to implement special formatting
529 529 of certain types of output."""
530 530
531 531 if self.Pprint:
532 532 out = pformat(arg)
533 533 if '\n' in out:
534 534 # So that multi-line strings line up with the left column of
535 535 # the screen, instead of having the output prompt mess up
536 536 # their first line.
537 537 Term.cout.write('\n')
538 538 print >>Term.cout, out
539 539 else:
540 540 print >>Term.cout, arg
541 541
542 542 # Assign the default display method:
543 543 display = _display
544 544
545 545 def update(self,arg):
546 546 #print '***cache_count', self.cache_count # dbg
547 547 if self.cache_count >= self.cache_size and self.do_full_cache:
548 548 self.flush()
549 549 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
550 550 # we cause buggy behavior for things like gettext).
551 551 if '_' not in __builtin__.__dict__:
552 552 self.___ = self.__
553 553 self.__ = self._
554 554 self._ = arg
555 555 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
556 556
557 557 # hackish access to top-level namespace to create _1,_2... dynamically
558 558 to_main = {}
559 559 if self.do_full_cache:
560 560 self.cache_count += 1
561 561 self.entries.append(arg)
562 562 new_result = '_'+`self.prompt_count`
563 563 to_main[new_result] = self.entries[-1]
564 564 self.user_ns.update(to_main)
565 565 self.user_ns['_oh'][self.prompt_count] = arg
566 566
567 567 def flush(self):
568 568 if not self.do_full_cache:
569 569 raise ValueError,"You shouldn't have reached the cache flush "\
570 570 "if full caching is not enabled!"
571 571 warn('Output cache limit (currently '+\
572 572 `self.cache_count`+' entries) hit.\n'
573 573 'Flushing cache and resetting history counter...\n'
574 574 'The only history variables available will be _,__,___ and _1\n'
575 575 'with the current result.')
576 576 # delete auto-generated vars from global namespace
577 577 for n in range(1,self.prompt_count + 1):
578 578 key = '_'+`n`
579 579 try:
580 580 del self.user_ns[key]
581 581 except: pass
582 582 self.prompt_count = 1
583 583 self.cache_count = 1
@@ -1,2051 +1,2056 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 968 2005-12-29 17:15:38Z fperez $
9 $Id: iplib.py 975 2005-12-29 23:50:22Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from __future__ import generators # for 2.2 backwards-compatibility
32 32
33 33 from IPython import Release
34 34 __author__ = '%s <%s>\n%s <%s>' % \
35 35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 36 __license__ = Release.license
37 37 __version__ = Release.version
38 38
39 39 # Python standard modules
40 40 import __main__
41 41 import __builtin__
42 42 import StringIO
43 43 import bdb
44 44 import cPickle as pickle
45 45 import codeop
46 46 import exceptions
47 47 import glob
48 48 import inspect
49 49 import keyword
50 50 import new
51 51 import os
52 52 import pdb
53 53 import pydoc
54 54 import re
55 55 import shutil
56 56 import string
57 57 import sys
58 58 import traceback
59 59 import types
60 60
61 61 from pprint import pprint, pformat
62 62
63 63 # IPython's own modules
64 64 import IPython
65 65 from IPython import OInspect,PyColorize,ultraTB
66 66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 67 from IPython.FakeModule import FakeModule
68 68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 69 from IPython.Logger import Logger
70 70 from IPython.Magic import Magic
71 71 from IPython.Prompts import CachedOutput
72 72 from IPython.Struct import Struct
73 73 from IPython.background_jobs import BackgroundJobManager
74 74 from IPython.usage import cmd_line_usage,interactive_usage
75 75 from IPython.genutils import *
76 76
77 77 # store the builtin raw_input globally, and use this always, in case user code
78 78 # overwrites it (like wx.py.PyShell does)
79 79 raw_input_original = raw_input
80 80
81 # compiled regexps for autoindent management
82 ini_spaces_re = re.compile(r'^(\s+)')
83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
84
81 85 #****************************************************************************
82 86 # Some utility function definitions
83 87
84 88 def softspace(file, newvalue):
85 89 """Copied from code.py, to remove the dependency"""
86 90 oldvalue = 0
87 91 try:
88 92 oldvalue = file.softspace
89 93 except AttributeError:
90 94 pass
91 95 try:
92 96 file.softspace = newvalue
93 97 except (AttributeError, TypeError):
94 98 # "attribute-less object" or "read-only attributes"
95 99 pass
96 100 return oldvalue
97 101
98 102 #****************************************************************************
99 103 # These special functions get installed in the builtin namespace, to provide
100 104 # programmatic (pure python) access to magics and aliases. This is important
101 105 # for logging, user scripting, and more.
102 106
103 107 def ipmagic(arg_s):
104 108 """Call a magic function by name.
105 109
106 110 Input: a string containing the name of the magic function to call and any
107 111 additional arguments to be passed to the magic.
108 112
109 113 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
110 114 prompt:
111 115
112 116 In[1]: %name -opt foo bar
113 117
114 118 To call a magic without arguments, simply use ipmagic('name').
115 119
116 120 This provides a proper Python function to call IPython's magics in any
117 121 valid Python code you can type at the interpreter, including loops and
118 122 compound statements. It is added by IPython to the Python builtin
119 123 namespace upon initialization."""
120 124
121 125 args = arg_s.split(' ',1)
122 126 magic_name = args[0]
123 127 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
124 128 magic_name = magic_name[1:]
125 129 try:
126 130 magic_args = args[1]
127 131 except IndexError:
128 132 magic_args = ''
129 133 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
130 134 if fn is None:
131 135 error("Magic function `%s` not found." % magic_name)
132 136 else:
133 137 magic_args = __IPYTHON__.var_expand(magic_args)
134 138 return fn(magic_args)
135 139
136 140 def ipalias(arg_s):
137 141 """Call an alias by name.
138 142
139 143 Input: a string containing the name of the alias to call and any
140 144 additional arguments to be passed to the magic.
141 145
142 146 ipalias('name -opt foo bar') is equivalent to typing at the ipython
143 147 prompt:
144 148
145 149 In[1]: name -opt foo bar
146 150
147 151 To call an alias without arguments, simply use ipalias('name').
148 152
149 153 This provides a proper Python function to call IPython's aliases in any
150 154 valid Python code you can type at the interpreter, including loops and
151 155 compound statements. It is added by IPython to the Python builtin
152 156 namespace upon initialization."""
153 157
154 158 args = arg_s.split(' ',1)
155 159 alias_name = args[0]
156 160 try:
157 161 alias_args = args[1]
158 162 except IndexError:
159 163 alias_args = ''
160 164 if alias_name in __IPYTHON__.alias_table:
161 165 __IPYTHON__.call_alias(alias_name,alias_args)
162 166 else:
163 167 error("Alias `%s` not found." % alias_name)
164 168
165 169 #****************************************************************************
166 170 # Local use exceptions
167 171 class SpaceInInput(exceptions.Exception): pass
168 172
169 173 #****************************************************************************
170 174 # Local use classes
171 175 class Bunch: pass
172 176
173 177 class InputList(list):
174 178 """Class to store user input.
175 179
176 180 It's basically a list, but slices return a string instead of a list, thus
177 181 allowing things like (assuming 'In' is an instance):
178 182
179 183 exec In[4:7]
180 184
181 185 or
182 186
183 187 exec In[5:9] + In[14] + In[21:25]"""
184 188
185 189 def __getslice__(self,i,j):
186 190 return ''.join(list.__getslice__(self,i,j))
187 191
188 192 class SyntaxTB(ultraTB.ListTB):
189 193 """Extension which holds some state: the last exception value"""
190 194
191 195 def __init__(self,color_scheme = 'NoColor'):
192 196 ultraTB.ListTB.__init__(self,color_scheme)
193 197 self.last_syntax_error = None
194 198
195 199 def __call__(self, etype, value, elist):
196 200 self.last_syntax_error = value
197 201 ultraTB.ListTB.__call__(self,etype,value,elist)
198 202
199 203 def clear_err_state(self):
200 204 """Return the current error state and clear it"""
201 205 e = self.last_syntax_error
202 206 self.last_syntax_error = None
203 207 return e
204 208
205 209 #****************************************************************************
206 210 # Main IPython class
207 211
208 212 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
209 213 # until a full rewrite is made. I've cleaned all cross-class uses of
210 214 # attributes and methods, but too much user code out there relies on the
211 215 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
212 216 #
213 217 # But at least now, all the pieces have been separated and we could, in
214 218 # principle, stop using the mixin. This will ease the transition to the
215 219 # chainsaw branch.
216 220
217 221 # For reference, the following is the list of 'self.foo' uses in the Magic
218 222 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
219 223 # class, to prevent clashes.
220 224
221 225 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
222 226 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
223 227 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
224 228 # 'self.value']
225 229
226 230 class InteractiveShell(Magic):
227 231 """An enhanced console for Python."""
228 232
229 233 # class attribute to indicate whether the class supports threads or not.
230 234 # Subclasses with thread support should override this as needed.
231 235 isthreaded = False
232 236
233 237 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
234 238 user_ns = None,user_global_ns=None,banner2='',
235 239 custom_exceptions=((),None),embedded=False):
236 240
237 241 # some minimal strict typechecks. For some core data structures, I
238 242 # want actual basic python types, not just anything that looks like
239 243 # one. This is especially true for namespaces.
240 244 for ns in (user_ns,user_global_ns):
241 245 if ns is not None and type(ns) != types.DictType:
242 246 raise TypeError,'namespace must be a dictionary'
243 247
244 248 # Put a reference to self in builtins so that any form of embedded or
245 249 # imported code can test for being inside IPython.
246 250 __builtin__.__IPYTHON__ = self
247 251
248 252 # And load into builtins ipmagic/ipalias as well
249 253 __builtin__.ipmagic = ipmagic
250 254 __builtin__.ipalias = ipalias
251 255
252 256 # Add to __builtin__ other parts of IPython's public API
253 257 __builtin__.ip_set_hook = self.set_hook
254 258
255 259 # Keep in the builtins a flag for when IPython is active. We set it
256 260 # with setdefault so that multiple nested IPythons don't clobber one
257 261 # another. Each will increase its value by one upon being activated,
258 262 # which also gives us a way to determine the nesting level.
259 263 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
260 264
261 265 # Do the intuitively correct thing for quit/exit: we remove the
262 266 # builtins if they exist, and our own prefilter routine will handle
263 267 # these special cases
264 268 try:
265 269 del __builtin__.exit, __builtin__.quit
266 270 except AttributeError:
267 271 pass
268 272
269 273 # Store the actual shell's name
270 274 self.name = name
271 275
272 276 # We need to know whether the instance is meant for embedding, since
273 277 # global/local namespaces need to be handled differently in that case
274 278 self.embedded = embedded
275 279
276 280 # command compiler
277 281 self.compile = codeop.CommandCompiler()
278 282
279 283 # User input buffer
280 284 self.buffer = []
281 285
282 286 # Default name given in compilation of code
283 287 self.filename = '<ipython console>'
284 288
285 289 # Create the namespace where the user will operate. user_ns is
286 290 # normally the only one used, and it is passed to the exec calls as
287 291 # the locals argument. But we do carry a user_global_ns namespace
288 292 # given as the exec 'globals' argument, This is useful in embedding
289 293 # situations where the ipython shell opens in a context where the
290 294 # distinction between locals and globals is meaningful.
291 295
292 296 # FIXME. For some strange reason, __builtins__ is showing up at user
293 297 # level as a dict instead of a module. This is a manual fix, but I
294 298 # should really track down where the problem is coming from. Alex
295 299 # Schmolck reported this problem first.
296 300
297 301 # A useful post by Alex Martelli on this topic:
298 302 # Re: inconsistent value from __builtins__
299 303 # Von: Alex Martelli <aleaxit@yahoo.com>
300 304 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
301 305 # Gruppen: comp.lang.python
302 306
303 307 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
304 308 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
305 309 # > <type 'dict'>
306 310 # > >>> print type(__builtins__)
307 311 # > <type 'module'>
308 312 # > Is this difference in return value intentional?
309 313
310 314 # Well, it's documented that '__builtins__' can be either a dictionary
311 315 # or a module, and it's been that way for a long time. Whether it's
312 316 # intentional (or sensible), I don't know. In any case, the idea is
313 317 # that if you need to access the built-in namespace directly, you
314 318 # should start with "import __builtin__" (note, no 's') which will
315 319 # definitely give you a module. Yeah, it's somewhatΒ confusing:-(.
316 320
317 321 if user_ns is None:
318 322 # Set __name__ to __main__ to better match the behavior of the
319 323 # normal interpreter.
320 324 user_ns = {'__name__' :'__main__',
321 325 '__builtins__' : __builtin__,
322 326 }
323 327
324 328 if user_global_ns is None:
325 329 user_global_ns = {}
326 330
327 331 # Assign namespaces
328 332 # This is the namespace where all normal user variables live
329 333 self.user_ns = user_ns
330 334 # Embedded instances require a separate namespace for globals.
331 335 # Normally this one is unused by non-embedded instances.
332 336 self.user_global_ns = user_global_ns
333 337 # A namespace to keep track of internal data structures to prevent
334 338 # them from cluttering user-visible stuff. Will be updated later
335 339 self.internal_ns = {}
336 340
337 341 # Namespace of system aliases. Each entry in the alias
338 342 # table must be a 2-tuple of the form (N,name), where N is the number
339 343 # of positional arguments of the alias.
340 344 self.alias_table = {}
341 345
342 346 # A table holding all the namespaces IPython deals with, so that
343 347 # introspection facilities can search easily.
344 348 self.ns_table = {'user':user_ns,
345 349 'user_global':user_global_ns,
346 350 'alias':self.alias_table,
347 351 'internal':self.internal_ns,
348 352 'builtin':__builtin__.__dict__
349 353 }
350 354
351 355 # The user namespace MUST have a pointer to the shell itself.
352 356 self.user_ns[name] = self
353 357
354 358 # We need to insert into sys.modules something that looks like a
355 359 # module but which accesses the IPython namespace, for shelve and
356 360 # pickle to work interactively. Normally they rely on getting
357 361 # everything out of __main__, but for embedding purposes each IPython
358 362 # instance has its own private namespace, so we can't go shoving
359 363 # everything into __main__.
360 364
361 365 # note, however, that we should only do this for non-embedded
362 366 # ipythons, which really mimic the __main__.__dict__ with their own
363 367 # namespace. Embedded instances, on the other hand, should not do
364 368 # this because they need to manage the user local/global namespaces
365 369 # only, but they live within a 'normal' __main__ (meaning, they
366 370 # shouldn't overtake the execution environment of the script they're
367 371 # embedded in).
368 372
369 373 if not embedded:
370 374 try:
371 375 main_name = self.user_ns['__name__']
372 376 except KeyError:
373 377 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
374 378 else:
375 379 #print "pickle hack in place" # dbg
376 380 sys.modules[main_name] = FakeModule(self.user_ns)
377 381
378 382 # List of input with multi-line handling.
379 383 # Fill its zero entry, user counter starts at 1
380 384 self.input_hist = InputList(['\n'])
381 385
382 386 # list of visited directories
383 387 try:
384 388 self.dir_hist = [os.getcwd()]
385 389 except IOError, e:
386 390 self.dir_hist = []
387 391
388 392 # dict of output history
389 393 self.output_hist = {}
390 394
391 395 # dict of things NOT to alias (keywords, builtins and some magics)
392 396 no_alias = {}
393 397 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
394 398 for key in keyword.kwlist + no_alias_magics:
395 399 no_alias[key] = 1
396 400 no_alias.update(__builtin__.__dict__)
397 401 self.no_alias = no_alias
398 402
399 403 # make global variables for user access to these
400 404 self.user_ns['_ih'] = self.input_hist
401 405 self.user_ns['_oh'] = self.output_hist
402 406 self.user_ns['_dh'] = self.dir_hist
403 407
404 408 # user aliases to input and output histories
405 409 self.user_ns['In'] = self.input_hist
406 410 self.user_ns['Out'] = self.output_hist
407 411
408 412 # Object variable to store code object waiting execution. This is
409 413 # used mainly by the multithreaded shells, but it can come in handy in
410 414 # other situations. No need to use a Queue here, since it's a single
411 415 # item which gets cleared once run.
412 416 self.code_to_run = None
413 417
414 418 # Job manager (for jobs run as background threads)
415 419 self.jobs = BackgroundJobManager()
416 420 # Put the job manager into builtins so it's always there.
417 421 __builtin__.jobs = self.jobs
418 422
419 423 # escapes for automatic behavior on the command line
420 424 self.ESC_SHELL = '!'
421 425 self.ESC_HELP = '?'
422 426 self.ESC_MAGIC = '%'
423 427 self.ESC_QUOTE = ','
424 428 self.ESC_QUOTE2 = ';'
425 429 self.ESC_PAREN = '/'
426 430
427 431 # And their associated handlers
428 432 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
429 433 self.ESC_QUOTE : self.handle_auto,
430 434 self.ESC_QUOTE2 : self.handle_auto,
431 435 self.ESC_MAGIC : self.handle_magic,
432 436 self.ESC_HELP : self.handle_help,
433 437 self.ESC_SHELL : self.handle_shell_escape,
434 438 }
435 439
436 440 # class initializations
437 441 Magic.__init__(self,self)
438 442
439 443 # Python source parser/formatter for syntax highlighting
440 444 pyformat = PyColorize.Parser().format
441 445 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
442 446
443 447 # hooks holds pointers used for user-side customizations
444 448 self.hooks = Struct()
445 449
446 450 # Set all default hooks, defined in the IPython.hooks module.
447 451 hooks = IPython.hooks
448 452 for hook_name in hooks.__all__:
449 453 self.set_hook(hook_name,getattr(hooks,hook_name))
450 454
451 455 # Flag to mark unconditional exit
452 456 self.exit_now = False
453 457
454 458 self.usage_min = """\
455 459 An enhanced console for Python.
456 460 Some of its features are:
457 461 - Readline support if the readline library is present.
458 462 - Tab completion in the local namespace.
459 463 - Logging of input, see command-line options.
460 464 - System shell escape via ! , eg !ls.
461 465 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
462 466 - Keeps track of locally defined variables via %who, %whos.
463 467 - Show object information with a ? eg ?x or x? (use ?? for more info).
464 468 """
465 469 if usage: self.usage = usage
466 470 else: self.usage = self.usage_min
467 471
468 472 # Storage
469 473 self.rc = rc # This will hold all configuration information
470 474 self.inputcache = []
471 475 self._boundcache = []
472 476 self.pager = 'less'
473 477 # temporary files used for various purposes. Deleted at exit.
474 478 self.tempfiles = []
475 479
476 480 # Keep track of readline usage (later set by init_readline)
477 481 self.has_readline = False
478 482
479 483 # template for logfile headers. It gets resolved at runtime by the
480 484 # logstart method.
481 485 self.loghead_tpl = \
482 486 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
483 487 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
484 488 #log# opts = %s
485 489 #log# args = %s
486 490 #log# It is safe to make manual edits below here.
487 491 #log#-----------------------------------------------------------------------
488 492 """
489 493 # for pushd/popd management
490 494 try:
491 495 self.home_dir = get_home_dir()
492 496 except HomeDirError,msg:
493 497 fatal(msg)
494 498
495 499 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
496 500
497 501 # Functions to call the underlying shell.
498 502
499 503 # utility to expand user variables via Itpl
500 504 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
501 505 self.user_ns))
502 506 # The first is similar to os.system, but it doesn't return a value,
503 507 # and it allows interpolation of variables in the user's namespace.
504 508 self.system = lambda cmd: shell(self.var_expand(cmd),
505 509 header='IPython system call: ',
506 510 verbose=self.rc.system_verbose)
507 511 # These are for getoutput and getoutputerror:
508 512 self.getoutput = lambda cmd: \
509 513 getoutput(self.var_expand(cmd),
510 514 header='IPython system call: ',
511 515 verbose=self.rc.system_verbose)
512 516 self.getoutputerror = lambda cmd: \
513 517 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
514 518 self.user_ns)),
515 519 header='IPython system call: ',
516 520 verbose=self.rc.system_verbose)
517 521
518 522 # RegExp for splitting line contents into pre-char//first
519 523 # word-method//rest. For clarity, each group in on one line.
520 524
521 525 # WARNING: update the regexp if the above escapes are changed, as they
522 526 # are hardwired in.
523 527
524 528 # Don't get carried away with trying to make the autocalling catch too
525 529 # much: it's better to be conservative rather than to trigger hidden
526 530 # evals() somewhere and end up causing side effects.
527 531
528 532 self.line_split = re.compile(r'^([\s*,;/])'
529 533 r'([\?\w\.]+\w*\s*)'
530 534 r'(\(?.*$)')
531 535
532 536 # Original re, keep around for a while in case changes break something
533 537 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
534 538 # r'(\s*[\?\w\.]+\w*\s*)'
535 539 # r'(\(?.*$)')
536 540
537 541 # RegExp to identify potential function names
538 542 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
539 543 # RegExp to exclude strings with this start from autocalling
540 544 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
541 545
542 546 # try to catch also methods for stuff in lists/tuples/dicts: off
543 547 # (experimental). For this to work, the line_split regexp would need
544 548 # to be modified so it wouldn't break things at '['. That line is
545 549 # nasty enough that I shouldn't change it until I can test it _well_.
546 550 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
547 551
548 552 # keep track of where we started running (mainly for crash post-mortem)
549 553 self.starting_dir = os.getcwd()
550 554
551 555 # Various switches which can be set
552 556 self.CACHELENGTH = 5000 # this is cheap, it's just text
553 557 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
554 558 self.banner2 = banner2
555 559
556 560 # TraceBack handlers:
557 561
558 562 # Syntax error handler.
559 563 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
560 564
561 565 # The interactive one is initialized with an offset, meaning we always
562 566 # want to remove the topmost item in the traceback, which is our own
563 567 # internal code. Valid modes: ['Plain','Context','Verbose']
564 568 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
565 569 color_scheme='NoColor',
566 570 tb_offset = 1)
567 571
568 572 # IPython itself shouldn't crash. This will produce a detailed
569 573 # post-mortem if it does. But we only install the crash handler for
570 574 # non-threaded shells, the threaded ones use a normal verbose reporter
571 575 # and lose the crash handler. This is because exceptions in the main
572 576 # thread (such as in GUI code) propagate directly to sys.excepthook,
573 577 # and there's no point in printing crash dumps for every user exception.
574 578 if self.isthreaded:
575 579 sys.excepthook = ultraTB.FormattedTB()
576 580 else:
577 581 from IPython import CrashHandler
578 582 sys.excepthook = CrashHandler.CrashHandler(self)
579 583
580 584 # The instance will store a pointer to this, so that runtime code
581 585 # (such as magics) can access it. This is because during the
582 586 # read-eval loop, it gets temporarily overwritten (to deal with GUI
583 587 # frameworks).
584 588 self.sys_excepthook = sys.excepthook
585 589
586 590 # and add any custom exception handlers the user may have specified
587 591 self.set_custom_exc(*custom_exceptions)
588 592
589 593 # Object inspector
590 594 self.inspector = OInspect.Inspector(OInspect.InspectColors,
591 595 PyColorize.ANSICodeColors,
592 596 'NoColor')
593 597 # indentation management
594 598 self.autoindent = False
595 599 self.indent_current_nsp = 0
596 600 self.indent_current = '' # actual indent string
597 601
598 602 # Make some aliases automatically
599 603 # Prepare list of shell aliases to auto-define
600 604 if os.name == 'posix':
601 605 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
602 606 'mv mv -i','rm rm -i','cp cp -i',
603 607 'cat cat','less less','clear clear',
604 608 # a better ls
605 609 'ls ls -F',
606 610 # long ls
607 611 'll ls -lF',
608 612 # color ls
609 613 'lc ls -F -o --color',
610 614 # ls normal files only
611 615 'lf ls -F -o --color %l | grep ^-',
612 616 # ls symbolic links
613 617 'lk ls -F -o --color %l | grep ^l',
614 618 # directories or links to directories,
615 619 'ldir ls -F -o --color %l | grep /$',
616 620 # things which are executable
617 621 'lx ls -F -o --color %l | grep ^-..x',
618 622 )
619 623 elif os.name in ['nt','dos']:
620 624 auto_alias = ('dir dir /on', 'ls dir /on',
621 625 'ddir dir /ad /on', 'ldir dir /ad /on',
622 626 'mkdir mkdir','rmdir rmdir','echo echo',
623 627 'ren ren','cls cls','copy copy')
624 628 else:
625 629 auto_alias = ()
626 630 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
627 631 # Call the actual (public) initializer
628 632 self.init_auto_alias()
629 633 # end __init__
630 634
631 635 def post_config_initialization(self):
632 636 """Post configuration init method
633 637
634 638 This is called after the configuration files have been processed to
635 639 'finalize' the initialization."""
636 640
637 641 rc = self.rc
638 642
639 643 # Load readline proper
640 644 if rc.readline:
641 645 self.init_readline()
642 646
643 647 # log system
644 648 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
645 649 # local shortcut, this is used a LOT
646 650 self.log = self.logger.log
647 651
648 652 # Initialize cache, set in/out prompts and printing system
649 653 self.outputcache = CachedOutput(self,
650 654 rc.cache_size,
651 655 rc.pprint,
652 656 input_sep = rc.separate_in,
653 657 output_sep = rc.separate_out,
654 658 output_sep2 = rc.separate_out2,
655 659 ps1 = rc.prompt_in1,
656 660 ps2 = rc.prompt_in2,
657 661 ps_out = rc.prompt_out,
658 662 pad_left = rc.prompts_pad_left)
659 663
660 664 # user may have over-ridden the default print hook:
661 665 try:
662 666 self.outputcache.__class__.display = self.hooks.display
663 667 except AttributeError:
664 668 pass
665 669
666 670 # I don't like assigning globally to sys, because it means when embedding
667 671 # instances, each embedded instance overrides the previous choice. But
668 672 # sys.displayhook seems to be called internally by exec, so I don't see a
669 673 # way around it.
670 674 sys.displayhook = self.outputcache
671 675
672 676 # Set user colors (don't do it in the constructor above so that it
673 677 # doesn't crash if colors option is invalid)
674 678 self.magic_colors(rc.colors)
675 679
676 680 # Set calling of pdb on exceptions
677 681 self.call_pdb = rc.pdb
678 682
679 683 # Load user aliases
680 684 for alias in rc.alias:
681 685 self.magic_alias(alias)
682 686
683 687 # dynamic data that survives through sessions
684 688 # XXX make the filename a config option?
685 689 persist_base = 'persist'
686 690 if rc.profile:
687 691 persist_base += '_%s' % rc.profile
688 692 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
689 693
690 694 try:
691 695 self.persist = pickle.load(file(self.persist_fname))
692 696 except:
693 697 self.persist = {}
694 698
695 699
696 700 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
697 701 try:
698 702 obj = pickle.loads(value)
699 703 except:
700 704
701 705 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
702 706 print "The error was:",sys.exc_info()[0]
703 707 continue
704 708
705 709
706 710 self.user_ns[key] = obj
707 711
708 712
709 713
710 714
711 715 def set_hook(self,name,hook):
712 716 """set_hook(name,hook) -> sets an internal IPython hook.
713 717
714 718 IPython exposes some of its internal API as user-modifiable hooks. By
715 719 resetting one of these hooks, you can modify IPython's behavior to
716 720 call at runtime your own routines."""
717 721
718 722 # At some point in the future, this should validate the hook before it
719 723 # accepts it. Probably at least check that the hook takes the number
720 724 # of args it's supposed to.
721 725 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
722 726
723 727 def set_custom_exc(self,exc_tuple,handler):
724 728 """set_custom_exc(exc_tuple,handler)
725 729
726 730 Set a custom exception handler, which will be called if any of the
727 731 exceptions in exc_tuple occur in the mainloop (specifically, in the
728 732 runcode() method.
729 733
730 734 Inputs:
731 735
732 736 - exc_tuple: a *tuple* of valid exceptions to call the defined
733 737 handler for. It is very important that you use a tuple, and NOT A
734 738 LIST here, because of the way Python's except statement works. If
735 739 you only want to trap a single exception, use a singleton tuple:
736 740
737 741 exc_tuple == (MyCustomException,)
738 742
739 743 - handler: this must be defined as a function with the following
740 744 basic interface: def my_handler(self,etype,value,tb).
741 745
742 746 This will be made into an instance method (via new.instancemethod)
743 747 of IPython itself, and it will be called if any of the exceptions
744 748 listed in the exc_tuple are caught. If the handler is None, an
745 749 internal basic one is used, which just prints basic info.
746 750
747 751 WARNING: by putting in your own exception handler into IPython's main
748 752 execution loop, you run a very good chance of nasty crashes. This
749 753 facility should only be used if you really know what you are doing."""
750 754
751 755 assert type(exc_tuple)==type(()) , \
752 756 "The custom exceptions must be given AS A TUPLE."
753 757
754 758 def dummy_handler(self,etype,value,tb):
755 759 print '*** Simple custom exception handler ***'
756 760 print 'Exception type :',etype
757 761 print 'Exception value:',value
758 762 print 'Traceback :',tb
759 763 print 'Source code :','\n'.join(self.buffer)
760 764
761 765 if handler is None: handler = dummy_handler
762 766
763 767 self.CustomTB = new.instancemethod(handler,self,self.__class__)
764 768 self.custom_exceptions = exc_tuple
765 769
766 770 def set_custom_completer(self,completer,pos=0):
767 771 """set_custom_completer(completer,pos=0)
768 772
769 773 Adds a new custom completer function.
770 774
771 775 The position argument (defaults to 0) is the index in the completers
772 776 list where you want the completer to be inserted."""
773 777
774 778 newcomp = new.instancemethod(completer,self.Completer,
775 779 self.Completer.__class__)
776 780 self.Completer.matchers.insert(pos,newcomp)
777 781
778 782 def _get_call_pdb(self):
779 783 return self._call_pdb
780 784
781 785 def _set_call_pdb(self,val):
782 786
783 787 if val not in (0,1,False,True):
784 788 raise ValueError,'new call_pdb value must be boolean'
785 789
786 790 # store value in instance
787 791 self._call_pdb = val
788 792
789 793 # notify the actual exception handlers
790 794 self.InteractiveTB.call_pdb = val
791 795 if self.isthreaded:
792 796 try:
793 797 self.sys_excepthook.call_pdb = val
794 798 except:
795 799 warn('Failed to activate pdb for threaded exception handler')
796 800
797 801 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
798 802 'Control auto-activation of pdb at exceptions')
799 803
800 804 def complete(self,text):
801 805 """Return a sorted list of all possible completions on text.
802 806
803 807 Inputs:
804 808
805 809 - text: a string of text to be completed on.
806 810
807 811 This is a wrapper around the completion mechanism, similar to what
808 812 readline does at the command line when the TAB key is hit. By
809 813 exposing it as a method, it can be used by other non-readline
810 814 environments (such as GUIs) for text completion.
811 815
812 816 Simple usage example:
813 817
814 818 In [1]: x = 'hello'
815 819
816 820 In [2]: __IP.complete('x.l')
817 821 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
818 822
819 823 complete = self.Completer.complete
820 824 state = 0
821 825 # use a dict so we get unique keys, since ipyhton's multiple
822 826 # completers can return duplicates.
823 827 comps = {}
824 828 while True:
825 829 newcomp = complete(text,state)
826 830 if newcomp is None:
827 831 break
828 832 comps[newcomp] = 1
829 833 state += 1
830 834 outcomps = comps.keys()
831 835 outcomps.sort()
832 836 return outcomps
833 837
834 838 def set_completer_frame(self, frame):
835 839 if frame:
836 840 self.Completer.namespace = frame.f_locals
837 841 self.Completer.global_namespace = frame.f_globals
838 842 else:
839 843 self.Completer.namespace = self.user_ns
840 844 self.Completer.global_namespace = self.user_global_ns
841 845
842 846 def init_auto_alias(self):
843 847 """Define some aliases automatically.
844 848
845 849 These are ALL parameter-less aliases"""
846 850 for alias,cmd in self.auto_alias:
847 851 self.alias_table[alias] = (0,cmd)
848 852
849 853 def alias_table_validate(self,verbose=0):
850 854 """Update information about the alias table.
851 855
852 856 In particular, make sure no Python keywords/builtins are in it."""
853 857
854 858 no_alias = self.no_alias
855 859 for k in self.alias_table.keys():
856 860 if k in no_alias:
857 861 del self.alias_table[k]
858 862 if verbose:
859 863 print ("Deleting alias <%s>, it's a Python "
860 864 "keyword or builtin." % k)
861 865
862 866 def set_autoindent(self,value=None):
863 867 """Set the autoindent flag, checking for readline support.
864 868
865 869 If called with no arguments, it acts as a toggle."""
866 870
867 871 if not self.has_readline:
868 872 if os.name == 'posix':
869 873 warn("The auto-indent feature requires the readline library")
870 874 self.autoindent = 0
871 875 return
872 876 if value is None:
873 877 self.autoindent = not self.autoindent
874 878 else:
875 879 self.autoindent = value
876 880
877 881 def rc_set_toggle(self,rc_field,value=None):
878 882 """Set or toggle a field in IPython's rc config. structure.
879 883
880 884 If called with no arguments, it acts as a toggle.
881 885
882 886 If called with a non-existent field, the resulting AttributeError
883 887 exception will propagate out."""
884 888
885 889 rc_val = getattr(self.rc,rc_field)
886 890 if value is None:
887 891 value = not rc_val
888 892 setattr(self.rc,rc_field,value)
889 893
890 894 def user_setup(self,ipythondir,rc_suffix,mode='install'):
891 895 """Install the user configuration directory.
892 896
893 897 Can be called when running for the first time or to upgrade the user's
894 898 .ipython/ directory with the mode parameter. Valid modes are 'install'
895 899 and 'upgrade'."""
896 900
897 901 def wait():
898 902 try:
899 903 raw_input("Please press <RETURN> to start IPython.")
900 904 except EOFError:
901 905 print >> Term.cout
902 906 print '*'*70
903 907
904 908 cwd = os.getcwd() # remember where we started
905 909 glb = glob.glob
906 910 print '*'*70
907 911 if mode == 'install':
908 912 print \
909 913 """Welcome to IPython. I will try to create a personal configuration directory
910 914 where you can customize many aspects of IPython's functionality in:\n"""
911 915 else:
912 916 print 'I am going to upgrade your configuration in:'
913 917
914 918 print ipythondir
915 919
916 920 rcdirend = os.path.join('IPython','UserConfig')
917 921 cfg = lambda d: os.path.join(d,rcdirend)
918 922 try:
919 923 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
920 924 except IOError:
921 925 warning = """
922 926 Installation error. IPython's directory was not found.
923 927
924 928 Check the following:
925 929
926 930 The ipython/IPython directory should be in a directory belonging to your
927 931 PYTHONPATH environment variable (that is, it should be in a directory
928 932 belonging to sys.path). You can copy it explicitly there or just link to it.
929 933
930 934 IPython will proceed with builtin defaults.
931 935 """
932 936 warn(warning)
933 937 wait()
934 938 return
935 939
936 940 if mode == 'install':
937 941 try:
938 942 shutil.copytree(rcdir,ipythondir)
939 943 os.chdir(ipythondir)
940 944 rc_files = glb("ipythonrc*")
941 945 for rc_file in rc_files:
942 946 os.rename(rc_file,rc_file+rc_suffix)
943 947 except:
944 948 warning = """
945 949
946 950 There was a problem with the installation:
947 951 %s
948 952 Try to correct it or contact the developers if you think it's a bug.
949 953 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
950 954 warn(warning)
951 955 wait()
952 956 return
953 957
954 958 elif mode == 'upgrade':
955 959 try:
956 960 os.chdir(ipythondir)
957 961 except:
958 962 print """
959 963 Can not upgrade: changing to directory %s failed. Details:
960 964 %s
961 965 """ % (ipythondir,sys.exc_info()[1])
962 966 wait()
963 967 return
964 968 else:
965 969 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
966 970 for new_full_path in sources:
967 971 new_filename = os.path.basename(new_full_path)
968 972 if new_filename.startswith('ipythonrc'):
969 973 new_filename = new_filename + rc_suffix
970 974 # The config directory should only contain files, skip any
971 975 # directories which may be there (like CVS)
972 976 if os.path.isdir(new_full_path):
973 977 continue
974 978 if os.path.exists(new_filename):
975 979 old_file = new_filename+'.old'
976 980 if os.path.exists(old_file):
977 981 os.remove(old_file)
978 982 os.rename(new_filename,old_file)
979 983 shutil.copy(new_full_path,new_filename)
980 984 else:
981 985 raise ValueError,'unrecognized mode for install:',`mode`
982 986
983 987 # Fix line-endings to those native to each platform in the config
984 988 # directory.
985 989 try:
986 990 os.chdir(ipythondir)
987 991 except:
988 992 print """
989 993 Problem: changing to directory %s failed.
990 994 Details:
991 995 %s
992 996
993 997 Some configuration files may have incorrect line endings. This should not
994 998 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
995 999 wait()
996 1000 else:
997 1001 for fname in glb('ipythonrc*'):
998 1002 try:
999 1003 native_line_ends(fname,backup=0)
1000 1004 except IOError:
1001 1005 pass
1002 1006
1003 1007 if mode == 'install':
1004 1008 print """
1005 1009 Successful installation!
1006 1010
1007 1011 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1008 1012 IPython manual (there are both HTML and PDF versions supplied with the
1009 1013 distribution) to make sure that your system environment is properly configured
1010 1014 to take advantage of IPython's features."""
1011 1015 else:
1012 1016 print """
1013 1017 Successful upgrade!
1014 1018
1015 1019 All files in your directory:
1016 1020 %(ipythondir)s
1017 1021 which would have been overwritten by the upgrade were backed up with a .old
1018 1022 extension. If you had made particular customizations in those files you may
1019 1023 want to merge them back into the new files.""" % locals()
1020 1024 wait()
1021 1025 os.chdir(cwd)
1022 1026 # end user_setup()
1023 1027
1024 1028 def atexit_operations(self):
1025 1029 """This will be executed at the time of exit.
1026 1030
1027 1031 Saving of persistent data should be performed here. """
1028 1032
1029 1033 # input history
1030 1034 self.savehist()
1031 1035
1032 1036 # Cleanup all tempfiles left around
1033 1037 for tfile in self.tempfiles:
1034 1038 try:
1035 1039 os.unlink(tfile)
1036 1040 except OSError:
1037 1041 pass
1038 1042
1039 1043 # save the "persistent data" catch-all dictionary
1040 1044 try:
1041 1045 pickle.dump(self.persist, open(self.persist_fname,"w"))
1042 1046 except:
1043 1047 print "*** ERROR *** persistent data saving failed."
1044 1048
1045 1049 def savehist(self):
1046 1050 """Save input history to a file (via readline library)."""
1047 1051 try:
1048 1052 self.readline.write_history_file(self.histfile)
1049 1053 except:
1050 1054 print 'Unable to save IPython command history to file: ' + \
1051 1055 `self.histfile`
1052 1056
1053 1057 def pre_readline(self):
1054 1058 """readline hook to be used at the start of each line.
1055 1059
1056 1060 Currently it handles auto-indent only."""
1057 1061
1058 1062 self.readline.insert_text(self.indent_current)
1059 1063
1060 1064 def init_readline(self):
1061 1065 """Command history completion/saving/reloading."""
1062 1066 try:
1063 1067 import readline
1064 1068 except ImportError:
1065 1069 self.has_readline = 0
1066 1070 self.readline = None
1067 1071 # no point in bugging windows users with this every time:
1068 1072 if os.name == 'posix':
1069 1073 warn('Readline services not available on this platform.')
1070 1074 else:
1071 1075 import atexit
1072 1076 from IPython.completer import IPCompleter
1073 1077 self.Completer = IPCompleter(self,
1074 1078 self.user_ns,
1075 1079 self.user_global_ns,
1076 1080 self.rc.readline_omit__names,
1077 1081 self.alias_table)
1078 1082
1079 1083 # Platform-specific configuration
1080 1084 if os.name == 'nt':
1081 1085 self.readline_startup_hook = readline.set_pre_input_hook
1082 1086 else:
1083 1087 self.readline_startup_hook = readline.set_startup_hook
1084 1088
1085 1089 # Load user's initrc file (readline config)
1086 1090 inputrc_name = os.environ.get('INPUTRC')
1087 1091 if inputrc_name is None:
1088 1092 home_dir = get_home_dir()
1089 1093 if home_dir is not None:
1090 1094 inputrc_name = os.path.join(home_dir,'.inputrc')
1091 1095 if os.path.isfile(inputrc_name):
1092 1096 try:
1093 1097 readline.read_init_file(inputrc_name)
1094 1098 except:
1095 1099 warn('Problems reading readline initialization file <%s>'
1096 1100 % inputrc_name)
1097 1101
1098 1102 self.has_readline = 1
1099 1103 self.readline = readline
1100 1104 # save this in sys so embedded copies can restore it properly
1101 1105 sys.ipcompleter = self.Completer.complete
1102 1106 readline.set_completer(self.Completer.complete)
1103 1107
1104 1108 # Configure readline according to user's prefs
1105 1109 for rlcommand in self.rc.readline_parse_and_bind:
1106 1110 readline.parse_and_bind(rlcommand)
1107 1111
1108 1112 # remove some chars from the delimiters list
1109 1113 delims = readline.get_completer_delims()
1110 1114 delims = delims.translate(string._idmap,
1111 1115 self.rc.readline_remove_delims)
1112 1116 readline.set_completer_delims(delims)
1113 1117 # otherwise we end up with a monster history after a while:
1114 1118 readline.set_history_length(1000)
1115 1119 try:
1116 1120 #print '*** Reading readline history' # dbg
1117 1121 readline.read_history_file(self.histfile)
1118 1122 except IOError:
1119 1123 pass # It doesn't exist yet.
1120 1124
1121 1125 atexit.register(self.atexit_operations)
1122 1126 del atexit
1123 1127
1124 1128 # Configure auto-indent for all platforms
1125 1129 self.set_autoindent(self.rc.autoindent)
1126 1130
1127 1131 def _should_recompile(self,e):
1128 1132 """Utility routine for edit_syntax_error"""
1129 1133
1130 1134 if e.filename in ('<ipython console>','<input>','<string>',
1131 1135 '<console>'):
1132 1136 return False
1133 1137 try:
1134 1138 if not ask_yes_no('Return to editor to correct syntax error? '
1135 1139 '[Y/n] ','y'):
1136 1140 return False
1137 1141 except EOFError:
1138 1142 return False
1139 1143 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1140 1144 return True
1141 1145
1142 1146 def edit_syntax_error(self):
1143 1147 """The bottom half of the syntax error handler called in the main loop.
1144 1148
1145 1149 Loop until syntax error is fixed or user cancels.
1146 1150 """
1147 1151
1148 1152 while self.SyntaxTB.last_syntax_error:
1149 1153 # copy and clear last_syntax_error
1150 1154 err = self.SyntaxTB.clear_err_state()
1151 1155 if not self._should_recompile(err):
1152 1156 return
1153 1157 try:
1154 1158 # may set last_syntax_error again if a SyntaxError is raised
1155 1159 self.safe_execfile(err.filename,self.shell.user_ns)
1156 1160 except:
1157 1161 self.showtraceback()
1158 1162 else:
1159 1163 f = file(err.filename)
1160 1164 try:
1161 1165 sys.displayhook(f.read())
1162 1166 finally:
1163 1167 f.close()
1164 1168
1165 1169 def showsyntaxerror(self, filename=None):
1166 1170 """Display the syntax error that just occurred.
1167 1171
1168 1172 This doesn't display a stack trace because there isn't one.
1169 1173
1170 1174 If a filename is given, it is stuffed in the exception instead
1171 1175 of what was there before (because Python's parser always uses
1172 1176 "<string>" when reading from a string).
1173 1177 """
1174 type, value, sys.last_traceback = sys.exc_info()
1175 sys.last_type = type
1176 sys.last_value = value
1177 if filename and type is SyntaxError:
1178 etype, value, last_traceback = sys.exc_info()
1179 if filename and etype is SyntaxError:
1178 1180 # Work hard to stuff the correct filename in the exception
1179 1181 try:
1180 1182 msg, (dummy_filename, lineno, offset, line) = value
1181 1183 except:
1182 1184 # Not the format we expect; leave it alone
1183 1185 pass
1184 1186 else:
1185 1187 # Stuff in the right filename
1186 1188 try:
1187 1189 # Assume SyntaxError is a class exception
1188 1190 value = SyntaxError(msg, (filename, lineno, offset, line))
1189 1191 except:
1190 1192 # If that failed, assume SyntaxError is a string
1191 1193 value = msg, (filename, lineno, offset, line)
1192 self.SyntaxTB(type,value,[])
1194 self.SyntaxTB(etype,value,[])
1193 1195
1194 1196 def debugger(self):
1195 1197 """Call the pdb debugger."""
1196 1198
1197 1199 if not self.rc.pdb:
1198 1200 return
1199 1201 pdb.pm()
1200 1202
1201 1203 def showtraceback(self,exc_tuple = None,filename=None):
1202 1204 """Display the exception that just occurred."""
1203 1205
1204 1206 # Though this won't be called by syntax errors in the input line,
1205 1207 # there may be SyntaxError cases whith imported code.
1206 1208 if exc_tuple is None:
1207 1209 type, value, tb = sys.exc_info()
1208 1210 else:
1209 1211 type, value, tb = exc_tuple
1210 1212 if type is SyntaxError:
1211 1213 self.showsyntaxerror(filename)
1212 1214 else:
1213 sys.last_type = type
1214 sys.last_value = value
1215 sys.last_traceback = tb
1216 1215 self.InteractiveTB()
1217 1216 if self.InteractiveTB.call_pdb and self.has_readline:
1218 1217 # pdb mucks up readline, fix it back
1219 1218 self.readline.set_completer(self.Completer.complete)
1220 1219
1221 1220 def update_cache(self, line):
1222 1221 """puts line into cache"""
1223 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1222 return # dbg
1223
1224 # This copies the cache every time ... :-(
1225 self.inputcache.insert(0, line)
1224 1226 if len(self.inputcache) >= self.CACHELENGTH:
1225 1227 self.inputcache.pop() # This doesn't :-)
1226 1228
1227 1229 def mainloop(self,banner=None):
1228 1230 """Creates the local namespace and starts the mainloop.
1229 1231
1230 1232 If an optional banner argument is given, it will override the
1231 1233 internally created default banner."""
1232 1234
1233 1235 if self.rc.c: # Emulate Python's -c option
1234 1236 self.exec_init_cmd()
1235 1237 if banner is None:
1236 1238 if self.rc.banner:
1237 1239 banner = self.BANNER+self.banner2
1238 1240 else:
1239 1241 banner = ''
1240 1242 self.interact(banner)
1241 1243
1242 1244 def exec_init_cmd(self):
1243 1245 """Execute a command given at the command line.
1244 1246
1245 1247 This emulates Python's -c option."""
1246 1248
1247 1249 sys.argv = ['-c']
1248 1250 self.push(self.rc.c)
1249 1251
1250 1252 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1251 1253 """Embeds IPython into a running python program.
1252 1254
1253 1255 Input:
1254 1256
1255 1257 - header: An optional header message can be specified.
1256 1258
1257 1259 - local_ns, global_ns: working namespaces. If given as None, the
1258 1260 IPython-initialized one is updated with __main__.__dict__, so that
1259 1261 program variables become visible but user-specific configuration
1260 1262 remains possible.
1261 1263
1262 1264 - stack_depth: specifies how many levels in the stack to go to
1263 1265 looking for namespaces (when local_ns and global_ns are None). This
1264 1266 allows an intermediate caller to make sure that this function gets
1265 1267 the namespace from the intended level in the stack. By default (0)
1266 1268 it will get its locals and globals from the immediate caller.
1267 1269
1268 1270 Warning: it's possible to use this in a program which is being run by
1269 1271 IPython itself (via %run), but some funny things will happen (a few
1270 1272 globals get overwritten). In the future this will be cleaned up, as
1271 1273 there is no fundamental reason why it can't work perfectly."""
1272 1274
1273 1275 # Get locals and globals from caller
1274 1276 if local_ns is None or global_ns is None:
1275 1277 call_frame = sys._getframe(stack_depth).f_back
1276 1278
1277 1279 if local_ns is None:
1278 1280 local_ns = call_frame.f_locals
1279 1281 if global_ns is None:
1280 1282 global_ns = call_frame.f_globals
1281 1283
1282 1284 # Update namespaces and fire up interpreter
1283 1285 self.user_ns = local_ns
1284 1286 self.user_global_ns = global_ns
1285 1287
1286 1288 # Patch for global embedding to make sure that things don't overwrite
1287 1289 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1288 1290 # FIXME. Test this a bit more carefully (the if.. is new)
1289 1291 if local_ns is None and global_ns is None:
1290 1292 self.user_global_ns.update(__main__.__dict__)
1291 1293
1292 1294 # make sure the tab-completer has the correct frame information, so it
1293 1295 # actually completes using the frame's locals/globals
1294 1296 self.set_completer_frame(call_frame)
1295 1297
1296 1298 self.interact(header)
1297 1299
1298 1300 def interact(self, banner=None):
1299 1301 """Closely emulate the interactive Python console.
1300 1302
1301 1303 The optional banner argument specify the banner to print
1302 1304 before the first interaction; by default it prints a banner
1303 1305 similar to the one printed by the real Python interpreter,
1304 1306 followed by the current class name in parentheses (so as not
1305 1307 to confuse this with the real interpreter -- since it's so
1306 1308 close!).
1307 1309
1308 1310 """
1309 1311 cprt = 'Type "copyright", "credits" or "license" for more information.'
1310 1312 if banner is None:
1311 1313 self.write("Python %s on %s\n%s\n(%s)\n" %
1312 1314 (sys.version, sys.platform, cprt,
1313 1315 self.__class__.__name__))
1314 1316 else:
1315 1317 self.write(banner)
1316 1318
1317 1319 more = 0
1318 1320
1319 1321 # Mark activity in the builtins
1320 1322 __builtin__.__dict__['__IPYTHON__active'] += 1
1321 1323
1322 # compiled regexps for autoindent management
1323 ini_spaces_re = re.compile(r'^(\s+)')
1324 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
1325
1326 1324 # exit_now is set by a call to %Exit or %Quit
1327 1325 while not self.exit_now:
1328 1326 try:
1329 1327 if more:
1330 1328 prompt = self.outputcache.prompt2
1331 1329 if self.autoindent:
1332 1330 self.readline_startup_hook(self.pre_readline)
1333 1331 else:
1334 1332 prompt = self.outputcache.prompt1
1335 1333 try:
1336 1334 line = self.raw_input(prompt,more)
1337 1335 if self.autoindent:
1338 1336 self.readline_startup_hook(None)
1339 1337 except EOFError:
1340 1338 if self.autoindent:
1341 1339 self.readline_startup_hook(None)
1342 1340 self.write("\n")
1343 1341 self.exit()
1344 1342 else:
1345 1343 more = self.push(line)
1346 # Auto-indent management
1347 if self.autoindent:
1348 if line:
1349 ini_spaces = ini_spaces_re.match(line)
1350 if ini_spaces:
1351 nspaces = ini_spaces.end()
1352 else:
1353 nspaces = 0
1354 self.indent_current_nsp = nspaces
1355
1356 if line[-1] == ':':
1357 self.indent_current_nsp += 4
1358 elif dedent_re.match(line):
1359 self.indent_current_nsp -= 4
1360 else:
1361 self.indent_current_nsp = 0
1362
1363 # indent_current is the actual string to be inserted
1364 # by the readline hooks for indentation
1365 self.indent_current = ' '* self.indent_current_nsp
1366 1344
1367 1345 if (self.SyntaxTB.last_syntax_error and
1368 1346 self.rc.autoedit_syntax):
1369 1347 self.edit_syntax_error()
1370 1348
1371 1349 except KeyboardInterrupt:
1372 1350 self.write("\nKeyboardInterrupt\n")
1373 1351 self.resetbuffer()
1374 1352 more = 0
1375 1353 # keep cache in sync with the prompt counter:
1376 1354 self.outputcache.prompt_count -= 1
1377 1355
1378 1356 if self.autoindent:
1379 1357 self.indent_current_nsp = 0
1380 1358 self.indent_current = ' '* self.indent_current_nsp
1381 1359
1382 1360 except bdb.BdbQuit:
1383 1361 warn("The Python debugger has exited with a BdbQuit exception.\n"
1384 1362 "Because of how pdb handles the stack, it is impossible\n"
1385 1363 "for IPython to properly format this particular exception.\n"
1386 1364 "IPython will resume normal operation.")
1387 1365
1388 1366 # We are off again...
1389 1367 __builtin__.__dict__['__IPYTHON__active'] -= 1
1390 1368
1391 1369 def excepthook(self, type, value, tb):
1392 1370 """One more defense for GUI apps that call sys.excepthook.
1393 1371
1394 1372 GUI frameworks like wxPython trap exceptions and call
1395 1373 sys.excepthook themselves. I guess this is a feature that
1396 1374 enables them to keep running after exceptions that would
1397 1375 otherwise kill their mainloop. This is a bother for IPython
1398 1376 which excepts to catch all of the program exceptions with a try:
1399 1377 except: statement.
1400 1378
1401 1379 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1402 1380 any app directly invokes sys.excepthook, it will look to the user like
1403 1381 IPython crashed. In order to work around this, we can disable the
1404 1382 CrashHandler and replace it with this excepthook instead, which prints a
1405 1383 regular traceback using our InteractiveTB. In this fashion, apps which
1406 1384 call sys.excepthook will generate a regular-looking exception from
1407 1385 IPython, and the CrashHandler will only be triggered by real IPython
1408 1386 crashes.
1409 1387
1410 1388 This hook should be used sparingly, only in places which are not likely
1411 1389 to be true IPython errors.
1412 1390 """
1413 1391
1414 1392 self.InteractiveTB(type, value, tb, tb_offset=0)
1415 1393 if self.InteractiveTB.call_pdb and self.has_readline:
1416 1394 self.readline.set_completer(self.Completer.complete)
1417 1395
1418 1396 def call_alias(self,alias,rest=''):
1419 1397 """Call an alias given its name and the rest of the line.
1420 1398
1421 1399 This function MUST be given a proper alias, because it doesn't make
1422 1400 any checks when looking up into the alias table. The caller is
1423 1401 responsible for invoking it only with a valid alias."""
1424 1402
1425 1403 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1426 1404 nargs,cmd = self.alias_table[alias]
1427 1405 # Expand the %l special to be the user's input line
1428 1406 if cmd.find('%l') >= 0:
1429 1407 cmd = cmd.replace('%l',rest)
1430 1408 rest = ''
1431 1409 if nargs==0:
1432 1410 # Simple, argument-less aliases
1433 1411 cmd = '%s %s' % (cmd,rest)
1434 1412 else:
1435 1413 # Handle aliases with positional arguments
1436 1414 args = rest.split(None,nargs)
1437 1415 if len(args)< nargs:
1438 1416 error('Alias <%s> requires %s arguments, %s given.' %
1439 1417 (alias,nargs,len(args)))
1440 1418 return
1441 1419 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1442 1420 # Now call the macro, evaluating in the user's namespace
1443 1421 try:
1444 1422 self.system(cmd)
1445 1423 except:
1446 1424 self.showtraceback()
1447 1425
1426 def autoindent_update(self,line):
1427 """Keep track of the indent level."""
1428 if self.autoindent:
1429 if line:
1430 ini_spaces = ini_spaces_re.match(line)
1431 if ini_spaces:
1432 nspaces = ini_spaces.end()
1433 else:
1434 nspaces = 0
1435 self.indent_current_nsp = nspaces
1436
1437 if line[-1] == ':':
1438 self.indent_current_nsp += 4
1439 elif dedent_re.match(line):
1440 self.indent_current_nsp -= 4
1441 else:
1442 self.indent_current_nsp = 0
1443
1444 # indent_current is the actual string to be inserted
1445 # by the readline hooks for indentation
1446 self.indent_current = ' '* self.indent_current_nsp
1447
1448 1448 def runlines(self,lines):
1449 1449 """Run a string of one or more lines of source.
1450 1450
1451 1451 This method is capable of running a string containing multiple source
1452 1452 lines, as if they had been entered at the IPython prompt. Since it
1453 1453 exposes IPython's processing machinery, the given strings can contain
1454 1454 magic calls (%magic), special shell access (!cmd), etc."""
1455 1455
1456 1456 # We must start with a clean buffer, in case this is run from an
1457 1457 # interactive IPython session (via a magic, for example).
1458 1458 self.resetbuffer()
1459 1459 lines = lines.split('\n')
1460 1460 more = 0
1461 1461 for line in lines:
1462 1462 # skip blank lines so we don't mess up the prompt counter, but do
1463 1463 # NOT skip even a blank line if we are in a code block (more is
1464 1464 # true)
1465 #print 'rl line:<%s>' % line # dbg
1465 1466 if line or more:
1466 more = self.push((self.prefilter(line,more)))
1467 #print 'doit' # dbg
1468 newline = self.prefilter(line,more)
1469 more = self.push(newline)
1467 1470 # IPython's runsource returns None if there was an error
1468 1471 # compiling the code. This allows us to stop processing right
1469 1472 # away, so the user gets the error message at the right place.
1470 1473 if more is None:
1471 1474 break
1472 1475 # final newline in case the input didn't have it, so that the code
1473 1476 # actually does get executed
1474 1477 if more:
1475 1478 self.push('\n')
1476 1479
1477 1480 def runsource(self, source, filename='<input>', symbol='single'):
1478 1481 """Compile and run some source in the interpreter.
1479 1482
1480 1483 Arguments are as for compile_command().
1481 1484
1482 1485 One several things can happen:
1483 1486
1484 1487 1) The input is incorrect; compile_command() raised an
1485 1488 exception (SyntaxError or OverflowError). A syntax traceback
1486 1489 will be printed by calling the showsyntaxerror() method.
1487 1490
1488 1491 2) The input is incomplete, and more input is required;
1489 1492 compile_command() returned None. Nothing happens.
1490 1493
1491 1494 3) The input is complete; compile_command() returned a code
1492 1495 object. The code is executed by calling self.runcode() (which
1493 1496 also handles run-time exceptions, except for SystemExit).
1494 1497
1495 1498 The return value is:
1496 1499
1497 1500 - True in case 2
1498 1501
1499 1502 - False in the other cases, unless an exception is raised, where
1500 1503 None is returned instead. This can be used by external callers to
1501 1504 know whether to continue feeding input or not.
1502 1505
1503 1506 The return value can be used to decide whether to use sys.ps1 or
1504 1507 sys.ps2 to prompt the next line."""
1505 1508
1506 1509 try:
1507 1510 code = self.compile(source,filename,symbol)
1508 1511 except (OverflowError, SyntaxError, ValueError):
1509 1512 # Case 1
1510 1513 self.showsyntaxerror(filename)
1511 1514 return None
1512 1515
1513 1516 if code is None:
1514 1517 # Case 2
1515 1518 return True
1516 1519
1517 1520 # Case 3
1518 1521 # We store the code object so that threaded shells and
1519 1522 # custom exception handlers can access all this info if needed.
1520 1523 # The source corresponding to this can be obtained from the
1521 1524 # buffer attribute as '\n'.join(self.buffer).
1522 1525 self.code_to_run = code
1523 1526 # now actually execute the code object
1524 1527 if self.runcode(code) == 0:
1525 1528 return False
1526 1529 else:
1527 1530 return None
1528 1531
1529 1532 def runcode(self,code_obj):
1530 1533 """Execute a code object.
1531 1534
1532 1535 When an exception occurs, self.showtraceback() is called to display a
1533 1536 traceback.
1534 1537
1535 1538 Return value: a flag indicating whether the code to be run completed
1536 1539 successfully:
1537 1540
1538 1541 - 0: successful execution.
1539 1542 - 1: an error occurred.
1540 1543 """
1541 1544
1542 1545 # Set our own excepthook in case the user code tries to call it
1543 1546 # directly, so that the IPython crash handler doesn't get triggered
1544 1547 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1545 1548
1546 1549 # we save the original sys.excepthook in the instance, in case config
1547 1550 # code (such as magics) needs access to it.
1548 1551 self.sys_excepthook = old_excepthook
1549 1552 outflag = 1 # happens in more places, so it's easier as default
1550 1553 try:
1551 1554 try:
1552 1555 # Embedded instances require separate global/local namespaces
1553 1556 # so they can see both the surrounding (local) namespace and
1554 1557 # the module-level globals when called inside another function.
1555 1558 if self.embedded:
1556 1559 exec code_obj in self.user_global_ns, self.user_ns
1557 1560 # Normal (non-embedded) instances should only have a single
1558 1561 # namespace for user code execution, otherwise functions won't
1559 1562 # see interactive top-level globals.
1560 1563 else:
1561 1564 exec code_obj in self.user_ns
1562 1565 finally:
1563 1566 # Reset our crash handler in place
1564 1567 sys.excepthook = old_excepthook
1565 1568 except SystemExit:
1566 1569 self.resetbuffer()
1567 1570 self.showtraceback()
1568 1571 warn("Type exit or quit to exit IPython "
1569 1572 "(%Exit or %Quit do so unconditionally).",level=1)
1570 1573 except self.custom_exceptions:
1571 1574 etype,value,tb = sys.exc_info()
1572 1575 self.CustomTB(etype,value,tb)
1573 1576 except:
1574 1577 self.showtraceback()
1575 1578 else:
1576 1579 outflag = 0
1577 1580 if softspace(sys.stdout, 0):
1578 1581 print
1579 1582 # Flush out code object which has been run (and source)
1580 1583 self.code_to_run = None
1581 1584 return outflag
1582 1585
1583 1586 def push(self, line):
1584 1587 """Push a line to the interpreter.
1585 1588
1586 1589 The line should not have a trailing newline; it may have
1587 1590 internal newlines. The line is appended to a buffer and the
1588 1591 interpreter's runsource() method is called with the
1589 1592 concatenated contents of the buffer as source. If this
1590 1593 indicates that the command was executed or invalid, the buffer
1591 1594 is reset; otherwise, the command is incomplete, and the buffer
1592 1595 is left as it was after the line was appended. The return
1593 1596 value is 1 if more input is required, 0 if the line was dealt
1594 1597 with in some way (this is the same as runsource()).
1595 1598
1596 1599 """
1597 1600 self.buffer.append(line)
1598 1601 more = self.runsource('\n'.join(self.buffer), self.filename)
1599 1602 if not more:
1600 1603 self.resetbuffer()
1601 1604 return more
1602 1605
1603 1606 def resetbuffer(self):
1604 1607 """Reset the input buffer."""
1605 1608 self.buffer[:] = []
1606 1609
1607 1610 def raw_input(self,prompt='',continue_prompt=False):
1608 1611 """Write a prompt and read a line.
1609 1612
1610 1613 The returned line does not include the trailing newline.
1611 1614 When the user enters the EOF key sequence, EOFError is raised.
1612 1615
1613 1616 Optional inputs:
1614 1617
1615 1618 - prompt(''): a string to be printed to prompt the user.
1616 1619
1617 1620 - continue_prompt(False): whether this line is the first one or a
1618 1621 continuation in a sequence of inputs.
1619 1622 """
1620 1623
1621 1624 line = raw_input_original(prompt)
1622 1625 # Try to be reasonably smart about not re-indenting pasted input more
1623 1626 # than necessary. We do this by trimming out the auto-indent initial
1624 1627 # spaces, if the user's actual input started itself with whitespace.
1625 1628 if self.autoindent:
1626 1629 line2 = line[self.indent_current_nsp:]
1627 1630 if line2[0:1] in (' ','\t'):
1628 1631 line = line2
1629 1632 return self.prefilter(line,continue_prompt)
1630 1633
1631 1634 def split_user_input(self,line):
1632 1635 """Split user input into pre-char, function part and rest."""
1633 1636
1634 1637 lsplit = self.line_split.match(line)
1635 1638 if lsplit is None: # no regexp match returns None
1636 1639 try:
1637 1640 iFun,theRest = line.split(None,1)
1638 1641 except ValueError:
1639 1642 iFun,theRest = line,''
1640 1643 pre = re.match('^(\s*)(.*)',line).groups()[0]
1641 1644 else:
1642 1645 pre,iFun,theRest = lsplit.groups()
1643 1646
1644 1647 #print 'line:<%s>' % line # dbg
1645 1648 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1646 1649 return pre,iFun.strip(),theRest
1647 1650
1648 1651 def _prefilter(self, line, continue_prompt):
1649 1652 """Calls different preprocessors, depending on the form of line."""
1650 1653
1651 1654 # All handlers *must* return a value, even if it's blank ('').
1652 1655
1653 1656 # Lines are NOT logged here. Handlers should process the line as
1654 1657 # needed, update the cache AND log it (so that the input cache array
1655 1658 # stays synced).
1656 1659
1657 1660 # This function is _very_ delicate, and since it's also the one which
1658 1661 # determines IPython's response to user input, it must be as efficient
1659 1662 # as possible. For this reason it has _many_ returns in it, trying
1660 1663 # always to exit as quickly as it can figure out what it needs to do.
1661 1664
1662 1665 # This function is the main responsible for maintaining IPython's
1663 1666 # behavior respectful of Python's semantics. So be _very_ careful if
1664 1667 # making changes to anything here.
1665 1668
1666 1669 #.....................................................................
1667 1670 # Code begins
1668 1671
1669 1672 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1670 1673
1671 1674 # save the line away in case we crash, so the post-mortem handler can
1672 1675 # record it
1673 1676 self._last_input_line = line
1674 1677
1675 1678 #print '***line: <%s>' % line # dbg
1676 1679
1677 1680 # the input history needs to track even empty lines
1678 1681 if not line.strip():
1679 1682 if not continue_prompt:
1680 1683 self.outputcache.prompt_count -= 1
1681 1684 return self.handle_normal(line,continue_prompt)
1682 1685 #return self.handle_normal('',continue_prompt)
1683 1686
1684 1687 # print '***cont',continue_prompt # dbg
1685 1688 # special handlers are only allowed for single line statements
1686 1689 if continue_prompt and not self.rc.multi_line_specials:
1687 1690 return self.handle_normal(line,continue_prompt)
1688 1691
1689 1692 # For the rest, we need the structure of the input
1690 1693 pre,iFun,theRest = self.split_user_input(line)
1691 1694 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1692 1695
1693 1696 # First check for explicit escapes in the last/first character
1694 1697 handler = None
1695 1698 if line[-1] == self.ESC_HELP:
1696 1699 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1697 1700 if handler is None:
1698 1701 # look at the first character of iFun, NOT of line, so we skip
1699 1702 # leading whitespace in multiline input
1700 1703 handler = self.esc_handlers.get(iFun[0:1])
1701 1704 if handler is not None:
1702 1705 return handler(line,continue_prompt,pre,iFun,theRest)
1703 1706 # Emacs ipython-mode tags certain input lines
1704 1707 if line.endswith('# PYTHON-MODE'):
1705 1708 return self.handle_emacs(line,continue_prompt)
1706 1709
1707 1710 # Next, check if we can automatically execute this thing
1708 1711
1709 1712 # Allow ! in multi-line statements if multi_line_specials is on:
1710 1713 if continue_prompt and self.rc.multi_line_specials and \
1711 1714 iFun.startswith(self.ESC_SHELL):
1712 1715 return self.handle_shell_escape(line,continue_prompt,
1713 1716 pre=pre,iFun=iFun,
1714 1717 theRest=theRest)
1715 1718
1716 1719 # Let's try to find if the input line is a magic fn
1717 1720 oinfo = None
1718 1721 if hasattr(self,'magic_'+iFun):
1722 # WARNING: _ofind uses getattr(), so it can consume generators and
1723 # cause other side effects.
1719 1724 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1720 1725 if oinfo['ismagic']:
1721 1726 # Be careful not to call magics when a variable assignment is
1722 1727 # being made (ls='hi', for example)
1723 1728 if self.rc.automagic and \
1724 1729 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1725 1730 (self.rc.multi_line_specials or not continue_prompt):
1726 1731 return self.handle_magic(line,continue_prompt,
1727 1732 pre,iFun,theRest)
1728 1733 else:
1729 1734 return self.handle_normal(line,continue_prompt)
1730 1735
1731 1736 # If the rest of the line begins with an (in)equality, assginment or
1732 1737 # function call, we should not call _ofind but simply execute it.
1733 1738 # This avoids spurious geattr() accesses on objects upon assignment.
1734 1739 #
1735 1740 # It also allows users to assign to either alias or magic names true
1736 1741 # python variables (the magic/alias systems always take second seat to
1737 1742 # true python code).
1738 1743 if theRest and theRest[0] in '!=()':
1739 1744 return self.handle_normal(line,continue_prompt)
1740 1745
1741 1746 if oinfo is None:
1742 1747 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1743 1748
1744 1749 if not oinfo['found']:
1745 1750 return self.handle_normal(line,continue_prompt)
1746 1751 else:
1747 1752 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1748 1753 if oinfo['isalias']:
1749 1754 return self.handle_alias(line,continue_prompt,
1750 1755 pre,iFun,theRest)
1751 1756
1752 1757 if self.rc.autocall and \
1753 1758 not self.re_exclude_auto.match(theRest) and \
1754 1759 self.re_fun_name.match(iFun) and \
1755 1760 callable(oinfo['obj']) :
1756 1761 #print 'going auto' # dbg
1757 1762 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1758 1763 else:
1759 1764 #print 'was callable?', callable(oinfo['obj']) # dbg
1760 1765 return self.handle_normal(line,continue_prompt)
1761 1766
1762 1767 # If we get here, we have a normal Python line. Log and return.
1763 1768 return self.handle_normal(line,continue_prompt)
1764 1769
1765 1770 def _prefilter_dumb(self, line, continue_prompt):
1766 1771 """simple prefilter function, for debugging"""
1767 1772 return self.handle_normal(line,continue_prompt)
1768 1773
1769 1774 # Set the default prefilter() function (this can be user-overridden)
1770 1775 prefilter = _prefilter
1771 1776
1772 1777 def handle_normal(self,line,continue_prompt=None,
1773 1778 pre=None,iFun=None,theRest=None):
1774 1779 """Handle normal input lines. Use as a template for handlers."""
1775 1780
1776 1781 # With autoindent on, we need some way to exit the input loop, and I
1777 1782 # don't want to force the user to have to backspace all the way to
1778 1783 # clear the line. The rule will be in this case, that either two
1779 1784 # lines of pure whitespace in a row, or a line of pure whitespace but
1780 1785 # of a size different to the indent level, will exit the input loop.
1781 1786 if (continue_prompt and self.autoindent and isspace(line) and
1782 1787 (line != self.indent_current or isspace(self.buffer[-1]))):
1783 1788 line = ''
1784 1789
1785 1790 self.log(line,continue_prompt)
1786 1791 self.update_cache(line)
1787 1792 return line
1788 1793
1789 1794 def handle_alias(self,line,continue_prompt=None,
1790 1795 pre=None,iFun=None,theRest=None):
1791 1796 """Handle alias input lines. """
1792 1797
1793 1798 theRest = esc_quotes(theRest)
1794 1799 # log the ipalias form, which doesn't depend on the instance name
1795 1800 line_log = 'ipalias("%s %s")' % (iFun,theRest)
1796 1801 self.log(line_log,continue_prompt)
1797 1802 self.update_cache(line_log)
1798 1803 # this is what actually gets executed
1799 1804 return "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1800 1805
1801 1806 def handle_shell_escape(self, line, continue_prompt=None,
1802 1807 pre=None,iFun=None,theRest=None):
1803 1808 """Execute the line in a shell, empty return value"""
1804 1809
1805 1810 #print 'line in :', `line` # dbg
1806 1811 # Example of a special handler. Others follow a similar pattern.
1807 1812 if continue_prompt: # multi-line statements
1808 1813 if iFun.startswith('!!'):
1809 1814 print 'SyntaxError: !! is not allowed in multiline statements'
1810 1815 return pre
1811 1816 else:
1812 1817 cmd = ("%s %s" % (iFun[1:],theRest)) #.replace('"','\\"')
1813 1818 #line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1814 1819 line_out = '%s%s.system(r"""%s"""[:-1])' % (pre,self.name,cmd + "_")
1815 1820 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1816 1821 else: # single-line input
1817 1822 if line.startswith('!!'):
1818 1823 # rewrite iFun/theRest to properly hold the call to %sx and
1819 1824 # the actual command to be executed, so handle_magic can work
1820 1825 # correctly
1821 1826 theRest = '%s %s' % (iFun[2:],theRest)
1822 1827 iFun = 'sx'
1823 1828 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1824 1829 continue_prompt,pre,iFun,theRest)
1825 1830 else:
1826 1831 #cmd = esc_quotes(line[1:])
1827 1832 cmd=line[1:]
1828 1833 #line_out = '%s.system("%s")' % (self.name,cmd)
1829 1834 line_out = '%s.system(r"""%s"""[:-1])' % (self.name,cmd +"_")
1830 1835 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1831 1836 # update cache/log and return
1832 1837 self.log(line_out,continue_prompt)
1833 1838 self.update_cache(line_out) # readline cache gets normal line
1834 1839 #print 'line out r:', `line_out` # dbg
1835 1840 #print 'line out s:', line_out # dbg
1836 1841 return line_out
1837 1842
1838 1843 def handle_magic(self, line, continue_prompt=None,
1839 1844 pre=None,iFun=None,theRest=None):
1840 1845 """Execute magic functions.
1841 1846
1842 1847 Also log them with a prepended # so the log is clean Python."""
1843 1848
1844 1849 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1845 1850 self.log(cmd,continue_prompt)
1846 1851 self.update_cache(line)
1847 1852 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1848 1853 return cmd
1849 1854
1850 1855 def handle_auto(self, line, continue_prompt=None,
1851 1856 pre=None,iFun=None,theRest=None):
1852 1857 """Hande lines which can be auto-executed, quoting if requested."""
1853 1858
1854 1859 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1855 1860
1856 1861 # This should only be active for single-line input!
1857 1862 if continue_prompt:
1858 1863 return line
1859 1864
1860 1865 if pre == self.ESC_QUOTE:
1861 1866 # Auto-quote splitting on whitespace
1862 1867 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1863 1868 elif pre == self.ESC_QUOTE2:
1864 1869 # Auto-quote whole string
1865 1870 newcmd = '%s("%s")' % (iFun,theRest)
1866 1871 else:
1867 1872 # Auto-paren
1868 1873 if theRest[0:1] in ('=','['):
1869 1874 # Don't autocall in these cases. They can be either
1870 1875 # rebindings of an existing callable's name, or item access
1871 1876 # for an object which is BOTH callable and implements
1872 1877 # __getitem__.
1873 1878 return '%s %s' % (iFun,theRest)
1874 1879 if theRest.endswith(';'):
1875 1880 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1876 1881 else:
1877 1882 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1878 1883
1879 1884 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1880 1885 # log what is now valid Python, not the actual user input (without the
1881 1886 # final newline)
1882 1887 self.log(newcmd,continue_prompt)
1883 1888 return newcmd
1884 1889
1885 1890 def handle_help(self, line, continue_prompt=None,
1886 1891 pre=None,iFun=None,theRest=None):
1887 1892 """Try to get some help for the object.
1888 1893
1889 1894 obj? or ?obj -> basic information.
1890 1895 obj?? or ??obj -> more details.
1891 1896 """
1892 1897
1893 1898 # We need to make sure that we don't process lines which would be
1894 1899 # otherwise valid python, such as "x=1 # what?"
1895 1900 try:
1896 1901 codeop.compile_command(line)
1897 1902 except SyntaxError:
1898 1903 # We should only handle as help stuff which is NOT valid syntax
1899 1904 if line[0]==self.ESC_HELP:
1900 1905 line = line[1:]
1901 1906 elif line[-1]==self.ESC_HELP:
1902 1907 line = line[:-1]
1903 1908 self.log('#?'+line)
1904 1909 self.update_cache(line)
1905 1910 if line:
1906 1911 self.magic_pinfo(line)
1907 1912 else:
1908 1913 page(self.usage,screen_lines=self.rc.screen_length)
1909 1914 return '' # Empty string is needed here!
1910 1915 except:
1911 1916 # Pass any other exceptions through to the normal handler
1912 1917 return self.handle_normal(line,continue_prompt)
1913 1918 else:
1914 1919 # If the code compiles ok, we should handle it normally
1915 1920 return self.handle_normal(line,continue_prompt)
1916 1921
1917 1922 def handle_emacs(self,line,continue_prompt=None,
1918 1923 pre=None,iFun=None,theRest=None):
1919 1924 """Handle input lines marked by python-mode."""
1920 1925
1921 1926 # Currently, nothing is done. Later more functionality can be added
1922 1927 # here if needed.
1923 1928
1924 1929 # The input cache shouldn't be updated
1925 1930
1926 1931 return line
1927 1932
1928 1933 def write(self,data):
1929 1934 """Write a string to the default output"""
1930 1935 Term.cout.write(data)
1931 1936
1932 1937 def write_err(self,data):
1933 1938 """Write a string to the default error output"""
1934 1939 Term.cerr.write(data)
1935 1940
1936 1941 def exit(self):
1937 1942 """Handle interactive exit.
1938 1943
1939 1944 This method sets the exit_now attribute."""
1940 1945
1941 1946 if self.rc.confirm_exit:
1942 1947 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1943 1948 self.exit_now = True
1944 1949 else:
1945 1950 self.exit_now = True
1946 1951 return self.exit_now
1947 1952
1948 1953 def safe_execfile(self,fname,*where,**kw):
1949 1954 fname = os.path.expanduser(fname)
1950 1955
1951 1956 # find things also in current directory
1952 1957 dname = os.path.dirname(fname)
1953 1958 if not sys.path.count(dname):
1954 1959 sys.path.append(dname)
1955 1960
1956 1961 try:
1957 1962 xfile = open(fname)
1958 1963 except:
1959 1964 print >> Term.cerr, \
1960 1965 'Could not open file <%s> for safe execution.' % fname
1961 1966 return None
1962 1967
1963 1968 kw.setdefault('islog',0)
1964 1969 kw.setdefault('quiet',1)
1965 1970 kw.setdefault('exit_ignore',0)
1966 1971 first = xfile.readline()
1967 1972 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
1968 1973 xfile.close()
1969 1974 # line by line execution
1970 1975 if first.startswith(loghead) or kw['islog']:
1971 1976 print 'Loading log file <%s> one line at a time...' % fname
1972 1977 if kw['quiet']:
1973 1978 stdout_save = sys.stdout
1974 1979 sys.stdout = StringIO.StringIO()
1975 1980 try:
1976 1981 globs,locs = where[0:2]
1977 1982 except:
1978 1983 try:
1979 1984 globs = locs = where[0]
1980 1985 except:
1981 1986 globs = locs = globals()
1982 1987 badblocks = []
1983 1988
1984 1989 # we also need to identify indented blocks of code when replaying
1985 1990 # logs and put them together before passing them to an exec
1986 1991 # statement. This takes a bit of regexp and look-ahead work in the
1987 1992 # file. It's easiest if we swallow the whole thing in memory
1988 1993 # first, and manually walk through the lines list moving the
1989 1994 # counter ourselves.
1990 1995 indent_re = re.compile('\s+\S')
1991 1996 xfile = open(fname)
1992 1997 filelines = xfile.readlines()
1993 1998 xfile.close()
1994 1999 nlines = len(filelines)
1995 2000 lnum = 0
1996 2001 while lnum < nlines:
1997 2002 line = filelines[lnum]
1998 2003 lnum += 1
1999 2004 # don't re-insert logger status info into cache
2000 2005 if line.startswith('#log#'):
2001 2006 continue
2002 2007 elif line.startswith('#!'):
2003 2008 self.update_cache(line[1:])
2004 2009 else:
2005 2010 # build a block of code (maybe a single line) for execution
2006 2011 block = line
2007 2012 try:
2008 2013 next = filelines[lnum] # lnum has already incremented
2009 2014 except:
2010 2015 next = None
2011 2016 while next and indent_re.match(next):
2012 2017 block += next
2013 2018 lnum += 1
2014 2019 try:
2015 2020 next = filelines[lnum]
2016 2021 except:
2017 2022 next = None
2018 2023 # now execute the block of one or more lines
2019 2024 try:
2020 2025 exec block in globs,locs
2021 2026 self.update_cache(block.rstrip())
2022 2027 except SystemExit:
2023 2028 pass
2024 2029 except:
2025 2030 badblocks.append(block.rstrip())
2026 2031 if kw['quiet']: # restore stdout
2027 2032 sys.stdout.close()
2028 2033 sys.stdout = stdout_save
2029 2034 print 'Finished replaying log file <%s>' % fname
2030 2035 if badblocks:
2031 2036 print >> sys.stderr, ('\nThe following lines/blocks in file '
2032 2037 '<%s> reported errors:' % fname)
2033 2038
2034 2039 for badline in badblocks:
2035 2040 print >> sys.stderr, badline
2036 2041 else: # regular file execution
2037 2042 try:
2038 2043 execfile(fname,*where)
2039 2044 except SyntaxError:
2040 2045 etype,evalue = sys.exc_info()[:2]
2041 2046 self.SyntaxTB(etype,evalue,[])
2042 2047 warn('Failure executing file: <%s>' % fname)
2043 2048 except SystemExit,status:
2044 2049 if not kw['exit_ignore']:
2045 2050 self.InteractiveTB()
2046 2051 warn('Failure executing file: <%s>' % fname)
2047 2052 except:
2048 2053 self.InteractiveTB()
2049 2054 warn('Failure executing file: <%s>' % fname)
2050 2055
2051 2056 #************************* end of file <iplib.py> *****************************
@@ -1,796 +1,796 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 ultraTB.py -- Spice up your tracebacks!
4 4
5 5 * ColorTB
6 6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 7 ColorTB class is a solution to that problem. It colors the different parts of a
8 8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 9 text editor.
10 10
11 11 Installation instructions for ColorTB:
12 12 import sys,ultraTB
13 13 sys.excepthook = ultraTB.ColorTB()
14 14
15 15 * VerboseTB
16 16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 18 and intended it for CGI programmers, but why should they have all the fun? I
19 19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 20 but kind of neat, and maybe useful for long-running programs that you believe
21 21 are bug-free. If a crash *does* occur in that type of program you want details.
22 22 Give it a shot--you'll love it or you'll hate it.
23 23
24 24 Note:
25 25
26 26 The Verbose mode prints the variables currently visible where the exception
27 27 happened (shortening their strings if too long). This can potentially be
28 28 very slow, if you happen to have a huge data structure whose string
29 29 representation is complex to compute. Your computer may appear to freeze for
30 30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 31 with Ctrl-C (maybe hitting it more than once).
32 32
33 33 If you encounter this kind of situation often, you may want to use the
34 34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 35 variables (but otherwise includes the information and context given by
36 36 Verbose).
37 37
38 38
39 39 Installation instructions for ColorTB:
40 40 import sys,ultraTB
41 41 sys.excepthook = ultraTB.VerboseTB()
42 42
43 43 Note: Much of the code in this module was lifted verbatim from the standard
44 44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45 45
46 46 * Color schemes
47 47 The colors are defined in the class TBTools through the use of the
48 48 ColorSchemeTable class. Currently the following exist:
49 49
50 50 - NoColor: allows all of this module to be used in any terminal (the color
51 51 escapes are just dummy blank strings).
52 52
53 53 - Linux: is meant to look good in a terminal like the Linux console (black
54 54 or very dark background).
55 55
56 56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 57 in light background terminals.
58 58
59 59 You can implement other color schemes easily, the syntax is fairly
60 60 self-explanatory. Please send back new schemes you develop to the author for
61 61 possible inclusion in future releases.
62 62
63 $Id: ultraTB.py 965 2005-12-28 23:23:09Z fperez $"""
63 $Id: ultraTB.py 975 2005-12-29 23:50:22Z fperez $"""
64 64
65 65 #*****************************************************************************
66 66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
67 67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
68 68 #
69 69 # Distributed under the terms of the BSD License. The full license is in
70 70 # the file COPYING, distributed as part of this software.
71 71 #*****************************************************************************
72 72
73 73 from IPython import Release
74 74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
75 75 Release.authors['Fernando'])
76 76 __license__ = Release.license
77 77
78 78 # Required modules
79 79 import inspect
80 80 import keyword
81 81 import linecache
82 82 import os
83 83 import pydoc
84 84 import string
85 85 import sys
86 86 import time
87 87 import tokenize
88 88 import traceback
89 89 import types
90 90
91 91 # IPython's own modules
92 92 # Modified pdb which doesn't damage IPython's readline handling
93 93 from IPython import Debugger
94 94 from IPython.Struct import Struct
95 95 from IPython.excolors import ExceptionColors
96 96 from IPython.genutils import Term,uniq_stable,error,info
97 97
98 98 #---------------------------------------------------------------------------
99 99 # Code begins
100 100
101 101 def inspect_error():
102 102 """Print a message about internal inspect errors.
103 103
104 104 These are unfortunately quite common."""
105 105
106 106 error('Internal Python error in the inspect module.\n'
107 107 'Below is the traceback from this internal error.\n')
108 108
109 109 class TBTools:
110 110 """Basic tools used by all traceback printer classes."""
111 111
112 112 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
113 113 # Whether to call the interactive pdb debugger after printing
114 114 # tracebacks or not
115 115 self.call_pdb = call_pdb
116 116
117 117 # Create color table
118 118 self.color_scheme_table = ExceptionColors
119 119
120 120 self.set_colors(color_scheme)
121 121 self.old_scheme = color_scheme # save initial value for toggles
122 122
123 123 if call_pdb:
124 124 self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
125 125 else:
126 126 self.pdb = None
127 127
128 128 def set_colors(self,*args,**kw):
129 129 """Shorthand access to the color table scheme selector method."""
130 130
131 131 self.color_scheme_table.set_active_scheme(*args,**kw)
132 132 # for convenience, set Colors to the active scheme
133 133 self.Colors = self.color_scheme_table.active_colors
134 134
135 135 def color_toggle(self):
136 136 """Toggle between the currently active color scheme and NoColor."""
137 137
138 138 if self.color_scheme_table.active_scheme_name == 'NoColor':
139 139 self.color_scheme_table.set_active_scheme(self.old_scheme)
140 140 self.Colors = self.color_scheme_table.active_colors
141 141 else:
142 142 self.old_scheme = self.color_scheme_table.active_scheme_name
143 143 self.color_scheme_table.set_active_scheme('NoColor')
144 144 self.Colors = self.color_scheme_table.active_colors
145 145
146 146 #---------------------------------------------------------------------------
147 147 class ListTB(TBTools):
148 148 """Print traceback information from a traceback list, with optional color.
149 149
150 150 Calling: requires 3 arguments:
151 151 (etype, evalue, elist)
152 152 as would be obtained by:
153 153 etype, evalue, tb = sys.exc_info()
154 154 if tb:
155 155 elist = traceback.extract_tb(tb)
156 156 else:
157 157 elist = None
158 158
159 159 It can thus be used by programs which need to process the traceback before
160 160 printing (such as console replacements based on the code module from the
161 161 standard library).
162 162
163 163 Because they are meant to be called without a full traceback (only a
164 164 list), instances of this class can't call the interactive pdb debugger."""
165 165
166 166 def __init__(self,color_scheme = 'NoColor'):
167 167 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
168 168
169 169 def __call__(self, etype, value, elist):
170 170 print >> Term.cerr, self.text(etype,value,elist)
171 171
172 172 def text(self,etype, value, elist,context=5):
173 173 """Return a color formatted string with the traceback info."""
174 174
175 175 Colors = self.Colors
176 176 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
177 177 if elist:
178 178 out_string.append('Traceback %s(most recent call last)%s:' % \
179 179 (Colors.normalEm, Colors.Normal) + '\n')
180 180 out_string.extend(self._format_list(elist))
181 181 lines = self._format_exception_only(etype, value)
182 182 for line in lines[:-1]:
183 183 out_string.append(" "+line)
184 184 out_string.append(lines[-1])
185 185 return ''.join(out_string)
186 186
187 187 def _format_list(self, extracted_list):
188 188 """Format a list of traceback entry tuples for printing.
189 189
190 190 Given a list of tuples as returned by extract_tb() or
191 191 extract_stack(), return a list of strings ready for printing.
192 192 Each string in the resulting list corresponds to the item with the
193 193 same index in the argument list. Each string ends in a newline;
194 194 the strings may contain internal newlines as well, for those items
195 195 whose source text line is not None.
196 196
197 197 Lifted almost verbatim from traceback.py
198 198 """
199 199
200 200 Colors = self.Colors
201 201 list = []
202 202 for filename, lineno, name, line in extracted_list[:-1]:
203 203 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
204 204 (Colors.filename, filename, Colors.Normal,
205 205 Colors.lineno, lineno, Colors.Normal,
206 206 Colors.name, name, Colors.Normal)
207 207 if line:
208 208 item = item + ' %s\n' % line.strip()
209 209 list.append(item)
210 210 # Emphasize the last entry
211 211 filename, lineno, name, line = extracted_list[-1]
212 212 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
213 213 (Colors.normalEm,
214 214 Colors.filenameEm, filename, Colors.normalEm,
215 215 Colors.linenoEm, lineno, Colors.normalEm,
216 216 Colors.nameEm, name, Colors.normalEm,
217 217 Colors.Normal)
218 218 if line:
219 219 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
220 220 Colors.Normal)
221 221 list.append(item)
222 222 return list
223 223
224 224 def _format_exception_only(self, etype, value):
225 225 """Format the exception part of a traceback.
226 226
227 227 The arguments are the exception type and value such as given by
228 sys.last_type and sys.last_value. The return value is a list of
229 strings, each ending in a newline. Normally, the list contains a
230 single string; however, for SyntaxError exceptions, it contains
231 several lines that (when printed) display detailed information
232 about where the syntax error occurred. The message indicating
233 which exception occurred is the always last string in the list.
228 sys.exc_info()[:2]. The return value is a list of strings, each ending
229 in a newline. Normally, the list contains a single string; however,
230 for SyntaxError exceptions, it contains several lines that (when
231 printed) display detailed information about where the syntax error
232 occurred. The message indicating which exception occurred is the
233 always last string in the list.
234 234
235 235 Also lifted nearly verbatim from traceback.py
236 236 """
237 237
238 238 Colors = self.Colors
239 239 list = []
240 240 if type(etype) == types.ClassType:
241 241 stype = Colors.excName + etype.__name__ + Colors.Normal
242 242 else:
243 243 stype = etype # String exceptions don't get special coloring
244 244 if value is None:
245 245 list.append( str(stype) + '\n')
246 246 else:
247 247 if etype is SyntaxError:
248 248 try:
249 249 msg, (filename, lineno, offset, line) = value
250 250 except:
251 251 pass
252 252 else:
253 253 #print 'filename is',filename # dbg
254 254 if not filename: filename = "<string>"
255 255 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
256 256 (Colors.normalEm,
257 257 Colors.filenameEm, filename, Colors.normalEm,
258 258 Colors.linenoEm, lineno, Colors.Normal ))
259 259 if line is not None:
260 260 i = 0
261 261 while i < len(line) and line[i].isspace():
262 262 i = i+1
263 263 list.append('%s %s%s\n' % (Colors.line,
264 264 line.strip(),
265 265 Colors.Normal))
266 266 if offset is not None:
267 267 s = ' '
268 268 for c in line[i:offset-1]:
269 269 if c.isspace():
270 270 s = s + c
271 271 else:
272 272 s = s + ' '
273 273 list.append('%s%s^%s\n' % (Colors.caret, s,
274 274 Colors.Normal) )
275 275 value = msg
276 276 s = self._some_str(value)
277 277 if s:
278 278 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
279 279 Colors.Normal, s))
280 280 else:
281 281 list.append('%s\n' % str(stype))
282 282 return list
283 283
284 284 def _some_str(self, value):
285 285 # Lifted from traceback.py
286 286 try:
287 287 return str(value)
288 288 except:
289 289 return '<unprintable %s object>' % type(value).__name__
290 290
291 291 #----------------------------------------------------------------------------
292 292 class VerboseTB(TBTools):
293 293 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
294 294 of HTML. Requires inspect and pydoc. Crazy, man.
295 295
296 296 Modified version which optionally strips the topmost entries from the
297 297 traceback, to be used with alternate interpreters (because their own code
298 298 would appear in the traceback)."""
299 299
300 300 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
301 301 call_pdb = 0, include_vars=1):
302 302 """Specify traceback offset, headers and color scheme.
303 303
304 304 Define how many frames to drop from the tracebacks. Calling it with
305 305 tb_offset=1 allows use of this handler in interpreters which will have
306 306 their own code at the top of the traceback (VerboseTB will first
307 307 remove that frame before printing the traceback info)."""
308 308 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
309 309 self.tb_offset = tb_offset
310 310 self.long_header = long_header
311 311 self.include_vars = include_vars
312 312
313 313 def text(self, etype, evalue, etb, context=5):
314 314 """Return a nice text document describing the traceback."""
315 315
316 316 # some locals
317 317 Colors = self.Colors # just a shorthand + quicker name lookup
318 318 ColorsNormal = Colors.Normal # used a lot
319 319 indent_size = 8 # we need some space to put line numbers before
320 320 indent = ' '*indent_size
321 321 numbers_width = indent_size - 1 # leave space between numbers & code
322 322 text_repr = pydoc.text.repr
323 323 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
324 324 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
325 325 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
326 326
327 327 # some internal-use functions
328 328 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
329 329 def nullrepr(value, repr=text_repr): return ''
330 330
331 331 # meat of the code begins
332 332 if type(etype) is types.ClassType:
333 333 etype = etype.__name__
334 334
335 335 if self.long_header:
336 336 # Header with the exception type, python version, and date
337 337 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
338 338 date = time.ctime(time.time())
339 339
340 340 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
341 341 exc, ' '*(75-len(str(etype))-len(pyver)),
342 342 pyver, string.rjust(date, 75) )
343 343 head += "\nA problem occured executing Python code. Here is the sequence of function"\
344 344 "\ncalls leading up to the error, with the most recent (innermost) call last."
345 345 else:
346 346 # Simplified header
347 347 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
348 348 string.rjust('Traceback (most recent call last)',
349 349 75 - len(str(etype)) ) )
350 350 frames = []
351 351 # Flush cache before calling inspect. This helps alleviate some of the
352 352 # problems with python 2.3's inspect.py.
353 353 linecache.checkcache()
354 354 # Drop topmost frames if requested
355 355 try:
356 356 records = inspect.getinnerframes(etb, context)[self.tb_offset:]
357 357 except:
358 358
359 359 # FIXME: I've been getting many crash reports from python 2.3
360 360 # users, traceable to inspect.py. If I can find a small test-case
361 361 # to reproduce this, I should either write a better workaround or
362 362 # file a bug report against inspect (if that's the real problem).
363 363 # So far, I haven't been able to find an isolated example to
364 364 # reproduce the problem.
365 365 inspect_error()
366 366 traceback.print_exc(file=Term.cerr)
367 367 info('\nUnfortunately, your original traceback can not be constructed.\n')
368 368 return ''
369 369
370 370 # build some color string templates outside these nested loops
371 371 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
372 372 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
373 373 ColorsNormal)
374 374 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
375 375 (Colors.vName, Colors.valEm, ColorsNormal)
376 376 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
377 377 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
378 378 Colors.vName, ColorsNormal)
379 379 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
380 380 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
381 381 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
382 382 ColorsNormal)
383 383
384 384 # now, loop over all records printing context and info
385 385 abspath = os.path.abspath
386 386 for frame, file, lnum, func, lines, index in records:
387 387 #print '*** record:',file,lnum,func,lines,index # dbg
388 388 try:
389 389 file = file and abspath(file) or '?'
390 390 except OSError:
391 391 # if file is '<console>' or something not in the filesystem,
392 392 # the abspath call will throw an OSError. Just ignore it and
393 393 # keep the original file string.
394 394 pass
395 395 link = tpl_link % file
396 396 try:
397 397 args, varargs, varkw, locals = inspect.getargvalues(frame)
398 398 except:
399 399 # This can happen due to a bug in python2.3. We should be
400 400 # able to remove this try/except when 2.4 becomes a
401 401 # requirement. Bug details at http://python.org/sf/1005466
402 402 inspect_error()
403 403 traceback.print_exc(file=Term.cerr)
404 404 info("\nIPython's exception reporting continues...\n")
405 405
406 406 if func == '?':
407 407 call = ''
408 408 else:
409 409 # Decide whether to include variable details or not
410 410 var_repr = self.include_vars and eqrepr or nullrepr
411 411 try:
412 412 call = tpl_call % (func,inspect.formatargvalues(args,
413 413 varargs, varkw,
414 414 locals,formatvalue=var_repr))
415 415 except KeyError:
416 416 # Very odd crash from inspect.formatargvalues(). The
417 417 # scenario under which it appeared was a call to
418 418 # view(array,scale) in NumTut.view.view(), where scale had
419 419 # been defined as a scalar (it should be a tuple). Somehow
420 420 # inspect messes up resolving the argument list of view()
421 421 # and barfs out. At some point I should dig into this one
422 422 # and file a bug report about it.
423 423 inspect_error()
424 424 traceback.print_exc(file=Term.cerr)
425 425 info("\nIPython's exception reporting continues...\n")
426 426 call = tpl_call_fail % func
427 427
428 428 # Initialize a list of names on the current line, which the
429 429 # tokenizer below will populate.
430 430 names = []
431 431
432 432 def tokeneater(token_type, token, start, end, line):
433 433 """Stateful tokeneater which builds dotted names.
434 434
435 435 The list of names it appends to (from the enclosing scope) can
436 436 contain repeated composite names. This is unavoidable, since
437 437 there is no way to disambguate partial dotted structures until
438 438 the full list is known. The caller is responsible for pruning
439 439 the final list of duplicates before using it."""
440 440
441 441 # build composite names
442 442 if token == '.':
443 443 try:
444 444 names[-1] += '.'
445 445 # store state so the next token is added for x.y.z names
446 446 tokeneater.name_cont = True
447 447 return
448 448 except IndexError:
449 449 pass
450 450 if token_type == tokenize.NAME and token not in keyword.kwlist:
451 451 if tokeneater.name_cont:
452 452 # Dotted names
453 453 names[-1] += token
454 454 tokeneater.name_cont = False
455 455 else:
456 456 # Regular new names. We append everything, the caller
457 457 # will be responsible for pruning the list later. It's
458 458 # very tricky to try to prune as we go, b/c composite
459 459 # names can fool us. The pruning at the end is easy
460 460 # to do (or the caller can print a list with repeated
461 461 # names if so desired.
462 462 names.append(token)
463 463 elif token_type == tokenize.NEWLINE:
464 464 raise IndexError
465 465 # we need to store a bit of state in the tokenizer to build
466 466 # dotted names
467 467 tokeneater.name_cont = False
468 468
469 469 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
470 470 line = getline(file, lnum[0])
471 471 lnum[0] += 1
472 472 return line
473 473
474 474 # Build the list of names on this line of code where the exception
475 475 # occurred.
476 476 try:
477 477 # This builds the names list in-place by capturing it from the
478 478 # enclosing scope.
479 479 tokenize.tokenize(linereader, tokeneater)
480 480 except IndexError:
481 481 # signals exit of tokenizer
482 482 pass
483 483 except tokenize.TokenError,msg:
484 484 _m = ("An unexpected error occurred while tokenizing input\n"
485 485 "The following traceback may be corrupted or invalid\n"
486 486 "The error message is: %s\n" % msg)
487 487 error(_m)
488 488
489 489 # prune names list of duplicates, but keep the right order
490 490 unique_names = uniq_stable(names)
491 491
492 492 # Start loop over vars
493 493 lvals = []
494 494 if self.include_vars:
495 495 for name_full in unique_names:
496 496 name_base = name_full.split('.',1)[0]
497 497 if name_base in frame.f_code.co_varnames:
498 498 if locals.has_key(name_base):
499 499 try:
500 500 value = repr(eval(name_full,locals))
501 501 except:
502 502 value = undefined
503 503 else:
504 504 value = undefined
505 505 name = tpl_local_var % name_full
506 506 else:
507 507 if frame.f_globals.has_key(name_base):
508 508 try:
509 509 value = repr(eval(name_full,frame.f_globals))
510 510 except:
511 511 value = undefined
512 512 else:
513 513 value = undefined
514 514 name = tpl_global_var % name_full
515 515 lvals.append(tpl_name_val % (name,value))
516 516 if lvals:
517 517 lvals = '%s%s' % (indent,em_normal.join(lvals))
518 518 else:
519 519 lvals = ''
520 520
521 521 level = '%s %s\n' % (link,call)
522 522 excerpt = []
523 523 if index is not None:
524 524 i = lnum - index
525 525 for line in lines:
526 526 if i == lnum:
527 527 # This is the line with the error
528 528 pad = numbers_width - len(str(i))
529 529 if pad >= 3:
530 530 marker = '-'*(pad-3) + '-> '
531 531 elif pad == 2:
532 532 marker = '> '
533 533 elif pad == 1:
534 534 marker = '>'
535 535 else:
536 536 marker = ''
537 537 num = '%s%s' % (marker,i)
538 538 line = tpl_line_em % (num,line)
539 539 else:
540 540 num = '%*s' % (numbers_width,i)
541 541 line = tpl_line % (num,line)
542 542
543 543 excerpt.append(line)
544 544 if self.include_vars and i == lnum:
545 545 excerpt.append('%s\n' % lvals)
546 546 i += 1
547 547 frames.append('%s%s' % (level,''.join(excerpt)) )
548 548
549 549 # Get (safely) a string form of the exception info
550 550 try:
551 551 etype_str,evalue_str = map(str,(etype,evalue))
552 552 except:
553 553 # User exception is improperly defined.
554 554 etype,evalue = str,sys.exc_info()[:2]
555 555 etype_str,evalue_str = map(str,(etype,evalue))
556 556 # ... and format it
557 557 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
558 558 ColorsNormal, evalue_str)]
559 559 if type(evalue) is types.InstanceType:
560 560 try:
561 561 names = [w for w in dir(evalue) if isinstance(w, basestring)]
562 562 except:
563 563 # Every now and then, an object with funny inernals blows up
564 564 # when dir() is called on it. We do the best we can to report
565 565 # the problem and continue
566 566 _m = '%sException reporting error (object with broken dir())%s:'
567 567 exception.append(_m % (Colors.excName,ColorsNormal))
568 568 etype_str,evalue_str = map(str,sys.exc_info()[:2])
569 569 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
570 570 ColorsNormal, evalue_str))
571 571 names = []
572 572 for name in names:
573 573 value = text_repr(getattr(evalue, name))
574 574 exception.append('\n%s%s = %s' % (indent, name, value))
575 575 # return all our info assembled as a single string
576 576 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
577 577
578 578 def debugger(self):
579 579 """Call up the pdb debugger if desired, always clean up the tb reference.
580 580
581 581 If the call_pdb flag is set, the pdb interactive debugger is
582 582 invoked. In all cases, the self.tb reference to the current traceback
583 583 is deleted to prevent lingering references which hamper memory
584 584 management.
585 585
586 586 Note that each call to pdb() does an 'import readline', so if your app
587 587 requires a special setup for the readline completers, you'll have to
588 588 fix that by hand after invoking the exception handler."""
589 589
590 590 if self.call_pdb:
591 591 if self.pdb is None:
592 592 self.pdb = Debugger.Pdb(
593 593 self.color_scheme_table.active_scheme_name)
594 594 # the system displayhook may have changed, restore the original
595 595 # for pdb
596 596 dhook = sys.displayhook
597 597 sys.displayhook = sys.__displayhook__
598 598 self.pdb.reset()
599 599 # Find the right frame so we don't pop up inside ipython itself
600 600 etb = self.tb
601 601 while self.tb.tb_next is not None:
602 602 self.tb = self.tb.tb_next
603 603 try:
604 604 if etb and etb.tb_next:
605 605 etb = etb.tb_next
606 606 self.pdb.botframe = etb.tb_frame
607 607 self.pdb.interaction(self.tb.tb_frame, self.tb)
608 608 except:
609 609 print '*** ERROR ***'
610 610 print 'This version of pdb has a bug and crashed.'
611 611 print 'Returning to IPython...'
612 612 sys.displayhook = dhook
613 613 del self.tb
614 614
615 615 def handler(self, info=None):
616 616 (etype, evalue, etb) = info or sys.exc_info()
617 617 self.tb = etb
618 618 print >> Term.cerr, self.text(etype, evalue, etb)
619 619
620 620 # Changed so an instance can just be called as VerboseTB_inst() and print
621 621 # out the right info on its own.
622 622 def __call__(self, etype=None, evalue=None, etb=None):
623 623 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
624 624 if etb is None:
625 625 self.handler()
626 626 else:
627 627 self.handler((etype, evalue, etb))
628 628 self.debugger()
629 629
630 630 #----------------------------------------------------------------------------
631 631 class FormattedTB(VerboseTB,ListTB):
632 632 """Subclass ListTB but allow calling with a traceback.
633 633
634 634 It can thus be used as a sys.excepthook for Python > 2.1.
635 635
636 636 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
637 637
638 638 Allows a tb_offset to be specified. This is useful for situations where
639 639 one needs to remove a number of topmost frames from the traceback (such as
640 640 occurs with python programs that themselves execute other python code,
641 641 like Python shells). """
642 642
643 643 def __init__(self, mode = 'Plain', color_scheme='Linux',
644 644 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
645 645
646 646 # NEVER change the order of this list. Put new modes at the end:
647 647 self.valid_modes = ['Plain','Context','Verbose']
648 648 self.verbose_modes = self.valid_modes[1:3]
649 649
650 650 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
651 651 call_pdb=call_pdb,include_vars=include_vars)
652 652 self.set_mode(mode)
653 653
654 654 def _extract_tb(self,tb):
655 655 if tb:
656 656 return traceback.extract_tb(tb)
657 657 else:
658 658 return None
659 659
660 660 def text(self, etype, value, tb,context=5,mode=None):
661 661 """Return formatted traceback.
662 662
663 663 If the optional mode parameter is given, it overrides the current
664 664 mode."""
665 665
666 666 if mode is None:
667 667 mode = self.mode
668 668 if mode in self.verbose_modes:
669 669 # verbose modes need a full traceback
670 670 return VerboseTB.text(self,etype, value, tb,context=5)
671 671 else:
672 672 # We must check the source cache because otherwise we can print
673 673 # out-of-date source code.
674 674 linecache.checkcache()
675 675 # Now we can extract and format the exception
676 676 elist = self._extract_tb(tb)
677 677 if len(elist) > self.tb_offset:
678 678 del elist[:self.tb_offset]
679 679 return ListTB.text(self,etype,value,elist)
680 680
681 681 def set_mode(self,mode=None):
682 682 """Switch to the desired mode.
683 683
684 684 If mode is not specified, cycles through the available modes."""
685 685
686 686 if not mode:
687 687 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
688 688 len(self.valid_modes)
689 689 self.mode = self.valid_modes[new_idx]
690 690 elif mode not in self.valid_modes:
691 691 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
692 692 'Valid modes: '+str(self.valid_modes)
693 693 else:
694 694 self.mode = mode
695 695 # include variable details only in 'Verbose' mode
696 696 self.include_vars = (self.mode == self.valid_modes[2])
697 697
698 698 # some convenient shorcuts
699 699 def plain(self):
700 700 self.set_mode(self.valid_modes[0])
701 701
702 702 def context(self):
703 703 self.set_mode(self.valid_modes[1])
704 704
705 705 def verbose(self):
706 706 self.set_mode(self.valid_modes[2])
707 707
708 708 #----------------------------------------------------------------------------
709 709 class AutoFormattedTB(FormattedTB):
710 710 """A traceback printer which can be called on the fly.
711 711
712 712 It will find out about exceptions by itself.
713 713
714 714 A brief example:
715 715
716 716 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
717 717 try:
718 718 ...
719 719 except:
720 720 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
721 721 """
722 722 def __call__(self,etype=None,evalue=None,etb=None,
723 723 out=None,tb_offset=None):
724 724 """Print out a formatted exception traceback.
725 725
726 726 Optional arguments:
727 727 - out: an open file-like object to direct output to.
728 728
729 729 - tb_offset: the number of frames to skip over in the stack, on a
730 730 per-call basis (this overrides temporarily the instance's tb_offset
731 731 given at initialization time. """
732 732
733 733 if out is None:
734 734 out = Term.cerr
735 735 if tb_offset is not None:
736 736 tb_offset, self.tb_offset = self.tb_offset, tb_offset
737 737 print >> out, self.text(etype, evalue, etb)
738 738 self.tb_offset = tb_offset
739 739 else:
740 740 print >> out, self.text(etype, evalue, etb)
741 741 self.debugger()
742 742
743 743 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
744 744 if etype is None:
745 745 etype,value,tb = sys.exc_info()
746 746 self.tb = tb
747 747 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
748 748
749 749 #---------------------------------------------------------------------------
750 750 # A simple class to preserve Nathan's original functionality.
751 751 class ColorTB(FormattedTB):
752 752 """Shorthand to initialize a FormattedTB in Linux colors mode."""
753 753 def __init__(self,color_scheme='Linux',call_pdb=0):
754 754 FormattedTB.__init__(self,color_scheme=color_scheme,
755 755 call_pdb=call_pdb)
756 756
757 757 #----------------------------------------------------------------------------
758 758 # module testing (minimal)
759 759 if __name__ == "__main__":
760 760 def spam(c, (d, e)):
761 761 x = c + d
762 762 y = c * d
763 763 foo(x, y)
764 764
765 765 def foo(a, b, bar=1):
766 766 eggs(a, b + bar)
767 767
768 768 def eggs(f, g, z=globals()):
769 769 h = f + g
770 770 i = f - g
771 771 return h / i
772 772
773 773 print ''
774 774 print '*** Before ***'
775 775 try:
776 776 print spam(1, (2, 3))
777 777 except:
778 778 traceback.print_exc()
779 779 print ''
780 780
781 781 handler = ColorTB()
782 782 print '*** ColorTB ***'
783 783 try:
784 784 print spam(1, (2, 3))
785 785 except:
786 786 apply(handler, sys.exc_info() )
787 787 print ''
788 788
789 789 handler = VerboseTB()
790 790 print '*** VerboseTB ***'
791 791 try:
792 792 print spam(1, (2, 3))
793 793 except:
794 794 apply(handler, sys.exc_info() )
795 795 print ''
796 796
@@ -1,4642 +1,4660 b''
1 1 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
2 2
3 * IPython/iplib.py (showtraceback): remove use of the
4 sys.last_{type/value/traceback} structures, which are non
5 thread-safe.
6
7 * IPython/macro.py (Macro.__init__): moved macros to a standalone
8 file. Now that they'll be more likely to be used with the
9 persistance system (%store), I want to make sure their module path
10 doesn't change in the future, so that we don't break things for
11 users' persisted data.
12
13 * IPython/iplib.py (autoindent_update): move indentation
14 management into the _text_ processing loop, not the keyboard
15 interactive one. This is necessary to correctly process non-typed
16 multiline input (such as macros).
17
3 18 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
4 19 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
5 20 which was producing problems in the resulting manual.
21 (magic_whos): improve reporting of instances (show their class,
22 instead of simply printing 'instance' which isn't terribly
23 informative).
6 24
7 25 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
8 26 (minor mods) to support network shares under win32.
9 27
10 28 * IPython/winconsole.py (get_console_size): add new winconsole
11 29 module and fixes to page_dumb() to improve its behavior under
12 30 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
13 31
14 32 * IPython/Magic.py (Macro): simplified Macro class to just
15 33 subclass list. We've had only 2.2 compatibility for a very long
16 34 time, yet I was still avoiding subclassing the builtin types. No
17 35 more (I'm also starting to use properties, though I won't shift to
18 36 2.3-specific features quite yet).
19 37 (magic_store): added Ville's patch for lightweight variable
20 38 persistence, after a request on the user list by Matt Wilkie
21 39 <maphew-AT-gmail.com>. The new %store magic's docstring has full
22 40 details.
23 41
24 42 * IPython/iplib.py (InteractiveShell.post_config_initialization):
25 43 changed the default logfile name from 'ipython.log' to
26 44 'ipython_log.py'. These logs are real python files, and now that
27 45 we have much better multiline support, people are more likely to
28 46 want to use them as such. Might as well name them correctly.
29 47
30 48 * IPython/Magic.py: substantial cleanup. While we can't stop
31 49 using magics as mixins, due to the existing customizations 'out
32 50 there' which rely on the mixin naming conventions, at least I
33 51 cleaned out all cross-class name usage. So once we are OK with
34 52 breaking compatibility, the two systems can be separated.
35 53
36 54 * IPython/Logger.py: major cleanup. This one is NOT a mixin
37 55 anymore, and the class is a fair bit less hideous as well. New
38 56 features were also introduced: timestamping of input, and logging
39 57 of output results. These are user-visible with the -t and -o
40 58 options to %logstart. Closes
41 59 http://www.scipy.net/roundup/ipython/issue11 and a request by
42 60 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
43 61
44 62 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
45 63
46 64 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
47 65 better hadnle backslashes in paths. See the thread 'More Windows
48 66 questions part 2 - \/ characters revisited' on the iypthon user
49 67 list:
50 68 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
51 69
52 70 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
53 71
54 72 (InteractiveShell.__init__): change threaded shells to not use the
55 73 ipython crash handler. This was causing more problems than not,
56 74 as exceptions in the main thread (GUI code, typically) would
57 75 always show up as a 'crash', when they really weren't.
58 76
59 77 The colors and exception mode commands (%colors/%xmode) have been
60 78 synchronized to also take this into account, so users can get
61 79 verbose exceptions for their threaded code as well. I also added
62 80 support for activating pdb inside this exception handler as well,
63 81 so now GUI authors can use IPython's enhanced pdb at runtime.
64 82
65 83 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
66 84 true by default, and add it to the shipped ipythonrc file. Since
67 85 this asks the user before proceeding, I think it's OK to make it
68 86 true by default.
69 87
70 88 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
71 89 of the previous special-casing of input in the eval loop. I think
72 90 this is cleaner, as they really are commands and shouldn't have
73 91 a special role in the middle of the core code.
74 92
75 93 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
76 94
77 95 * IPython/iplib.py (edit_syntax_error): added support for
78 96 automatically reopening the editor if the file had a syntax error
79 97 in it. Thanks to scottt who provided the patch at:
80 98 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
81 99 version committed).
82 100
83 101 * IPython/iplib.py (handle_normal): add suport for multi-line
84 102 input with emtpy lines. This fixes
85 103 http://www.scipy.net/roundup/ipython/issue43 and a similar
86 104 discussion on the user list.
87 105
88 106 WARNING: a behavior change is necessarily introduced to support
89 107 blank lines: now a single blank line with whitespace does NOT
90 108 break the input loop, which means that when autoindent is on, by
91 109 default hitting return on the next (indented) line does NOT exit.
92 110
93 111 Instead, to exit a multiline input you can either have:
94 112
95 113 - TWO whitespace lines (just hit return again), or
96 114 - a single whitespace line of a different length than provided
97 115 by the autoindent (add or remove a space).
98 116
99 117 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
100 118 module to better organize all readline-related functionality.
101 119 I've deleted FlexCompleter and put all completion clases here.
102 120
103 121 * IPython/iplib.py (raw_input): improve indentation management.
104 122 It is now possible to paste indented code with autoindent on, and
105 123 the code is interpreted correctly (though it still looks bad on
106 124 screen, due to the line-oriented nature of ipython).
107 125 (MagicCompleter.complete): change behavior so that a TAB key on an
108 126 otherwise empty line actually inserts a tab, instead of completing
109 127 on the entire global namespace. This makes it easier to use the
110 128 TAB key for indentation. After a request by Hans Meine
111 129 <hans_meine-AT-gmx.net>
112 130 (_prefilter): add support so that typing plain 'exit' or 'quit'
113 131 does a sensible thing. Originally I tried to deviate as little as
114 132 possible from the default python behavior, but even that one may
115 133 change in this direction (thread on python-dev to that effect).
116 134 Regardless, ipython should do the right thing even if CPython's
117 135 '>>>' prompt doesn't.
118 136 (InteractiveShell): removed subclassing code.InteractiveConsole
119 137 class. By now we'd overridden just about all of its methods: I've
120 138 copied the remaining two over, and now ipython is a standalone
121 139 class. This will provide a clearer picture for the chainsaw
122 140 branch refactoring.
123 141
124 142 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
125 143
126 144 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
127 145 failures for objects which break when dir() is called on them.
128 146
129 147 * IPython/FlexCompleter.py (Completer.__init__): Added support for
130 148 distinct local and global namespaces in the completer API. This
131 149 change allows us top properly handle completion with distinct
132 150 scopes, including in embedded instances (this had never really
133 151 worked correctly).
134 152
135 153 Note: this introduces a change in the constructor for
136 154 MagicCompleter, as a new global_namespace parameter is now the
137 155 second argument (the others were bumped one position).
138 156
139 157 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
140 158
141 159 * IPython/iplib.py (embed_mainloop): fix tab-completion in
142 160 embedded instances (which can be done now thanks to Vivian's
143 161 frame-handling fixes for pdb).
144 162 (InteractiveShell.__init__): Fix namespace handling problem in
145 163 embedded instances. We were overwriting __main__ unconditionally,
146 164 and this should only be done for 'full' (non-embedded) IPython;
147 165 embedded instances must respect the caller's __main__. Thanks to
148 166 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
149 167
150 168 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
151 169
152 170 * setup.py: added download_url to setup(). This registers the
153 171 download address at PyPI, which is not only useful to humans
154 172 browsing the site, but is also picked up by setuptools (the Eggs
155 173 machinery). Thanks to Ville and R. Kern for the info/discussion
156 174 on this.
157 175
158 176 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
159 177
160 178 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
161 179 This brings a lot of nice functionality to the pdb mode, which now
162 180 has tab-completion, syntax highlighting, and better stack handling
163 181 than before. Many thanks to Vivian De Smedt
164 182 <vivian-AT-vdesmedt.com> for the original patches.
165 183
166 184 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
167 185
168 186 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
169 187 sequence to consistently accept the banner argument. The
170 188 inconsistency was tripping SAGE, thanks to Gary Zablackis
171 189 <gzabl-AT-yahoo.com> for the report.
172 190
173 191 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
174 192
175 193 * IPython/iplib.py (InteractiveShell.post_config_initialization):
176 194 Fix bug where a naked 'alias' call in the ipythonrc file would
177 195 cause a crash. Bug reported by Jorgen Stenarson.
178 196
179 197 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
180 198
181 199 * IPython/ipmaker.py (make_IPython): cleanups which should improve
182 200 startup time.
183 201
184 202 * IPython/iplib.py (runcode): my globals 'fix' for embedded
185 203 instances had introduced a bug with globals in normal code. Now
186 204 it's working in all cases.
187 205
188 206 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
189 207 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
190 208 has been introduced to set the default case sensitivity of the
191 209 searches. Users can still select either mode at runtime on a
192 210 per-search basis.
193 211
194 212 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
195 213
196 214 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
197 215 attributes in wildcard searches for subclasses. Modified version
198 216 of a patch by Jorgen.
199 217
200 218 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
201 219
202 220 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
203 221 embedded instances. I added a user_global_ns attribute to the
204 222 InteractiveShell class to handle this.
205 223
206 224 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
207 225
208 226 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
209 227 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
210 228 (reported under win32, but may happen also in other platforms).
211 229 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
212 230
213 231 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
214 232
215 233 * IPython/Magic.py (magic_psearch): new support for wildcard
216 234 patterns. Now, typing ?a*b will list all names which begin with a
217 235 and end in b, for example. The %psearch magic has full
218 236 docstrings. Many thanks to JΓΆrgen Stenarson
219 237 <jorgen.stenarson-AT-bostream.nu>, author of the patches
220 238 implementing this functionality.
221 239
222 240 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
223 241
224 242 * Manual: fixed long-standing annoyance of double-dashes (as in
225 243 --prefix=~, for example) being stripped in the HTML version. This
226 244 is a latex2html bug, but a workaround was provided. Many thanks
227 245 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
228 246 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
229 247 rolling. This seemingly small issue had tripped a number of users
230 248 when first installing, so I'm glad to see it gone.
231 249
232 250 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
233 251
234 252 * IPython/Extensions/numeric_formats.py: fix missing import,
235 253 reported by Stephen Walton.
236 254
237 255 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
238 256
239 257 * IPython/demo.py: finish demo module, fully documented now.
240 258
241 259 * IPython/genutils.py (file_read): simple little utility to read a
242 260 file and ensure it's closed afterwards.
243 261
244 262 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
245 263
246 264 * IPython/demo.py (Demo.__init__): added support for individually
247 265 tagging blocks for automatic execution.
248 266
249 267 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
250 268 syntax-highlighted python sources, requested by John.
251 269
252 270 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
253 271
254 272 * IPython/demo.py (Demo.again): fix bug where again() blocks after
255 273 finishing.
256 274
257 275 * IPython/genutils.py (shlex_split): moved from Magic to here,
258 276 where all 2.2 compatibility stuff lives. I needed it for demo.py.
259 277
260 278 * IPython/demo.py (Demo.__init__): added support for silent
261 279 blocks, improved marks as regexps, docstrings written.
262 280 (Demo.__init__): better docstring, added support for sys.argv.
263 281
264 282 * IPython/genutils.py (marquee): little utility used by the demo
265 283 code, handy in general.
266 284
267 285 * IPython/demo.py (Demo.__init__): new class for interactive
268 286 demos. Not documented yet, I just wrote it in a hurry for
269 287 scipy'05. Will docstring later.
270 288
271 289 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
272 290
273 291 * IPython/Shell.py (sigint_handler): Drastic simplification which
274 292 also seems to make Ctrl-C work correctly across threads! This is
275 293 so simple, that I can't beleive I'd missed it before. Needs more
276 294 testing, though.
277 295 (KBINT): Never mind, revert changes. I'm sure I'd tried something
278 296 like this before...
279 297
280 298 * IPython/genutils.py (get_home_dir): add protection against
281 299 non-dirs in win32 registry.
282 300
283 301 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
284 302 bug where dict was mutated while iterating (pysh crash).
285 303
286 304 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
287 305
288 306 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
289 307 spurious newlines added by this routine. After a report by
290 308 F. Mantegazza.
291 309
292 310 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
293 311
294 312 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
295 313 calls. These were a leftover from the GTK 1.x days, and can cause
296 314 problems in certain cases (after a report by John Hunter).
297 315
298 316 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
299 317 os.getcwd() fails at init time. Thanks to patch from David Remahl
300 318 <chmod007-AT-mac.com>.
301 319 (InteractiveShell.__init__): prevent certain special magics from
302 320 being shadowed by aliases. Closes
303 321 http://www.scipy.net/roundup/ipython/issue41.
304 322
305 323 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
306 324
307 325 * IPython/iplib.py (InteractiveShell.complete): Added new
308 326 top-level completion method to expose the completion mechanism
309 327 beyond readline-based environments.
310 328
311 329 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
312 330
313 331 * tools/ipsvnc (svnversion): fix svnversion capture.
314 332
315 333 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
316 334 attribute to self, which was missing. Before, it was set by a
317 335 routine which in certain cases wasn't being called, so the
318 336 instance could end up missing the attribute. This caused a crash.
319 337 Closes http://www.scipy.net/roundup/ipython/issue40.
320 338
321 339 2005-08-16 Fernando Perez <fperez@colorado.edu>
322 340
323 341 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
324 342 contains non-string attribute. Closes
325 343 http://www.scipy.net/roundup/ipython/issue38.
326 344
327 345 2005-08-14 Fernando Perez <fperez@colorado.edu>
328 346
329 347 * tools/ipsvnc: Minor improvements, to add changeset info.
330 348
331 349 2005-08-12 Fernando Perez <fperez@colorado.edu>
332 350
333 351 * IPython/iplib.py (runsource): remove self.code_to_run_src
334 352 attribute. I realized this is nothing more than
335 353 '\n'.join(self.buffer), and having the same data in two different
336 354 places is just asking for synchronization bugs. This may impact
337 355 people who have custom exception handlers, so I need to warn
338 356 ipython-dev about it (F. Mantegazza may use them).
339 357
340 358 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
341 359
342 360 * IPython/genutils.py: fix 2.2 compatibility (generators)
343 361
344 362 2005-07-18 Fernando Perez <fperez@colorado.edu>
345 363
346 364 * IPython/genutils.py (get_home_dir): fix to help users with
347 365 invalid $HOME under win32.
348 366
349 367 2005-07-17 Fernando Perez <fperez@colorado.edu>
350 368
351 369 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
352 370 some old hacks and clean up a bit other routines; code should be
353 371 simpler and a bit faster.
354 372
355 373 * IPython/iplib.py (interact): removed some last-resort attempts
356 374 to survive broken stdout/stderr. That code was only making it
357 375 harder to abstract out the i/o (necessary for gui integration),
358 376 and the crashes it could prevent were extremely rare in practice
359 377 (besides being fully user-induced in a pretty violent manner).
360 378
361 379 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
362 380 Nothing major yet, but the code is simpler to read; this should
363 381 make it easier to do more serious modifications in the future.
364 382
365 383 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
366 384 which broke in .15 (thanks to a report by Ville).
367 385
368 386 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
369 387 be quite correct, I know next to nothing about unicode). This
370 388 will allow unicode strings to be used in prompts, amongst other
371 389 cases. It also will prevent ipython from crashing when unicode
372 390 shows up unexpectedly in many places. If ascii encoding fails, we
373 391 assume utf_8. Currently the encoding is not a user-visible
374 392 setting, though it could be made so if there is demand for it.
375 393
376 394 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
377 395
378 396 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
379 397
380 398 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
381 399
382 400 * IPython/genutils.py: Add 2.2 compatibility here, so all other
383 401 code can work transparently for 2.2/2.3.
384 402
385 403 2005-07-16 Fernando Perez <fperez@colorado.edu>
386 404
387 405 * IPython/ultraTB.py (ExceptionColors): Make a global variable
388 406 out of the color scheme table used for coloring exception
389 407 tracebacks. This allows user code to add new schemes at runtime.
390 408 This is a minimally modified version of the patch at
391 409 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
392 410 for the contribution.
393 411
394 412 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
395 413 slightly modified version of the patch in
396 414 http://www.scipy.net/roundup/ipython/issue34, which also allows me
397 415 to remove the previous try/except solution (which was costlier).
398 416 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
399 417
400 418 2005-06-08 Fernando Perez <fperez@colorado.edu>
401 419
402 420 * IPython/iplib.py (write/write_err): Add methods to abstract all
403 421 I/O a bit more.
404 422
405 423 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
406 424 warning, reported by Aric Hagberg, fix by JD Hunter.
407 425
408 426 2005-06-02 *** Released version 0.6.15
409 427
410 428 2005-06-01 Fernando Perez <fperez@colorado.edu>
411 429
412 430 * IPython/iplib.py (MagicCompleter.file_matches): Fix
413 431 tab-completion of filenames within open-quoted strings. Note that
414 432 this requires that in ~/.ipython/ipythonrc, users change the
415 433 readline delimiters configuration to read:
416 434
417 435 readline_remove_delims -/~
418 436
419 437
420 438 2005-05-31 *** Released version 0.6.14
421 439
422 440 2005-05-29 Fernando Perez <fperez@colorado.edu>
423 441
424 442 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
425 443 with files not on the filesystem. Reported by Eliyahu Sandler
426 444 <eli@gondolin.net>
427 445
428 446 2005-05-22 Fernando Perez <fperez@colorado.edu>
429 447
430 448 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
431 449 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
432 450
433 451 2005-05-19 Fernando Perez <fperez@colorado.edu>
434 452
435 453 * IPython/iplib.py (safe_execfile): close a file which could be
436 454 left open (causing problems in win32, which locks open files).
437 455 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
438 456
439 457 2005-05-18 Fernando Perez <fperez@colorado.edu>
440 458
441 459 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
442 460 keyword arguments correctly to safe_execfile().
443 461
444 462 2005-05-13 Fernando Perez <fperez@colorado.edu>
445 463
446 464 * ipython.1: Added info about Qt to manpage, and threads warning
447 465 to usage page (invoked with --help).
448 466
449 467 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
450 468 new matcher (it goes at the end of the priority list) to do
451 469 tab-completion on named function arguments. Submitted by George
452 470 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
453 471 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
454 472 for more details.
455 473
456 474 * IPython/Magic.py (magic_run): Added new -e flag to ignore
457 475 SystemExit exceptions in the script being run. Thanks to a report
458 476 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
459 477 producing very annoying behavior when running unit tests.
460 478
461 479 2005-05-12 Fernando Perez <fperez@colorado.edu>
462 480
463 481 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
464 482 which I'd broken (again) due to a changed regexp. In the process,
465 483 added ';' as an escape to auto-quote the whole line without
466 484 splitting its arguments. Thanks to a report by Jerry McRae
467 485 <qrs0xyc02-AT-sneakemail.com>.
468 486
469 487 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
470 488 possible crashes caused by a TokenError. Reported by Ed Schofield
471 489 <schofield-AT-ftw.at>.
472 490
473 491 2005-05-06 Fernando Perez <fperez@colorado.edu>
474 492
475 493 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
476 494
477 495 2005-04-29 Fernando Perez <fperez@colorado.edu>
478 496
479 497 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
480 498 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
481 499 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
482 500 which provides support for Qt interactive usage (similar to the
483 501 existing one for WX and GTK). This had been often requested.
484 502
485 503 2005-04-14 *** Released version 0.6.13
486 504
487 505 2005-04-08 Fernando Perez <fperez@colorado.edu>
488 506
489 507 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
490 508 from _ofind, which gets called on almost every input line. Now,
491 509 we only try to get docstrings if they are actually going to be
492 510 used (the overhead of fetching unnecessary docstrings can be
493 511 noticeable for certain objects, such as Pyro proxies).
494 512
495 513 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
496 514 for completers. For some reason I had been passing them the state
497 515 variable, which completers never actually need, and was in
498 516 conflict with the rlcompleter API. Custom completers ONLY need to
499 517 take the text parameter.
500 518
501 519 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
502 520 work correctly in pysh. I've also moved all the logic which used
503 521 to be in pysh.py here, which will prevent problems with future
504 522 upgrades. However, this time I must warn users to update their
505 523 pysh profile to include the line
506 524
507 525 import_all IPython.Extensions.InterpreterExec
508 526
509 527 because otherwise things won't work for them. They MUST also
510 528 delete pysh.py and the line
511 529
512 530 execfile pysh.py
513 531
514 532 from their ipythonrc-pysh.
515 533
516 534 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
517 535 robust in the face of objects whose dir() returns non-strings
518 536 (which it shouldn't, but some broken libs like ITK do). Thanks to
519 537 a patch by John Hunter (implemented differently, though). Also
520 538 minor improvements by using .extend instead of + on lists.
521 539
522 540 * pysh.py:
523 541
524 542 2005-04-06 Fernando Perez <fperez@colorado.edu>
525 543
526 544 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
527 545 by default, so that all users benefit from it. Those who don't
528 546 want it can still turn it off.
529 547
530 548 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
531 549 config file, I'd forgotten about this, so users were getting it
532 550 off by default.
533 551
534 552 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
535 553 consistency. Now magics can be called in multiline statements,
536 554 and python variables can be expanded in magic calls via $var.
537 555 This makes the magic system behave just like aliases or !system
538 556 calls.
539 557
540 558 2005-03-28 Fernando Perez <fperez@colorado.edu>
541 559
542 560 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
543 561 expensive string additions for building command. Add support for
544 562 trailing ';' when autocall is used.
545 563
546 564 2005-03-26 Fernando Perez <fperez@colorado.edu>
547 565
548 566 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
549 567 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
550 568 ipython.el robust against prompts with any number of spaces
551 569 (including 0) after the ':' character.
552 570
553 571 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
554 572 continuation prompt, which misled users to think the line was
555 573 already indented. Closes debian Bug#300847, reported to me by
556 574 Norbert Tretkowski <tretkowski-AT-inittab.de>.
557 575
558 576 2005-03-23 Fernando Perez <fperez@colorado.edu>
559 577
560 578 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
561 579 properly aligned if they have embedded newlines.
562 580
563 581 * IPython/iplib.py (runlines): Add a public method to expose
564 582 IPython's code execution machinery, so that users can run strings
565 583 as if they had been typed at the prompt interactively.
566 584 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
567 585 methods which can call the system shell, but with python variable
568 586 expansion. The three such methods are: __IPYTHON__.system,
569 587 .getoutput and .getoutputerror. These need to be documented in a
570 588 'public API' section (to be written) of the manual.
571 589
572 590 2005-03-20 Fernando Perez <fperez@colorado.edu>
573 591
574 592 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
575 593 for custom exception handling. This is quite powerful, and it
576 594 allows for user-installable exception handlers which can trap
577 595 custom exceptions at runtime and treat them separately from
578 596 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
579 597 Mantegazza <mantegazza-AT-ill.fr>.
580 598 (InteractiveShell.set_custom_completer): public API function to
581 599 add new completers at runtime.
582 600
583 601 2005-03-19 Fernando Perez <fperez@colorado.edu>
584 602
585 603 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
586 604 allow objects which provide their docstrings via non-standard
587 605 mechanisms (like Pyro proxies) to still be inspected by ipython's
588 606 ? system.
589 607
590 608 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
591 609 automatic capture system. I tried quite hard to make it work
592 610 reliably, and simply failed. I tried many combinations with the
593 611 subprocess module, but eventually nothing worked in all needed
594 612 cases (not blocking stdin for the child, duplicating stdout
595 613 without blocking, etc). The new %sc/%sx still do capture to these
596 614 magical list/string objects which make shell use much more
597 615 conveninent, so not all is lost.
598 616
599 617 XXX - FIX MANUAL for the change above!
600 618
601 619 (runsource): I copied code.py's runsource() into ipython to modify
602 620 it a bit. Now the code object and source to be executed are
603 621 stored in ipython. This makes this info accessible to third-party
604 622 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
605 623 Mantegazza <mantegazza-AT-ill.fr>.
606 624
607 625 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
608 626 history-search via readline (like C-p/C-n). I'd wanted this for a
609 627 long time, but only recently found out how to do it. For users
610 628 who already have their ipythonrc files made and want this, just
611 629 add:
612 630
613 631 readline_parse_and_bind "\e[A": history-search-backward
614 632 readline_parse_and_bind "\e[B": history-search-forward
615 633
616 634 2005-03-18 Fernando Perez <fperez@colorado.edu>
617 635
618 636 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
619 637 LSString and SList classes which allow transparent conversions
620 638 between list mode and whitespace-separated string.
621 639 (magic_r): Fix recursion problem in %r.
622 640
623 641 * IPython/genutils.py (LSString): New class to be used for
624 642 automatic storage of the results of all alias/system calls in _o
625 643 and _e (stdout/err). These provide a .l/.list attribute which
626 644 does automatic splitting on newlines. This means that for most
627 645 uses, you'll never need to do capturing of output with %sc/%sx
628 646 anymore, since ipython keeps this always done for you. Note that
629 647 only the LAST results are stored, the _o/e variables are
630 648 overwritten on each call. If you need to save their contents
631 649 further, simply bind them to any other name.
632 650
633 651 2005-03-17 Fernando Perez <fperez@colorado.edu>
634 652
635 653 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
636 654 prompt namespace handling.
637 655
638 656 2005-03-16 Fernando Perez <fperez@colorado.edu>
639 657
640 658 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
641 659 classic prompts to be '>>> ' (final space was missing, and it
642 660 trips the emacs python mode).
643 661 (BasePrompt.__str__): Added safe support for dynamic prompt
644 662 strings. Now you can set your prompt string to be '$x', and the
645 663 value of x will be printed from your interactive namespace. The
646 664 interpolation syntax includes the full Itpl support, so
647 665 ${foo()+x+bar()} is a valid prompt string now, and the function
648 666 calls will be made at runtime.
649 667
650 668 2005-03-15 Fernando Perez <fperez@colorado.edu>
651 669
652 670 * IPython/Magic.py (magic_history): renamed %hist to %history, to
653 671 avoid name clashes in pylab. %hist still works, it just forwards
654 672 the call to %history.
655 673
656 674 2005-03-02 *** Released version 0.6.12
657 675
658 676 2005-03-02 Fernando Perez <fperez@colorado.edu>
659 677
660 678 * IPython/iplib.py (handle_magic): log magic calls properly as
661 679 ipmagic() function calls.
662 680
663 681 * IPython/Magic.py (magic_time): Improved %time to support
664 682 statements and provide wall-clock as well as CPU time.
665 683
666 684 2005-02-27 Fernando Perez <fperez@colorado.edu>
667 685
668 686 * IPython/hooks.py: New hooks module, to expose user-modifiable
669 687 IPython functionality in a clean manner. For now only the editor
670 688 hook is actually written, and other thigns which I intend to turn
671 689 into proper hooks aren't yet there. The display and prefilter
672 690 stuff, for example, should be hooks. But at least now the
673 691 framework is in place, and the rest can be moved here with more
674 692 time later. IPython had had a .hooks variable for a long time for
675 693 this purpose, but I'd never actually used it for anything.
676 694
677 695 2005-02-26 Fernando Perez <fperez@colorado.edu>
678 696
679 697 * IPython/ipmaker.py (make_IPython): make the default ipython
680 698 directory be called _ipython under win32, to follow more the
681 699 naming peculiarities of that platform (where buggy software like
682 700 Visual Sourcesafe breaks with .named directories). Reported by
683 701 Ville Vainio.
684 702
685 703 2005-02-23 Fernando Perez <fperez@colorado.edu>
686 704
687 705 * IPython/iplib.py (InteractiveShell.__init__): removed a few
688 706 auto_aliases for win32 which were causing problems. Users can
689 707 define the ones they personally like.
690 708
691 709 2005-02-21 Fernando Perez <fperez@colorado.edu>
692 710
693 711 * IPython/Magic.py (magic_time): new magic to time execution of
694 712 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
695 713
696 714 2005-02-19 Fernando Perez <fperez@colorado.edu>
697 715
698 716 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
699 717 into keys (for prompts, for example).
700 718
701 719 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
702 720 prompts in case users want them. This introduces a small behavior
703 721 change: ipython does not automatically add a space to all prompts
704 722 anymore. To get the old prompts with a space, users should add it
705 723 manually to their ipythonrc file, so for example prompt_in1 should
706 724 now read 'In [\#]: ' instead of 'In [\#]:'.
707 725 (BasePrompt.__init__): New option prompts_pad_left (only in rc
708 726 file) to control left-padding of secondary prompts.
709 727
710 728 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
711 729 the profiler can't be imported. Fix for Debian, which removed
712 730 profile.py because of License issues. I applied a slightly
713 731 modified version of the original Debian patch at
714 732 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
715 733
716 734 2005-02-17 Fernando Perez <fperez@colorado.edu>
717 735
718 736 * IPython/genutils.py (native_line_ends): Fix bug which would
719 737 cause improper line-ends under win32 b/c I was not opening files
720 738 in binary mode. Bug report and fix thanks to Ville.
721 739
722 740 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
723 741 trying to catch spurious foo[1] autocalls. My fix actually broke
724 742 ',/' autoquote/call with explicit escape (bad regexp).
725 743
726 744 2005-02-15 *** Released version 0.6.11
727 745
728 746 2005-02-14 Fernando Perez <fperez@colorado.edu>
729 747
730 748 * IPython/background_jobs.py: New background job management
731 749 subsystem. This is implemented via a new set of classes, and
732 750 IPython now provides a builtin 'jobs' object for background job
733 751 execution. A convenience %bg magic serves as a lightweight
734 752 frontend for starting the more common type of calls. This was
735 753 inspired by discussions with B. Granger and the BackgroundCommand
736 754 class described in the book Python Scripting for Computational
737 755 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
738 756 (although ultimately no code from this text was used, as IPython's
739 757 system is a separate implementation).
740 758
741 759 * IPython/iplib.py (MagicCompleter.python_matches): add new option
742 760 to control the completion of single/double underscore names
743 761 separately. As documented in the example ipytonrc file, the
744 762 readline_omit__names variable can now be set to 2, to omit even
745 763 single underscore names. Thanks to a patch by Brian Wong
746 764 <BrianWong-AT-AirgoNetworks.Com>.
747 765 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
748 766 be autocalled as foo([1]) if foo were callable. A problem for
749 767 things which are both callable and implement __getitem__.
750 768 (init_readline): Fix autoindentation for win32. Thanks to a patch
751 769 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
752 770
753 771 2005-02-12 Fernando Perez <fperez@colorado.edu>
754 772
755 773 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
756 774 which I had written long ago to sort out user error messages which
757 775 may occur during startup. This seemed like a good idea initially,
758 776 but it has proven a disaster in retrospect. I don't want to
759 777 change much code for now, so my fix is to set the internal 'debug'
760 778 flag to true everywhere, whose only job was precisely to control
761 779 this subsystem. This closes issue 28 (as well as avoiding all
762 780 sorts of strange hangups which occur from time to time).
763 781
764 782 2005-02-07 Fernando Perez <fperez@colorado.edu>
765 783
766 784 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
767 785 previous call produced a syntax error.
768 786
769 787 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
770 788 classes without constructor.
771 789
772 790 2005-02-06 Fernando Perez <fperez@colorado.edu>
773 791
774 792 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
775 793 completions with the results of each matcher, so we return results
776 794 to the user from all namespaces. This breaks with ipython
777 795 tradition, but I think it's a nicer behavior. Now you get all
778 796 possible completions listed, from all possible namespaces (python,
779 797 filesystem, magics...) After a request by John Hunter
780 798 <jdhunter-AT-nitace.bsd.uchicago.edu>.
781 799
782 800 2005-02-05 Fernando Perez <fperez@colorado.edu>
783 801
784 802 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
785 803 the call had quote characters in it (the quotes were stripped).
786 804
787 805 2005-01-31 Fernando Perez <fperez@colorado.edu>
788 806
789 807 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
790 808 Itpl.itpl() to make the code more robust against psyco
791 809 optimizations.
792 810
793 811 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
794 812 of causing an exception. Quicker, cleaner.
795 813
796 814 2005-01-28 Fernando Perez <fperez@colorado.edu>
797 815
798 816 * scripts/ipython_win_post_install.py (install): hardcode
799 817 sys.prefix+'python.exe' as the executable path. It turns out that
800 818 during the post-installation run, sys.executable resolves to the
801 819 name of the binary installer! I should report this as a distutils
802 820 bug, I think. I updated the .10 release with this tiny fix, to
803 821 avoid annoying the lists further.
804 822
805 823 2005-01-27 *** Released version 0.6.10
806 824
807 825 2005-01-27 Fernando Perez <fperez@colorado.edu>
808 826
809 827 * IPython/numutils.py (norm): Added 'inf' as optional name for
810 828 L-infinity norm, included references to mathworld.com for vector
811 829 norm definitions.
812 830 (amin/amax): added amin/amax for array min/max. Similar to what
813 831 pylab ships with after the recent reorganization of names.
814 832 (spike/spike_odd): removed deprecated spike/spike_odd functions.
815 833
816 834 * ipython.el: committed Alex's recent fixes and improvements.
817 835 Tested with python-mode from CVS, and it looks excellent. Since
818 836 python-mode hasn't released anything in a while, I'm temporarily
819 837 putting a copy of today's CVS (v 4.70) of python-mode in:
820 838 http://ipython.scipy.org/tmp/python-mode.el
821 839
822 840 * scripts/ipython_win_post_install.py (install): Win32 fix to use
823 841 sys.executable for the executable name, instead of assuming it's
824 842 called 'python.exe' (the post-installer would have produced broken
825 843 setups on systems with a differently named python binary).
826 844
827 845 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
828 846 references to os.linesep, to make the code more
829 847 platform-independent. This is also part of the win32 coloring
830 848 fixes.
831 849
832 850 * IPython/genutils.py (page_dumb): Remove attempts to chop long
833 851 lines, which actually cause coloring bugs because the length of
834 852 the line is very difficult to correctly compute with embedded
835 853 escapes. This was the source of all the coloring problems under
836 854 Win32. I think that _finally_, Win32 users have a properly
837 855 working ipython in all respects. This would never have happened
838 856 if not for Gary Bishop and Viktor Ransmayr's great help and work.
839 857
840 858 2005-01-26 *** Released version 0.6.9
841 859
842 860 2005-01-25 Fernando Perez <fperez@colorado.edu>
843 861
844 862 * setup.py: finally, we have a true Windows installer, thanks to
845 863 the excellent work of Viktor Ransmayr
846 864 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
847 865 Windows users. The setup routine is quite a bit cleaner thanks to
848 866 this, and the post-install script uses the proper functions to
849 867 allow a clean de-installation using the standard Windows Control
850 868 Panel.
851 869
852 870 * IPython/genutils.py (get_home_dir): changed to use the $HOME
853 871 environment variable under all OSes (including win32) if
854 872 available. This will give consistency to win32 users who have set
855 873 this variable for any reason. If os.environ['HOME'] fails, the
856 874 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
857 875
858 876 2005-01-24 Fernando Perez <fperez@colorado.edu>
859 877
860 878 * IPython/numutils.py (empty_like): add empty_like(), similar to
861 879 zeros_like() but taking advantage of the new empty() Numeric routine.
862 880
863 881 2005-01-23 *** Released version 0.6.8
864 882
865 883 2005-01-22 Fernando Perez <fperez@colorado.edu>
866 884
867 885 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
868 886 automatic show() calls. After discussing things with JDH, it
869 887 turns out there are too many corner cases where this can go wrong.
870 888 It's best not to try to be 'too smart', and simply have ipython
871 889 reproduce as much as possible the default behavior of a normal
872 890 python shell.
873 891
874 892 * IPython/iplib.py (InteractiveShell.__init__): Modified the
875 893 line-splitting regexp and _prefilter() to avoid calling getattr()
876 894 on assignments. This closes
877 895 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
878 896 readline uses getattr(), so a simple <TAB> keypress is still
879 897 enough to trigger getattr() calls on an object.
880 898
881 899 2005-01-21 Fernando Perez <fperez@colorado.edu>
882 900
883 901 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
884 902 docstring under pylab so it doesn't mask the original.
885 903
886 904 2005-01-21 *** Released version 0.6.7
887 905
888 906 2005-01-21 Fernando Perez <fperez@colorado.edu>
889 907
890 908 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
891 909 signal handling for win32 users in multithreaded mode.
892 910
893 911 2005-01-17 Fernando Perez <fperez@colorado.edu>
894 912
895 913 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
896 914 instances with no __init__. After a crash report by Norbert Nemec
897 915 <Norbert-AT-nemec-online.de>.
898 916
899 917 2005-01-14 Fernando Perez <fperez@colorado.edu>
900 918
901 919 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
902 920 names for verbose exceptions, when multiple dotted names and the
903 921 'parent' object were present on the same line.
904 922
905 923 2005-01-11 Fernando Perez <fperez@colorado.edu>
906 924
907 925 * IPython/genutils.py (flag_calls): new utility to trap and flag
908 926 calls in functions. I need it to clean up matplotlib support.
909 927 Also removed some deprecated code in genutils.
910 928
911 929 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
912 930 that matplotlib scripts called with %run, which don't call show()
913 931 themselves, still have their plotting windows open.
914 932
915 933 2005-01-05 Fernando Perez <fperez@colorado.edu>
916 934
917 935 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
918 936 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
919 937
920 938 2004-12-19 Fernando Perez <fperez@colorado.edu>
921 939
922 940 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
923 941 parent_runcode, which was an eyesore. The same result can be
924 942 obtained with Python's regular superclass mechanisms.
925 943
926 944 2004-12-17 Fernando Perez <fperez@colorado.edu>
927 945
928 946 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
929 947 reported by Prabhu.
930 948 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
931 949 sys.stderr) instead of explicitly calling sys.stderr. This helps
932 950 maintain our I/O abstractions clean, for future GUI embeddings.
933 951
934 952 * IPython/genutils.py (info): added new utility for sys.stderr
935 953 unified info message handling (thin wrapper around warn()).
936 954
937 955 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
938 956 composite (dotted) names on verbose exceptions.
939 957 (VerboseTB.nullrepr): harden against another kind of errors which
940 958 Python's inspect module can trigger, and which were crashing
941 959 IPython. Thanks to a report by Marco Lombardi
942 960 <mlombard-AT-ma010192.hq.eso.org>.
943 961
944 962 2004-12-13 *** Released version 0.6.6
945 963
946 964 2004-12-12 Fernando Perez <fperez@colorado.edu>
947 965
948 966 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
949 967 generated by pygtk upon initialization if it was built without
950 968 threads (for matplotlib users). After a crash reported by
951 969 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
952 970
953 971 * IPython/ipmaker.py (make_IPython): fix small bug in the
954 972 import_some parameter for multiple imports.
955 973
956 974 * IPython/iplib.py (ipmagic): simplified the interface of
957 975 ipmagic() to take a single string argument, just as it would be
958 976 typed at the IPython cmd line.
959 977 (ipalias): Added new ipalias() with an interface identical to
960 978 ipmagic(). This completes exposing a pure python interface to the
961 979 alias and magic system, which can be used in loops or more complex
962 980 code where IPython's automatic line mangling is not active.
963 981
964 982 * IPython/genutils.py (timing): changed interface of timing to
965 983 simply run code once, which is the most common case. timings()
966 984 remains unchanged, for the cases where you want multiple runs.
967 985
968 986 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
969 987 bug where Python2.2 crashes with exec'ing code which does not end
970 988 in a single newline. Python 2.3 is OK, so I hadn't noticed this
971 989 before.
972 990
973 991 2004-12-10 Fernando Perez <fperez@colorado.edu>
974 992
975 993 * IPython/Magic.py (Magic.magic_prun): changed name of option from
976 994 -t to -T, to accomodate the new -t flag in %run (the %run and
977 995 %prun options are kind of intermixed, and it's not easy to change
978 996 this with the limitations of python's getopt).
979 997
980 998 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
981 999 the execution of scripts. It's not as fine-tuned as timeit.py,
982 1000 but it works from inside ipython (and under 2.2, which lacks
983 1001 timeit.py). Optionally a number of runs > 1 can be given for
984 1002 timing very short-running code.
985 1003
986 1004 * IPython/genutils.py (uniq_stable): new routine which returns a
987 1005 list of unique elements in any iterable, but in stable order of
988 1006 appearance. I needed this for the ultraTB fixes, and it's a handy
989 1007 utility.
990 1008
991 1009 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
992 1010 dotted names in Verbose exceptions. This had been broken since
993 1011 the very start, now x.y will properly be printed in a Verbose
994 1012 traceback, instead of x being shown and y appearing always as an
995 1013 'undefined global'. Getting this to work was a bit tricky,
996 1014 because by default python tokenizers are stateless. Saved by
997 1015 python's ability to easily add a bit of state to an arbitrary
998 1016 function (without needing to build a full-blown callable object).
999 1017
1000 1018 Also big cleanup of this code, which had horrendous runtime
1001 1019 lookups of zillions of attributes for colorization. Moved all
1002 1020 this code into a few templates, which make it cleaner and quicker.
1003 1021
1004 1022 Printout quality was also improved for Verbose exceptions: one
1005 1023 variable per line, and memory addresses are printed (this can be
1006 1024 quite handy in nasty debugging situations, which is what Verbose
1007 1025 is for).
1008 1026
1009 1027 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1010 1028 the command line as scripts to be loaded by embedded instances.
1011 1029 Doing so has the potential for an infinite recursion if there are
1012 1030 exceptions thrown in the process. This fixes a strange crash
1013 1031 reported by Philippe MULLER <muller-AT-irit.fr>.
1014 1032
1015 1033 2004-12-09 Fernando Perez <fperez@colorado.edu>
1016 1034
1017 1035 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1018 1036 to reflect new names in matplotlib, which now expose the
1019 1037 matlab-compatible interface via a pylab module instead of the
1020 1038 'matlab' name. The new code is backwards compatible, so users of
1021 1039 all matplotlib versions are OK. Patch by J. Hunter.
1022 1040
1023 1041 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1024 1042 of __init__ docstrings for instances (class docstrings are already
1025 1043 automatically printed). Instances with customized docstrings
1026 1044 (indep. of the class) are also recognized and all 3 separate
1027 1045 docstrings are printed (instance, class, constructor). After some
1028 1046 comments/suggestions by J. Hunter.
1029 1047
1030 1048 2004-12-05 Fernando Perez <fperez@colorado.edu>
1031 1049
1032 1050 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1033 1051 warnings when tab-completion fails and triggers an exception.
1034 1052
1035 1053 2004-12-03 Fernando Perez <fperez@colorado.edu>
1036 1054
1037 1055 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1038 1056 be triggered when using 'run -p'. An incorrect option flag was
1039 1057 being set ('d' instead of 'D').
1040 1058 (manpage): fix missing escaped \- sign.
1041 1059
1042 1060 2004-11-30 *** Released version 0.6.5
1043 1061
1044 1062 2004-11-30 Fernando Perez <fperez@colorado.edu>
1045 1063
1046 1064 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1047 1065 setting with -d option.
1048 1066
1049 1067 * setup.py (docfiles): Fix problem where the doc glob I was using
1050 1068 was COMPLETELY BROKEN. It was giving the right files by pure
1051 1069 accident, but failed once I tried to include ipython.el. Note:
1052 1070 glob() does NOT allow you to do exclusion on multiple endings!
1053 1071
1054 1072 2004-11-29 Fernando Perez <fperez@colorado.edu>
1055 1073
1056 1074 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1057 1075 the manpage as the source. Better formatting & consistency.
1058 1076
1059 1077 * IPython/Magic.py (magic_run): Added new -d option, to run
1060 1078 scripts under the control of the python pdb debugger. Note that
1061 1079 this required changing the %prun option -d to -D, to avoid a clash
1062 1080 (since %run must pass options to %prun, and getopt is too dumb to
1063 1081 handle options with string values with embedded spaces). Thanks
1064 1082 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1065 1083 (magic_who_ls): added type matching to %who and %whos, so that one
1066 1084 can filter their output to only include variables of certain
1067 1085 types. Another suggestion by Matthew.
1068 1086 (magic_whos): Added memory summaries in kb and Mb for arrays.
1069 1087 (magic_who): Improve formatting (break lines every 9 vars).
1070 1088
1071 1089 2004-11-28 Fernando Perez <fperez@colorado.edu>
1072 1090
1073 1091 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1074 1092 cache when empty lines were present.
1075 1093
1076 1094 2004-11-24 Fernando Perez <fperez@colorado.edu>
1077 1095
1078 1096 * IPython/usage.py (__doc__): document the re-activated threading
1079 1097 options for WX and GTK.
1080 1098
1081 1099 2004-11-23 Fernando Perez <fperez@colorado.edu>
1082 1100
1083 1101 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1084 1102 the -wthread and -gthread options, along with a new -tk one to try
1085 1103 and coordinate Tk threading with wx/gtk. The tk support is very
1086 1104 platform dependent, since it seems to require Tcl and Tk to be
1087 1105 built with threads (Fedora1/2 appears NOT to have it, but in
1088 1106 Prabhu's Debian boxes it works OK). But even with some Tk
1089 1107 limitations, this is a great improvement.
1090 1108
1091 1109 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1092 1110 info in user prompts. Patch by Prabhu.
1093 1111
1094 1112 2004-11-18 Fernando Perez <fperez@colorado.edu>
1095 1113
1096 1114 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1097 1115 EOFErrors and bail, to avoid infinite loops if a non-terminating
1098 1116 file is fed into ipython. Patch submitted in issue 19 by user,
1099 1117 many thanks.
1100 1118
1101 1119 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1102 1120 autoquote/parens in continuation prompts, which can cause lots of
1103 1121 problems. Closes roundup issue 20.
1104 1122
1105 1123 2004-11-17 Fernando Perez <fperez@colorado.edu>
1106 1124
1107 1125 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1108 1126 reported as debian bug #280505. I'm not sure my local changelog
1109 1127 entry has the proper debian format (Jack?).
1110 1128
1111 1129 2004-11-08 *** Released version 0.6.4
1112 1130
1113 1131 2004-11-08 Fernando Perez <fperez@colorado.edu>
1114 1132
1115 1133 * IPython/iplib.py (init_readline): Fix exit message for Windows
1116 1134 when readline is active. Thanks to a report by Eric Jones
1117 1135 <eric-AT-enthought.com>.
1118 1136
1119 1137 2004-11-07 Fernando Perez <fperez@colorado.edu>
1120 1138
1121 1139 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1122 1140 sometimes seen by win2k/cygwin users.
1123 1141
1124 1142 2004-11-06 Fernando Perez <fperez@colorado.edu>
1125 1143
1126 1144 * IPython/iplib.py (interact): Change the handling of %Exit from
1127 1145 trying to propagate a SystemExit to an internal ipython flag.
1128 1146 This is less elegant than using Python's exception mechanism, but
1129 1147 I can't get that to work reliably with threads, so under -pylab
1130 1148 %Exit was hanging IPython. Cross-thread exception handling is
1131 1149 really a bitch. Thaks to a bug report by Stephen Walton
1132 1150 <stephen.walton-AT-csun.edu>.
1133 1151
1134 1152 2004-11-04 Fernando Perez <fperez@colorado.edu>
1135 1153
1136 1154 * IPython/iplib.py (raw_input_original): store a pointer to the
1137 1155 true raw_input to harden against code which can modify it
1138 1156 (wx.py.PyShell does this and would otherwise crash ipython).
1139 1157 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1140 1158
1141 1159 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1142 1160 Ctrl-C problem, which does not mess up the input line.
1143 1161
1144 1162 2004-11-03 Fernando Perez <fperez@colorado.edu>
1145 1163
1146 1164 * IPython/Release.py: Changed licensing to BSD, in all files.
1147 1165 (name): lowercase name for tarball/RPM release.
1148 1166
1149 1167 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1150 1168 use throughout ipython.
1151 1169
1152 1170 * IPython/Magic.py (Magic._ofind): Switch to using the new
1153 1171 OInspect.getdoc() function.
1154 1172
1155 1173 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1156 1174 of the line currently being canceled via Ctrl-C. It's extremely
1157 1175 ugly, but I don't know how to do it better (the problem is one of
1158 1176 handling cross-thread exceptions).
1159 1177
1160 1178 2004-10-28 Fernando Perez <fperez@colorado.edu>
1161 1179
1162 1180 * IPython/Shell.py (signal_handler): add signal handlers to trap
1163 1181 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1164 1182 report by Francesc Alted.
1165 1183
1166 1184 2004-10-21 Fernando Perez <fperez@colorado.edu>
1167 1185
1168 1186 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1169 1187 to % for pysh syntax extensions.
1170 1188
1171 1189 2004-10-09 Fernando Perez <fperez@colorado.edu>
1172 1190
1173 1191 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1174 1192 arrays to print a more useful summary, without calling str(arr).
1175 1193 This avoids the problem of extremely lengthy computations which
1176 1194 occur if arr is large, and appear to the user as a system lockup
1177 1195 with 100% cpu activity. After a suggestion by Kristian Sandberg
1178 1196 <Kristian.Sandberg@colorado.edu>.
1179 1197 (Magic.__init__): fix bug in global magic escapes not being
1180 1198 correctly set.
1181 1199
1182 1200 2004-10-08 Fernando Perez <fperez@colorado.edu>
1183 1201
1184 1202 * IPython/Magic.py (__license__): change to absolute imports of
1185 1203 ipython's own internal packages, to start adapting to the absolute
1186 1204 import requirement of PEP-328.
1187 1205
1188 1206 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1189 1207 files, and standardize author/license marks through the Release
1190 1208 module instead of having per/file stuff (except for files with
1191 1209 particular licenses, like the MIT/PSF-licensed codes).
1192 1210
1193 1211 * IPython/Debugger.py: remove dead code for python 2.1
1194 1212
1195 1213 2004-10-04 Fernando Perez <fperez@colorado.edu>
1196 1214
1197 1215 * IPython/iplib.py (ipmagic): New function for accessing magics
1198 1216 via a normal python function call.
1199 1217
1200 1218 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1201 1219 from '@' to '%', to accomodate the new @decorator syntax of python
1202 1220 2.4.
1203 1221
1204 1222 2004-09-29 Fernando Perez <fperez@colorado.edu>
1205 1223
1206 1224 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1207 1225 matplotlib.use to prevent running scripts which try to switch
1208 1226 interactive backends from within ipython. This will just crash
1209 1227 the python interpreter, so we can't allow it (but a detailed error
1210 1228 is given to the user).
1211 1229
1212 1230 2004-09-28 Fernando Perez <fperez@colorado.edu>
1213 1231
1214 1232 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1215 1233 matplotlib-related fixes so that using @run with non-matplotlib
1216 1234 scripts doesn't pop up spurious plot windows. This requires
1217 1235 matplotlib >= 0.63, where I had to make some changes as well.
1218 1236
1219 1237 * IPython/ipmaker.py (make_IPython): update version requirement to
1220 1238 python 2.2.
1221 1239
1222 1240 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1223 1241 banner arg for embedded customization.
1224 1242
1225 1243 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1226 1244 explicit uses of __IP as the IPython's instance name. Now things
1227 1245 are properly handled via the shell.name value. The actual code
1228 1246 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1229 1247 is much better than before. I'll clean things completely when the
1230 1248 magic stuff gets a real overhaul.
1231 1249
1232 1250 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1233 1251 minor changes to debian dir.
1234 1252
1235 1253 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1236 1254 pointer to the shell itself in the interactive namespace even when
1237 1255 a user-supplied dict is provided. This is needed for embedding
1238 1256 purposes (found by tests with Michel Sanner).
1239 1257
1240 1258 2004-09-27 Fernando Perez <fperez@colorado.edu>
1241 1259
1242 1260 * IPython/UserConfig/ipythonrc: remove []{} from
1243 1261 readline_remove_delims, so that things like [modname.<TAB> do
1244 1262 proper completion. This disables [].TAB, but that's a less common
1245 1263 case than module names in list comprehensions, for example.
1246 1264 Thanks to a report by Andrea Riciputi.
1247 1265
1248 1266 2004-09-09 Fernando Perez <fperez@colorado.edu>
1249 1267
1250 1268 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1251 1269 blocking problems in win32 and osx. Fix by John.
1252 1270
1253 1271 2004-09-08 Fernando Perez <fperez@colorado.edu>
1254 1272
1255 1273 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1256 1274 for Win32 and OSX. Fix by John Hunter.
1257 1275
1258 1276 2004-08-30 *** Released version 0.6.3
1259 1277
1260 1278 2004-08-30 Fernando Perez <fperez@colorado.edu>
1261 1279
1262 1280 * setup.py (isfile): Add manpages to list of dependent files to be
1263 1281 updated.
1264 1282
1265 1283 2004-08-27 Fernando Perez <fperez@colorado.edu>
1266 1284
1267 1285 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1268 1286 for now. They don't really work with standalone WX/GTK code
1269 1287 (though matplotlib IS working fine with both of those backends).
1270 1288 This will neeed much more testing. I disabled most things with
1271 1289 comments, so turning it back on later should be pretty easy.
1272 1290
1273 1291 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1274 1292 autocalling of expressions like r'foo', by modifying the line
1275 1293 split regexp. Closes
1276 1294 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1277 1295 Riley <ipythonbugs-AT-sabi.net>.
1278 1296 (InteractiveShell.mainloop): honor --nobanner with banner
1279 1297 extensions.
1280 1298
1281 1299 * IPython/Shell.py: Significant refactoring of all classes, so
1282 1300 that we can really support ALL matplotlib backends and threading
1283 1301 models (John spotted a bug with Tk which required this). Now we
1284 1302 should support single-threaded, WX-threads and GTK-threads, both
1285 1303 for generic code and for matplotlib.
1286 1304
1287 1305 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1288 1306 -pylab, to simplify things for users. Will also remove the pylab
1289 1307 profile, since now all of matplotlib configuration is directly
1290 1308 handled here. This also reduces startup time.
1291 1309
1292 1310 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1293 1311 shell wasn't being correctly called. Also in IPShellWX.
1294 1312
1295 1313 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1296 1314 fine-tune banner.
1297 1315
1298 1316 * IPython/numutils.py (spike): Deprecate these spike functions,
1299 1317 delete (long deprecated) gnuplot_exec handler.
1300 1318
1301 1319 2004-08-26 Fernando Perez <fperez@colorado.edu>
1302 1320
1303 1321 * ipython.1: Update for threading options, plus some others which
1304 1322 were missing.
1305 1323
1306 1324 * IPython/ipmaker.py (__call__): Added -wthread option for
1307 1325 wxpython thread handling. Make sure threading options are only
1308 1326 valid at the command line.
1309 1327
1310 1328 * scripts/ipython: moved shell selection into a factory function
1311 1329 in Shell.py, to keep the starter script to a minimum.
1312 1330
1313 1331 2004-08-25 Fernando Perez <fperez@colorado.edu>
1314 1332
1315 1333 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1316 1334 John. Along with some recent changes he made to matplotlib, the
1317 1335 next versions of both systems should work very well together.
1318 1336
1319 1337 2004-08-24 Fernando Perez <fperez@colorado.edu>
1320 1338
1321 1339 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1322 1340 tried to switch the profiling to using hotshot, but I'm getting
1323 1341 strange errors from prof.runctx() there. I may be misreading the
1324 1342 docs, but it looks weird. For now the profiling code will
1325 1343 continue to use the standard profiler.
1326 1344
1327 1345 2004-08-23 Fernando Perez <fperez@colorado.edu>
1328 1346
1329 1347 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1330 1348 threaded shell, by John Hunter. It's not quite ready yet, but
1331 1349 close.
1332 1350
1333 1351 2004-08-22 Fernando Perez <fperez@colorado.edu>
1334 1352
1335 1353 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1336 1354 in Magic and ultraTB.
1337 1355
1338 1356 * ipython.1: document threading options in manpage.
1339 1357
1340 1358 * scripts/ipython: Changed name of -thread option to -gthread,
1341 1359 since this is GTK specific. I want to leave the door open for a
1342 1360 -wthread option for WX, which will most likely be necessary. This
1343 1361 change affects usage and ipmaker as well.
1344 1362
1345 1363 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1346 1364 handle the matplotlib shell issues. Code by John Hunter
1347 1365 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1348 1366 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1349 1367 broken (and disabled for end users) for now, but it puts the
1350 1368 infrastructure in place.
1351 1369
1352 1370 2004-08-21 Fernando Perez <fperez@colorado.edu>
1353 1371
1354 1372 * ipythonrc-pylab: Add matplotlib support.
1355 1373
1356 1374 * matplotlib_config.py: new files for matplotlib support, part of
1357 1375 the pylab profile.
1358 1376
1359 1377 * IPython/usage.py (__doc__): documented the threading options.
1360 1378
1361 1379 2004-08-20 Fernando Perez <fperez@colorado.edu>
1362 1380
1363 1381 * ipython: Modified the main calling routine to handle the -thread
1364 1382 and -mpthread options. This needs to be done as a top-level hack,
1365 1383 because it determines which class to instantiate for IPython
1366 1384 itself.
1367 1385
1368 1386 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1369 1387 classes to support multithreaded GTK operation without blocking,
1370 1388 and matplotlib with all backends. This is a lot of still very
1371 1389 experimental code, and threads are tricky. So it may still have a
1372 1390 few rough edges... This code owes a lot to
1373 1391 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1374 1392 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1375 1393 to John Hunter for all the matplotlib work.
1376 1394
1377 1395 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1378 1396 options for gtk thread and matplotlib support.
1379 1397
1380 1398 2004-08-16 Fernando Perez <fperez@colorado.edu>
1381 1399
1382 1400 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1383 1401 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1384 1402 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1385 1403
1386 1404 2004-08-11 Fernando Perez <fperez@colorado.edu>
1387 1405
1388 1406 * setup.py (isfile): Fix build so documentation gets updated for
1389 1407 rpms (it was only done for .tgz builds).
1390 1408
1391 1409 2004-08-10 Fernando Perez <fperez@colorado.edu>
1392 1410
1393 1411 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1394 1412
1395 1413 * iplib.py : Silence syntax error exceptions in tab-completion.
1396 1414
1397 1415 2004-08-05 Fernando Perez <fperez@colorado.edu>
1398 1416
1399 1417 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1400 1418 'color off' mark for continuation prompts. This was causing long
1401 1419 continuation lines to mis-wrap.
1402 1420
1403 1421 2004-08-01 Fernando Perez <fperez@colorado.edu>
1404 1422
1405 1423 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1406 1424 for building ipython to be a parameter. All this is necessary
1407 1425 right now to have a multithreaded version, but this insane
1408 1426 non-design will be cleaned up soon. For now, it's a hack that
1409 1427 works.
1410 1428
1411 1429 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1412 1430 args in various places. No bugs so far, but it's a dangerous
1413 1431 practice.
1414 1432
1415 1433 2004-07-31 Fernando Perez <fperez@colorado.edu>
1416 1434
1417 1435 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1418 1436 fix completion of files with dots in their names under most
1419 1437 profiles (pysh was OK because the completion order is different).
1420 1438
1421 1439 2004-07-27 Fernando Perez <fperez@colorado.edu>
1422 1440
1423 1441 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1424 1442 keywords manually, b/c the one in keyword.py was removed in python
1425 1443 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1426 1444 This is NOT a bug under python 2.3 and earlier.
1427 1445
1428 1446 2004-07-26 Fernando Perez <fperez@colorado.edu>
1429 1447
1430 1448 * IPython/ultraTB.py (VerboseTB.text): Add another
1431 1449 linecache.checkcache() call to try to prevent inspect.py from
1432 1450 crashing under python 2.3. I think this fixes
1433 1451 http://www.scipy.net/roundup/ipython/issue17.
1434 1452
1435 1453 2004-07-26 *** Released version 0.6.2
1436 1454
1437 1455 2004-07-26 Fernando Perez <fperez@colorado.edu>
1438 1456
1439 1457 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1440 1458 fail for any number.
1441 1459 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1442 1460 empty bookmarks.
1443 1461
1444 1462 2004-07-26 *** Released version 0.6.1
1445 1463
1446 1464 2004-07-26 Fernando Perez <fperez@colorado.edu>
1447 1465
1448 1466 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1449 1467
1450 1468 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1451 1469 escaping '()[]{}' in filenames.
1452 1470
1453 1471 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1454 1472 Python 2.2 users who lack a proper shlex.split.
1455 1473
1456 1474 2004-07-19 Fernando Perez <fperez@colorado.edu>
1457 1475
1458 1476 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1459 1477 for reading readline's init file. I follow the normal chain:
1460 1478 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1461 1479 report by Mike Heeter. This closes
1462 1480 http://www.scipy.net/roundup/ipython/issue16.
1463 1481
1464 1482 2004-07-18 Fernando Perez <fperez@colorado.edu>
1465 1483
1466 1484 * IPython/iplib.py (__init__): Add better handling of '\' under
1467 1485 Win32 for filenames. After a patch by Ville.
1468 1486
1469 1487 2004-07-17 Fernando Perez <fperez@colorado.edu>
1470 1488
1471 1489 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1472 1490 autocalling would be triggered for 'foo is bar' if foo is
1473 1491 callable. I also cleaned up the autocall detection code to use a
1474 1492 regexp, which is faster. Bug reported by Alexander Schmolck.
1475 1493
1476 1494 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1477 1495 '?' in them would confuse the help system. Reported by Alex
1478 1496 Schmolck.
1479 1497
1480 1498 2004-07-16 Fernando Perez <fperez@colorado.edu>
1481 1499
1482 1500 * IPython/GnuplotInteractive.py (__all__): added plot2.
1483 1501
1484 1502 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1485 1503 plotting dictionaries, lists or tuples of 1d arrays.
1486 1504
1487 1505 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1488 1506 optimizations.
1489 1507
1490 1508 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1491 1509 the information which was there from Janko's original IPP code:
1492 1510
1493 1511 03.05.99 20:53 porto.ifm.uni-kiel.de
1494 1512 --Started changelog.
1495 1513 --make clear do what it say it does
1496 1514 --added pretty output of lines from inputcache
1497 1515 --Made Logger a mixin class, simplifies handling of switches
1498 1516 --Added own completer class. .string<TAB> expands to last history
1499 1517 line which starts with string. The new expansion is also present
1500 1518 with Ctrl-r from the readline library. But this shows, who this
1501 1519 can be done for other cases.
1502 1520 --Added convention that all shell functions should accept a
1503 1521 parameter_string This opens the door for different behaviour for
1504 1522 each function. @cd is a good example of this.
1505 1523
1506 1524 04.05.99 12:12 porto.ifm.uni-kiel.de
1507 1525 --added logfile rotation
1508 1526 --added new mainloop method which freezes first the namespace
1509 1527
1510 1528 07.05.99 21:24 porto.ifm.uni-kiel.de
1511 1529 --added the docreader classes. Now there is a help system.
1512 1530 -This is only a first try. Currently it's not easy to put new
1513 1531 stuff in the indices. But this is the way to go. Info would be
1514 1532 better, but HTML is every where and not everybody has an info
1515 1533 system installed and it's not so easy to change html-docs to info.
1516 1534 --added global logfile option
1517 1535 --there is now a hook for object inspection method pinfo needs to
1518 1536 be provided for this. Can be reached by two '??'.
1519 1537
1520 1538 08.05.99 20:51 porto.ifm.uni-kiel.de
1521 1539 --added a README
1522 1540 --bug in rc file. Something has changed so functions in the rc
1523 1541 file need to reference the shell and not self. Not clear if it's a
1524 1542 bug or feature.
1525 1543 --changed rc file for new behavior
1526 1544
1527 1545 2004-07-15 Fernando Perez <fperez@colorado.edu>
1528 1546
1529 1547 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1530 1548 cache was falling out of sync in bizarre manners when multi-line
1531 1549 input was present. Minor optimizations and cleanup.
1532 1550
1533 1551 (Logger): Remove old Changelog info for cleanup. This is the
1534 1552 information which was there from Janko's original code:
1535 1553
1536 1554 Changes to Logger: - made the default log filename a parameter
1537 1555
1538 1556 - put a check for lines beginning with !@? in log(). Needed
1539 1557 (even if the handlers properly log their lines) for mid-session
1540 1558 logging activation to work properly. Without this, lines logged
1541 1559 in mid session, which get read from the cache, would end up
1542 1560 'bare' (with !@? in the open) in the log. Now they are caught
1543 1561 and prepended with a #.
1544 1562
1545 1563 * IPython/iplib.py (InteractiveShell.init_readline): added check
1546 1564 in case MagicCompleter fails to be defined, so we don't crash.
1547 1565
1548 1566 2004-07-13 Fernando Perez <fperez@colorado.edu>
1549 1567
1550 1568 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1551 1569 of EPS if the requested filename ends in '.eps'.
1552 1570
1553 1571 2004-07-04 Fernando Perez <fperez@colorado.edu>
1554 1572
1555 1573 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1556 1574 escaping of quotes when calling the shell.
1557 1575
1558 1576 2004-07-02 Fernando Perez <fperez@colorado.edu>
1559 1577
1560 1578 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1561 1579 gettext not working because we were clobbering '_'. Fixes
1562 1580 http://www.scipy.net/roundup/ipython/issue6.
1563 1581
1564 1582 2004-07-01 Fernando Perez <fperez@colorado.edu>
1565 1583
1566 1584 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1567 1585 into @cd. Patch by Ville.
1568 1586
1569 1587 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1570 1588 new function to store things after ipmaker runs. Patch by Ville.
1571 1589 Eventually this will go away once ipmaker is removed and the class
1572 1590 gets cleaned up, but for now it's ok. Key functionality here is
1573 1591 the addition of the persistent storage mechanism, a dict for
1574 1592 keeping data across sessions (for now just bookmarks, but more can
1575 1593 be implemented later).
1576 1594
1577 1595 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1578 1596 persistent across sections. Patch by Ville, I modified it
1579 1597 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1580 1598 added a '-l' option to list all bookmarks.
1581 1599
1582 1600 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1583 1601 center for cleanup. Registered with atexit.register(). I moved
1584 1602 here the old exit_cleanup(). After a patch by Ville.
1585 1603
1586 1604 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1587 1605 characters in the hacked shlex_split for python 2.2.
1588 1606
1589 1607 * IPython/iplib.py (file_matches): more fixes to filenames with
1590 1608 whitespace in them. It's not perfect, but limitations in python's
1591 1609 readline make it impossible to go further.
1592 1610
1593 1611 2004-06-29 Fernando Perez <fperez@colorado.edu>
1594 1612
1595 1613 * IPython/iplib.py (file_matches): escape whitespace correctly in
1596 1614 filename completions. Bug reported by Ville.
1597 1615
1598 1616 2004-06-28 Fernando Perez <fperez@colorado.edu>
1599 1617
1600 1618 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1601 1619 the history file will be called 'history-PROFNAME' (or just
1602 1620 'history' if no profile is loaded). I was getting annoyed at
1603 1621 getting my Numerical work history clobbered by pysh sessions.
1604 1622
1605 1623 * IPython/iplib.py (InteractiveShell.__init__): Internal
1606 1624 getoutputerror() function so that we can honor the system_verbose
1607 1625 flag for _all_ system calls. I also added escaping of #
1608 1626 characters here to avoid confusing Itpl.
1609 1627
1610 1628 * IPython/Magic.py (shlex_split): removed call to shell in
1611 1629 parse_options and replaced it with shlex.split(). The annoying
1612 1630 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1613 1631 to backport it from 2.3, with several frail hacks (the shlex
1614 1632 module is rather limited in 2.2). Thanks to a suggestion by Ville
1615 1633 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1616 1634 problem.
1617 1635
1618 1636 (Magic.magic_system_verbose): new toggle to print the actual
1619 1637 system calls made by ipython. Mainly for debugging purposes.
1620 1638
1621 1639 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1622 1640 doesn't support persistence. Reported (and fix suggested) by
1623 1641 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1624 1642
1625 1643 2004-06-26 Fernando Perez <fperez@colorado.edu>
1626 1644
1627 1645 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1628 1646 continue prompts.
1629 1647
1630 1648 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1631 1649 function (basically a big docstring) and a few more things here to
1632 1650 speedup startup. pysh.py is now very lightweight. We want because
1633 1651 it gets execfile'd, while InterpreterExec gets imported, so
1634 1652 byte-compilation saves time.
1635 1653
1636 1654 2004-06-25 Fernando Perez <fperez@colorado.edu>
1637 1655
1638 1656 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1639 1657 -NUM', which was recently broken.
1640 1658
1641 1659 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1642 1660 in multi-line input (but not !!, which doesn't make sense there).
1643 1661
1644 1662 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1645 1663 It's just too useful, and people can turn it off in the less
1646 1664 common cases where it's a problem.
1647 1665
1648 1666 2004-06-24 Fernando Perez <fperez@colorado.edu>
1649 1667
1650 1668 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1651 1669 special syntaxes (like alias calling) is now allied in multi-line
1652 1670 input. This is still _very_ experimental, but it's necessary for
1653 1671 efficient shell usage combining python looping syntax with system
1654 1672 calls. For now it's restricted to aliases, I don't think it
1655 1673 really even makes sense to have this for magics.
1656 1674
1657 1675 2004-06-23 Fernando Perez <fperez@colorado.edu>
1658 1676
1659 1677 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1660 1678 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1661 1679
1662 1680 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1663 1681 extensions under Windows (after code sent by Gary Bishop). The
1664 1682 extensions considered 'executable' are stored in IPython's rc
1665 1683 structure as win_exec_ext.
1666 1684
1667 1685 * IPython/genutils.py (shell): new function, like system() but
1668 1686 without return value. Very useful for interactive shell work.
1669 1687
1670 1688 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1671 1689 delete aliases.
1672 1690
1673 1691 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1674 1692 sure that the alias table doesn't contain python keywords.
1675 1693
1676 1694 2004-06-21 Fernando Perez <fperez@colorado.edu>
1677 1695
1678 1696 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1679 1697 non-existent items are found in $PATH. Reported by Thorsten.
1680 1698
1681 1699 2004-06-20 Fernando Perez <fperez@colorado.edu>
1682 1700
1683 1701 * IPython/iplib.py (complete): modified the completer so that the
1684 1702 order of priorities can be easily changed at runtime.
1685 1703
1686 1704 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1687 1705 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1688 1706
1689 1707 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1690 1708 expand Python variables prepended with $ in all system calls. The
1691 1709 same was done to InteractiveShell.handle_shell_escape. Now all
1692 1710 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1693 1711 expansion of python variables and expressions according to the
1694 1712 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1695 1713
1696 1714 Though PEP-215 has been rejected, a similar (but simpler) one
1697 1715 seems like it will go into Python 2.4, PEP-292 -
1698 1716 http://www.python.org/peps/pep-0292.html.
1699 1717
1700 1718 I'll keep the full syntax of PEP-215, since IPython has since the
1701 1719 start used Ka-Ping Yee's reference implementation discussed there
1702 1720 (Itpl), and I actually like the powerful semantics it offers.
1703 1721
1704 1722 In order to access normal shell variables, the $ has to be escaped
1705 1723 via an extra $. For example:
1706 1724
1707 1725 In [7]: PATH='a python variable'
1708 1726
1709 1727 In [8]: !echo $PATH
1710 1728 a python variable
1711 1729
1712 1730 In [9]: !echo $$PATH
1713 1731 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1714 1732
1715 1733 (Magic.parse_options): escape $ so the shell doesn't evaluate
1716 1734 things prematurely.
1717 1735
1718 1736 * IPython/iplib.py (InteractiveShell.call_alias): added the
1719 1737 ability for aliases to expand python variables via $.
1720 1738
1721 1739 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1722 1740 system, now there's a @rehash/@rehashx pair of magics. These work
1723 1741 like the csh rehash command, and can be invoked at any time. They
1724 1742 build a table of aliases to everything in the user's $PATH
1725 1743 (@rehash uses everything, @rehashx is slower but only adds
1726 1744 executable files). With this, the pysh.py-based shell profile can
1727 1745 now simply call rehash upon startup, and full access to all
1728 1746 programs in the user's path is obtained.
1729 1747
1730 1748 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1731 1749 functionality is now fully in place. I removed the old dynamic
1732 1750 code generation based approach, in favor of a much lighter one
1733 1751 based on a simple dict. The advantage is that this allows me to
1734 1752 now have thousands of aliases with negligible cost (unthinkable
1735 1753 with the old system).
1736 1754
1737 1755 2004-06-19 Fernando Perez <fperez@colorado.edu>
1738 1756
1739 1757 * IPython/iplib.py (__init__): extended MagicCompleter class to
1740 1758 also complete (last in priority) on user aliases.
1741 1759
1742 1760 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1743 1761 call to eval.
1744 1762 (ItplNS.__init__): Added a new class which functions like Itpl,
1745 1763 but allows configuring the namespace for the evaluation to occur
1746 1764 in.
1747 1765
1748 1766 2004-06-18 Fernando Perez <fperez@colorado.edu>
1749 1767
1750 1768 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1751 1769 better message when 'exit' or 'quit' are typed (a common newbie
1752 1770 confusion).
1753 1771
1754 1772 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1755 1773 check for Windows users.
1756 1774
1757 1775 * IPython/iplib.py (InteractiveShell.user_setup): removed
1758 1776 disabling of colors for Windows. I'll test at runtime and issue a
1759 1777 warning if Gary's readline isn't found, as to nudge users to
1760 1778 download it.
1761 1779
1762 1780 2004-06-16 Fernando Perez <fperez@colorado.edu>
1763 1781
1764 1782 * IPython/genutils.py (Stream.__init__): changed to print errors
1765 1783 to sys.stderr. I had a circular dependency here. Now it's
1766 1784 possible to run ipython as IDLE's shell (consider this pre-alpha,
1767 1785 since true stdout things end up in the starting terminal instead
1768 1786 of IDLE's out).
1769 1787
1770 1788 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1771 1789 users who haven't # updated their prompt_in2 definitions. Remove
1772 1790 eventually.
1773 1791 (multiple_replace): added credit to original ASPN recipe.
1774 1792
1775 1793 2004-06-15 Fernando Perez <fperez@colorado.edu>
1776 1794
1777 1795 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1778 1796 list of auto-defined aliases.
1779 1797
1780 1798 2004-06-13 Fernando Perez <fperez@colorado.edu>
1781 1799
1782 1800 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1783 1801 install was really requested (so setup.py can be used for other
1784 1802 things under Windows).
1785 1803
1786 1804 2004-06-10 Fernando Perez <fperez@colorado.edu>
1787 1805
1788 1806 * IPython/Logger.py (Logger.create_log): Manually remove any old
1789 1807 backup, since os.remove may fail under Windows. Fixes bug
1790 1808 reported by Thorsten.
1791 1809
1792 1810 2004-06-09 Fernando Perez <fperez@colorado.edu>
1793 1811
1794 1812 * examples/example-embed.py: fixed all references to %n (replaced
1795 1813 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1796 1814 for all examples and the manual as well.
1797 1815
1798 1816 2004-06-08 Fernando Perez <fperez@colorado.edu>
1799 1817
1800 1818 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1801 1819 alignment and color management. All 3 prompt subsystems now
1802 1820 inherit from BasePrompt.
1803 1821
1804 1822 * tools/release: updates for windows installer build and tag rpms
1805 1823 with python version (since paths are fixed).
1806 1824
1807 1825 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1808 1826 which will become eventually obsolete. Also fixed the default
1809 1827 prompt_in2 to use \D, so at least new users start with the correct
1810 1828 defaults.
1811 1829 WARNING: Users with existing ipythonrc files will need to apply
1812 1830 this fix manually!
1813 1831
1814 1832 * setup.py: make windows installer (.exe). This is finally the
1815 1833 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1816 1834 which I hadn't included because it required Python 2.3 (or recent
1817 1835 distutils).
1818 1836
1819 1837 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1820 1838 usage of new '\D' escape.
1821 1839
1822 1840 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1823 1841 lacks os.getuid())
1824 1842 (CachedOutput.set_colors): Added the ability to turn coloring
1825 1843 on/off with @colors even for manually defined prompt colors. It
1826 1844 uses a nasty global, but it works safely and via the generic color
1827 1845 handling mechanism.
1828 1846 (Prompt2.__init__): Introduced new escape '\D' for continuation
1829 1847 prompts. It represents the counter ('\#') as dots.
1830 1848 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1831 1849 need to update their ipythonrc files and replace '%n' with '\D' in
1832 1850 their prompt_in2 settings everywhere. Sorry, but there's
1833 1851 otherwise no clean way to get all prompts to properly align. The
1834 1852 ipythonrc shipped with IPython has been updated.
1835 1853
1836 1854 2004-06-07 Fernando Perez <fperez@colorado.edu>
1837 1855
1838 1856 * setup.py (isfile): Pass local_icons option to latex2html, so the
1839 1857 resulting HTML file is self-contained. Thanks to
1840 1858 dryice-AT-liu.com.cn for the tip.
1841 1859
1842 1860 * pysh.py: I created a new profile 'shell', which implements a
1843 1861 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1844 1862 system shell, nor will it become one anytime soon. It's mainly
1845 1863 meant to illustrate the use of the new flexible bash-like prompts.
1846 1864 I guess it could be used by hardy souls for true shell management,
1847 1865 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1848 1866 profile. This uses the InterpreterExec extension provided by
1849 1867 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1850 1868
1851 1869 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1852 1870 auto-align itself with the length of the previous input prompt
1853 1871 (taking into account the invisible color escapes).
1854 1872 (CachedOutput.__init__): Large restructuring of this class. Now
1855 1873 all three prompts (primary1, primary2, output) are proper objects,
1856 1874 managed by the 'parent' CachedOutput class. The code is still a
1857 1875 bit hackish (all prompts share state via a pointer to the cache),
1858 1876 but it's overall far cleaner than before.
1859 1877
1860 1878 * IPython/genutils.py (getoutputerror): modified to add verbose,
1861 1879 debug and header options. This makes the interface of all getout*
1862 1880 functions uniform.
1863 1881 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1864 1882
1865 1883 * IPython/Magic.py (Magic.default_option): added a function to
1866 1884 allow registering default options for any magic command. This
1867 1885 makes it easy to have profiles which customize the magics globally
1868 1886 for a certain use. The values set through this function are
1869 1887 picked up by the parse_options() method, which all magics should
1870 1888 use to parse their options.
1871 1889
1872 1890 * IPython/genutils.py (warn): modified the warnings framework to
1873 1891 use the Term I/O class. I'm trying to slowly unify all of
1874 1892 IPython's I/O operations to pass through Term.
1875 1893
1876 1894 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1877 1895 the secondary prompt to correctly match the length of the primary
1878 1896 one for any prompt. Now multi-line code will properly line up
1879 1897 even for path dependent prompts, such as the new ones available
1880 1898 via the prompt_specials.
1881 1899
1882 1900 2004-06-06 Fernando Perez <fperez@colorado.edu>
1883 1901
1884 1902 * IPython/Prompts.py (prompt_specials): Added the ability to have
1885 1903 bash-like special sequences in the prompts, which get
1886 1904 automatically expanded. Things like hostname, current working
1887 1905 directory and username are implemented already, but it's easy to
1888 1906 add more in the future. Thanks to a patch by W.J. van der Laan
1889 1907 <gnufnork-AT-hetdigitalegat.nl>
1890 1908 (prompt_specials): Added color support for prompt strings, so
1891 1909 users can define arbitrary color setups for their prompts.
1892 1910
1893 1911 2004-06-05 Fernando Perez <fperez@colorado.edu>
1894 1912
1895 1913 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1896 1914 code to load Gary Bishop's readline and configure it
1897 1915 automatically. Thanks to Gary for help on this.
1898 1916
1899 1917 2004-06-01 Fernando Perez <fperez@colorado.edu>
1900 1918
1901 1919 * IPython/Logger.py (Logger.create_log): fix bug for logging
1902 1920 with no filename (previous fix was incomplete).
1903 1921
1904 1922 2004-05-25 Fernando Perez <fperez@colorado.edu>
1905 1923
1906 1924 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1907 1925 parens would get passed to the shell.
1908 1926
1909 1927 2004-05-20 Fernando Perez <fperez@colorado.edu>
1910 1928
1911 1929 * IPython/Magic.py (Magic.magic_prun): changed default profile
1912 1930 sort order to 'time' (the more common profiling need).
1913 1931
1914 1932 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1915 1933 so that source code shown is guaranteed in sync with the file on
1916 1934 disk (also changed in psource). Similar fix to the one for
1917 1935 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1918 1936 <yann.ledu-AT-noos.fr>.
1919 1937
1920 1938 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1921 1939 with a single option would not be correctly parsed. Closes
1922 1940 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1923 1941 introduced in 0.6.0 (on 2004-05-06).
1924 1942
1925 1943 2004-05-13 *** Released version 0.6.0
1926 1944
1927 1945 2004-05-13 Fernando Perez <fperez@colorado.edu>
1928 1946
1929 1947 * debian/: Added debian/ directory to CVS, so that debian support
1930 1948 is publicly accessible. The debian package is maintained by Jack
1931 1949 Moffit <jack-AT-xiph.org>.
1932 1950
1933 1951 * Documentation: included the notes about an ipython-based system
1934 1952 shell (the hypothetical 'pysh') into the new_design.pdf document,
1935 1953 so that these ideas get distributed to users along with the
1936 1954 official documentation.
1937 1955
1938 1956 2004-05-10 Fernando Perez <fperez@colorado.edu>
1939 1957
1940 1958 * IPython/Logger.py (Logger.create_log): fix recently introduced
1941 1959 bug (misindented line) where logstart would fail when not given an
1942 1960 explicit filename.
1943 1961
1944 1962 2004-05-09 Fernando Perez <fperez@colorado.edu>
1945 1963
1946 1964 * IPython/Magic.py (Magic.parse_options): skip system call when
1947 1965 there are no options to look for. Faster, cleaner for the common
1948 1966 case.
1949 1967
1950 1968 * Documentation: many updates to the manual: describing Windows
1951 1969 support better, Gnuplot updates, credits, misc small stuff. Also
1952 1970 updated the new_design doc a bit.
1953 1971
1954 1972 2004-05-06 *** Released version 0.6.0.rc1
1955 1973
1956 1974 2004-05-06 Fernando Perez <fperez@colorado.edu>
1957 1975
1958 1976 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1959 1977 operations to use the vastly more efficient list/''.join() method.
1960 1978 (FormattedTB.text): Fix
1961 1979 http://www.scipy.net/roundup/ipython/issue12 - exception source
1962 1980 extract not updated after reload. Thanks to Mike Salib
1963 1981 <msalib-AT-mit.edu> for pinning the source of the problem.
1964 1982 Fortunately, the solution works inside ipython and doesn't require
1965 1983 any changes to python proper.
1966 1984
1967 1985 * IPython/Magic.py (Magic.parse_options): Improved to process the
1968 1986 argument list as a true shell would (by actually using the
1969 1987 underlying system shell). This way, all @magics automatically get
1970 1988 shell expansion for variables. Thanks to a comment by Alex
1971 1989 Schmolck.
1972 1990
1973 1991 2004-04-04 Fernando Perez <fperez@colorado.edu>
1974 1992
1975 1993 * IPython/iplib.py (InteractiveShell.interact): Added a special
1976 1994 trap for a debugger quit exception, which is basically impossible
1977 1995 to handle by normal mechanisms, given what pdb does to the stack.
1978 1996 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1979 1997
1980 1998 2004-04-03 Fernando Perez <fperez@colorado.edu>
1981 1999
1982 2000 * IPython/genutils.py (Term): Standardized the names of the Term
1983 2001 class streams to cin/cout/cerr, following C++ naming conventions
1984 2002 (I can't use in/out/err because 'in' is not a valid attribute
1985 2003 name).
1986 2004
1987 2005 * IPython/iplib.py (InteractiveShell.interact): don't increment
1988 2006 the prompt if there's no user input. By Daniel 'Dang' Griffith
1989 2007 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
1990 2008 Francois Pinard.
1991 2009
1992 2010 2004-04-02 Fernando Perez <fperez@colorado.edu>
1993 2011
1994 2012 * IPython/genutils.py (Stream.__init__): Modified to survive at
1995 2013 least importing in contexts where stdin/out/err aren't true file
1996 2014 objects, such as PyCrust (they lack fileno() and mode). However,
1997 2015 the recovery facilities which rely on these things existing will
1998 2016 not work.
1999 2017
2000 2018 2004-04-01 Fernando Perez <fperez@colorado.edu>
2001 2019
2002 2020 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2003 2021 use the new getoutputerror() function, so it properly
2004 2022 distinguishes stdout/err.
2005 2023
2006 2024 * IPython/genutils.py (getoutputerror): added a function to
2007 2025 capture separately the standard output and error of a command.
2008 2026 After a comment from dang on the mailing lists. This code is
2009 2027 basically a modified version of commands.getstatusoutput(), from
2010 2028 the standard library.
2011 2029
2012 2030 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2013 2031 '!!' as a special syntax (shorthand) to access @sx.
2014 2032
2015 2033 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2016 2034 command and return its output as a list split on '\n'.
2017 2035
2018 2036 2004-03-31 Fernando Perez <fperez@colorado.edu>
2019 2037
2020 2038 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2021 2039 method to dictionaries used as FakeModule instances if they lack
2022 2040 it. At least pydoc in python2.3 breaks for runtime-defined
2023 2041 functions without this hack. At some point I need to _really_
2024 2042 understand what FakeModule is doing, because it's a gross hack.
2025 2043 But it solves Arnd's problem for now...
2026 2044
2027 2045 2004-02-27 Fernando Perez <fperez@colorado.edu>
2028 2046
2029 2047 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2030 2048 mode would behave erratically. Also increased the number of
2031 2049 possible logs in rotate mod to 999. Thanks to Rod Holland
2032 2050 <rhh@StructureLABS.com> for the report and fixes.
2033 2051
2034 2052 2004-02-26 Fernando Perez <fperez@colorado.edu>
2035 2053
2036 2054 * IPython/genutils.py (page): Check that the curses module really
2037 2055 has the initscr attribute before trying to use it. For some
2038 2056 reason, the Solaris curses module is missing this. I think this
2039 2057 should be considered a Solaris python bug, but I'm not sure.
2040 2058
2041 2059 2004-01-17 Fernando Perez <fperez@colorado.edu>
2042 2060
2043 2061 * IPython/genutils.py (Stream.__init__): Changes to try to make
2044 2062 ipython robust against stdin/out/err being closed by the user.
2045 2063 This is 'user error' (and blocks a normal python session, at least
2046 2064 the stdout case). However, Ipython should be able to survive such
2047 2065 instances of abuse as gracefully as possible. To simplify the
2048 2066 coding and maintain compatibility with Gary Bishop's Term
2049 2067 contributions, I've made use of classmethods for this. I think
2050 2068 this introduces a dependency on python 2.2.
2051 2069
2052 2070 2004-01-13 Fernando Perez <fperez@colorado.edu>
2053 2071
2054 2072 * IPython/numutils.py (exp_safe): simplified the code a bit and
2055 2073 removed the need for importing the kinds module altogether.
2056 2074
2057 2075 2004-01-06 Fernando Perez <fperez@colorado.edu>
2058 2076
2059 2077 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2060 2078 a magic function instead, after some community feedback. No
2061 2079 special syntax will exist for it, but its name is deliberately
2062 2080 very short.
2063 2081
2064 2082 2003-12-20 Fernando Perez <fperez@colorado.edu>
2065 2083
2066 2084 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2067 2085 new functionality, to automagically assign the result of a shell
2068 2086 command to a variable. I'll solicit some community feedback on
2069 2087 this before making it permanent.
2070 2088
2071 2089 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2072 2090 requested about callables for which inspect couldn't obtain a
2073 2091 proper argspec. Thanks to a crash report sent by Etienne
2074 2092 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2075 2093
2076 2094 2003-12-09 Fernando Perez <fperez@colorado.edu>
2077 2095
2078 2096 * IPython/genutils.py (page): patch for the pager to work across
2079 2097 various versions of Windows. By Gary Bishop.
2080 2098
2081 2099 2003-12-04 Fernando Perez <fperez@colorado.edu>
2082 2100
2083 2101 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2084 2102 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2085 2103 While I tested this and it looks ok, there may still be corner
2086 2104 cases I've missed.
2087 2105
2088 2106 2003-12-01 Fernando Perez <fperez@colorado.edu>
2089 2107
2090 2108 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2091 2109 where a line like 'p,q=1,2' would fail because the automagic
2092 2110 system would be triggered for @p.
2093 2111
2094 2112 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2095 2113 cleanups, code unmodified.
2096 2114
2097 2115 * IPython/genutils.py (Term): added a class for IPython to handle
2098 2116 output. In most cases it will just be a proxy for stdout/err, but
2099 2117 having this allows modifications to be made for some platforms,
2100 2118 such as handling color escapes under Windows. All of this code
2101 2119 was contributed by Gary Bishop, with minor modifications by me.
2102 2120 The actual changes affect many files.
2103 2121
2104 2122 2003-11-30 Fernando Perez <fperez@colorado.edu>
2105 2123
2106 2124 * IPython/iplib.py (file_matches): new completion code, courtesy
2107 2125 of Jeff Collins. This enables filename completion again under
2108 2126 python 2.3, which disabled it at the C level.
2109 2127
2110 2128 2003-11-11 Fernando Perez <fperez@colorado.edu>
2111 2129
2112 2130 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2113 2131 for Numeric.array(map(...)), but often convenient.
2114 2132
2115 2133 2003-11-05 Fernando Perez <fperez@colorado.edu>
2116 2134
2117 2135 * IPython/numutils.py (frange): Changed a call from int() to
2118 2136 int(round()) to prevent a problem reported with arange() in the
2119 2137 numpy list.
2120 2138
2121 2139 2003-10-06 Fernando Perez <fperez@colorado.edu>
2122 2140
2123 2141 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2124 2142 prevent crashes if sys lacks an argv attribute (it happens with
2125 2143 embedded interpreters which build a bare-bones sys module).
2126 2144 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2127 2145
2128 2146 2003-09-24 Fernando Perez <fperez@colorado.edu>
2129 2147
2130 2148 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2131 2149 to protect against poorly written user objects where __getattr__
2132 2150 raises exceptions other than AttributeError. Thanks to a bug
2133 2151 report by Oliver Sander <osander-AT-gmx.de>.
2134 2152
2135 2153 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2136 2154 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2137 2155
2138 2156 2003-09-09 Fernando Perez <fperez@colorado.edu>
2139 2157
2140 2158 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2141 2159 unpacking a list whith a callable as first element would
2142 2160 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2143 2161 Collins.
2144 2162
2145 2163 2003-08-25 *** Released version 0.5.0
2146 2164
2147 2165 2003-08-22 Fernando Perez <fperez@colorado.edu>
2148 2166
2149 2167 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2150 2168 improperly defined user exceptions. Thanks to feedback from Mark
2151 2169 Russell <mrussell-AT-verio.net>.
2152 2170
2153 2171 2003-08-20 Fernando Perez <fperez@colorado.edu>
2154 2172
2155 2173 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2156 2174 printing so that it would print multi-line string forms starting
2157 2175 with a new line. This way the formatting is better respected for
2158 2176 objects which work hard to make nice string forms.
2159 2177
2160 2178 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2161 2179 autocall would overtake data access for objects with both
2162 2180 __getitem__ and __call__.
2163 2181
2164 2182 2003-08-19 *** Released version 0.5.0-rc1
2165 2183
2166 2184 2003-08-19 Fernando Perez <fperez@colorado.edu>
2167 2185
2168 2186 * IPython/deep_reload.py (load_tail): single tiny change here
2169 2187 seems to fix the long-standing bug of dreload() failing to work
2170 2188 for dotted names. But this module is pretty tricky, so I may have
2171 2189 missed some subtlety. Needs more testing!.
2172 2190
2173 2191 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2174 2192 exceptions which have badly implemented __str__ methods.
2175 2193 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2176 2194 which I've been getting reports about from Python 2.3 users. I
2177 2195 wish I had a simple test case to reproduce the problem, so I could
2178 2196 either write a cleaner workaround or file a bug report if
2179 2197 necessary.
2180 2198
2181 2199 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2182 2200 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2183 2201 a bug report by Tjabo Kloppenburg.
2184 2202
2185 2203 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2186 2204 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2187 2205 seems rather unstable. Thanks to a bug report by Tjabo
2188 2206 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2189 2207
2190 2208 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2191 2209 this out soon because of the critical fixes in the inner loop for
2192 2210 generators.
2193 2211
2194 2212 * IPython/Magic.py (Magic.getargspec): removed. This (and
2195 2213 _get_def) have been obsoleted by OInspect for a long time, I
2196 2214 hadn't noticed that they were dead code.
2197 2215 (Magic._ofind): restored _ofind functionality for a few literals
2198 2216 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2199 2217 for things like "hello".capitalize?, since that would require a
2200 2218 potentially dangerous eval() again.
2201 2219
2202 2220 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2203 2221 logic a bit more to clean up the escapes handling and minimize the
2204 2222 use of _ofind to only necessary cases. The interactive 'feel' of
2205 2223 IPython should have improved quite a bit with the changes in
2206 2224 _prefilter and _ofind (besides being far safer than before).
2207 2225
2208 2226 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2209 2227 obscure, never reported). Edit would fail to find the object to
2210 2228 edit under some circumstances.
2211 2229 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2212 2230 which were causing double-calling of generators. Those eval calls
2213 2231 were _very_ dangerous, since code with side effects could be
2214 2232 triggered. As they say, 'eval is evil'... These were the
2215 2233 nastiest evals in IPython. Besides, _ofind is now far simpler,
2216 2234 and it should also be quite a bit faster. Its use of inspect is
2217 2235 also safer, so perhaps some of the inspect-related crashes I've
2218 2236 seen lately with Python 2.3 might be taken care of. That will
2219 2237 need more testing.
2220 2238
2221 2239 2003-08-17 Fernando Perez <fperez@colorado.edu>
2222 2240
2223 2241 * IPython/iplib.py (InteractiveShell._prefilter): significant
2224 2242 simplifications to the logic for handling user escapes. Faster
2225 2243 and simpler code.
2226 2244
2227 2245 2003-08-14 Fernando Perez <fperez@colorado.edu>
2228 2246
2229 2247 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2230 2248 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2231 2249 but it should be quite a bit faster. And the recursive version
2232 2250 generated O(log N) intermediate storage for all rank>1 arrays,
2233 2251 even if they were contiguous.
2234 2252 (l1norm): Added this function.
2235 2253 (norm): Added this function for arbitrary norms (including
2236 2254 l-infinity). l1 and l2 are still special cases for convenience
2237 2255 and speed.
2238 2256
2239 2257 2003-08-03 Fernando Perez <fperez@colorado.edu>
2240 2258
2241 2259 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2242 2260 exceptions, which now raise PendingDeprecationWarnings in Python
2243 2261 2.3. There were some in Magic and some in Gnuplot2.
2244 2262
2245 2263 2003-06-30 Fernando Perez <fperez@colorado.edu>
2246 2264
2247 2265 * IPython/genutils.py (page): modified to call curses only for
2248 2266 terminals where TERM=='xterm'. After problems under many other
2249 2267 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2250 2268
2251 2269 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2252 2270 would be triggered when readline was absent. This was just an old
2253 2271 debugging statement I'd forgotten to take out.
2254 2272
2255 2273 2003-06-20 Fernando Perez <fperez@colorado.edu>
2256 2274
2257 2275 * IPython/genutils.py (clock): modified to return only user time
2258 2276 (not counting system time), after a discussion on scipy. While
2259 2277 system time may be a useful quantity occasionally, it may much
2260 2278 more easily be skewed by occasional swapping or other similar
2261 2279 activity.
2262 2280
2263 2281 2003-06-05 Fernando Perez <fperez@colorado.edu>
2264 2282
2265 2283 * IPython/numutils.py (identity): new function, for building
2266 2284 arbitrary rank Kronecker deltas (mostly backwards compatible with
2267 2285 Numeric.identity)
2268 2286
2269 2287 2003-06-03 Fernando Perez <fperez@colorado.edu>
2270 2288
2271 2289 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2272 2290 arguments passed to magics with spaces, to allow trailing '\' to
2273 2291 work normally (mainly for Windows users).
2274 2292
2275 2293 2003-05-29 Fernando Perez <fperez@colorado.edu>
2276 2294
2277 2295 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2278 2296 instead of pydoc.help. This fixes a bizarre behavior where
2279 2297 printing '%s' % locals() would trigger the help system. Now
2280 2298 ipython behaves like normal python does.
2281 2299
2282 2300 Note that if one does 'from pydoc import help', the bizarre
2283 2301 behavior returns, but this will also happen in normal python, so
2284 2302 it's not an ipython bug anymore (it has to do with how pydoc.help
2285 2303 is implemented).
2286 2304
2287 2305 2003-05-22 Fernando Perez <fperez@colorado.edu>
2288 2306
2289 2307 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2290 2308 return [] instead of None when nothing matches, also match to end
2291 2309 of line. Patch by Gary Bishop.
2292 2310
2293 2311 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2294 2312 protection as before, for files passed on the command line. This
2295 2313 prevents the CrashHandler from kicking in if user files call into
2296 2314 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2297 2315 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2298 2316
2299 2317 2003-05-20 *** Released version 0.4.0
2300 2318
2301 2319 2003-05-20 Fernando Perez <fperez@colorado.edu>
2302 2320
2303 2321 * setup.py: added support for manpages. It's a bit hackish b/c of
2304 2322 a bug in the way the bdist_rpm distutils target handles gzipped
2305 2323 manpages, but it works. After a patch by Jack.
2306 2324
2307 2325 2003-05-19 Fernando Perez <fperez@colorado.edu>
2308 2326
2309 2327 * IPython/numutils.py: added a mockup of the kinds module, since
2310 2328 it was recently removed from Numeric. This way, numutils will
2311 2329 work for all users even if they are missing kinds.
2312 2330
2313 2331 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2314 2332 failure, which can occur with SWIG-wrapped extensions. After a
2315 2333 crash report from Prabhu.
2316 2334
2317 2335 2003-05-16 Fernando Perez <fperez@colorado.edu>
2318 2336
2319 2337 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2320 2338 protect ipython from user code which may call directly
2321 2339 sys.excepthook (this looks like an ipython crash to the user, even
2322 2340 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2323 2341 This is especially important to help users of WxWindows, but may
2324 2342 also be useful in other cases.
2325 2343
2326 2344 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2327 2345 an optional tb_offset to be specified, and to preserve exception
2328 2346 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2329 2347
2330 2348 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2331 2349
2332 2350 2003-05-15 Fernando Perez <fperez@colorado.edu>
2333 2351
2334 2352 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2335 2353 installing for a new user under Windows.
2336 2354
2337 2355 2003-05-12 Fernando Perez <fperez@colorado.edu>
2338 2356
2339 2357 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2340 2358 handler for Emacs comint-based lines. Currently it doesn't do
2341 2359 much (but importantly, it doesn't update the history cache). In
2342 2360 the future it may be expanded if Alex needs more functionality
2343 2361 there.
2344 2362
2345 2363 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2346 2364 info to crash reports.
2347 2365
2348 2366 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2349 2367 just like Python's -c. Also fixed crash with invalid -color
2350 2368 option value at startup. Thanks to Will French
2351 2369 <wfrench-AT-bestweb.net> for the bug report.
2352 2370
2353 2371 2003-05-09 Fernando Perez <fperez@colorado.edu>
2354 2372
2355 2373 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2356 2374 to EvalDict (it's a mapping, after all) and simplified its code
2357 2375 quite a bit, after a nice discussion on c.l.py where Gustavo
2358 2376 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2359 2377
2360 2378 2003-04-30 Fernando Perez <fperez@colorado.edu>
2361 2379
2362 2380 * IPython/genutils.py (timings_out): modified it to reduce its
2363 2381 overhead in the common reps==1 case.
2364 2382
2365 2383 2003-04-29 Fernando Perez <fperez@colorado.edu>
2366 2384
2367 2385 * IPython/genutils.py (timings_out): Modified to use the resource
2368 2386 module, which avoids the wraparound problems of time.clock().
2369 2387
2370 2388 2003-04-17 *** Released version 0.2.15pre4
2371 2389
2372 2390 2003-04-17 Fernando Perez <fperez@colorado.edu>
2373 2391
2374 2392 * setup.py (scriptfiles): Split windows-specific stuff over to a
2375 2393 separate file, in an attempt to have a Windows GUI installer.
2376 2394 That didn't work, but part of the groundwork is done.
2377 2395
2378 2396 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2379 2397 indent/unindent with 4 spaces. Particularly useful in combination
2380 2398 with the new auto-indent option.
2381 2399
2382 2400 2003-04-16 Fernando Perez <fperez@colorado.edu>
2383 2401
2384 2402 * IPython/Magic.py: various replacements of self.rc for
2385 2403 self.shell.rc. A lot more remains to be done to fully disentangle
2386 2404 this class from the main Shell class.
2387 2405
2388 2406 * IPython/GnuplotRuntime.py: added checks for mouse support so
2389 2407 that we don't try to enable it if the current gnuplot doesn't
2390 2408 really support it. Also added checks so that we don't try to
2391 2409 enable persist under Windows (where Gnuplot doesn't recognize the
2392 2410 option).
2393 2411
2394 2412 * IPython/iplib.py (InteractiveShell.interact): Added optional
2395 2413 auto-indenting code, after a patch by King C. Shu
2396 2414 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2397 2415 get along well with pasting indented code. If I ever figure out
2398 2416 how to make that part go well, it will become on by default.
2399 2417
2400 2418 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2401 2419 crash ipython if there was an unmatched '%' in the user's prompt
2402 2420 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2403 2421
2404 2422 * IPython/iplib.py (InteractiveShell.interact): removed the
2405 2423 ability to ask the user whether he wants to crash or not at the
2406 2424 'last line' exception handler. Calling functions at that point
2407 2425 changes the stack, and the error reports would have incorrect
2408 2426 tracebacks.
2409 2427
2410 2428 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2411 2429 pass through a peger a pretty-printed form of any object. After a
2412 2430 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2413 2431
2414 2432 2003-04-14 Fernando Perez <fperez@colorado.edu>
2415 2433
2416 2434 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2417 2435 all files in ~ would be modified at first install (instead of
2418 2436 ~/.ipython). This could be potentially disastrous, as the
2419 2437 modification (make line-endings native) could damage binary files.
2420 2438
2421 2439 2003-04-10 Fernando Perez <fperez@colorado.edu>
2422 2440
2423 2441 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2424 2442 handle only lines which are invalid python. This now means that
2425 2443 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2426 2444 for the bug report.
2427 2445
2428 2446 2003-04-01 Fernando Perez <fperez@colorado.edu>
2429 2447
2430 2448 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2431 2449 where failing to set sys.last_traceback would crash pdb.pm().
2432 2450 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2433 2451 report.
2434 2452
2435 2453 2003-03-25 Fernando Perez <fperez@colorado.edu>
2436 2454
2437 2455 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2438 2456 before printing it (it had a lot of spurious blank lines at the
2439 2457 end).
2440 2458
2441 2459 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2442 2460 output would be sent 21 times! Obviously people don't use this
2443 2461 too often, or I would have heard about it.
2444 2462
2445 2463 2003-03-24 Fernando Perez <fperez@colorado.edu>
2446 2464
2447 2465 * setup.py (scriptfiles): renamed the data_files parameter from
2448 2466 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2449 2467 for the patch.
2450 2468
2451 2469 2003-03-20 Fernando Perez <fperez@colorado.edu>
2452 2470
2453 2471 * IPython/genutils.py (error): added error() and fatal()
2454 2472 functions.
2455 2473
2456 2474 2003-03-18 *** Released version 0.2.15pre3
2457 2475
2458 2476 2003-03-18 Fernando Perez <fperez@colorado.edu>
2459 2477
2460 2478 * setupext/install_data_ext.py
2461 2479 (install_data_ext.initialize_options): Class contributed by Jack
2462 2480 Moffit for fixing the old distutils hack. He is sending this to
2463 2481 the distutils folks so in the future we may not need it as a
2464 2482 private fix.
2465 2483
2466 2484 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2467 2485 changes for Debian packaging. See his patch for full details.
2468 2486 The old distutils hack of making the ipythonrc* files carry a
2469 2487 bogus .py extension is gone, at last. Examples were moved to a
2470 2488 separate subdir under doc/, and the separate executable scripts
2471 2489 now live in their own directory. Overall a great cleanup. The
2472 2490 manual was updated to use the new files, and setup.py has been
2473 2491 fixed for this setup.
2474 2492
2475 2493 * IPython/PyColorize.py (Parser.usage): made non-executable and
2476 2494 created a pycolor wrapper around it to be included as a script.
2477 2495
2478 2496 2003-03-12 *** Released version 0.2.15pre2
2479 2497
2480 2498 2003-03-12 Fernando Perez <fperez@colorado.edu>
2481 2499
2482 2500 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2483 2501 long-standing problem with garbage characters in some terminals.
2484 2502 The issue was really that the \001 and \002 escapes must _only_ be
2485 2503 passed to input prompts (which call readline), but _never_ to
2486 2504 normal text to be printed on screen. I changed ColorANSI to have
2487 2505 two classes: TermColors and InputTermColors, each with the
2488 2506 appropriate escapes for input prompts or normal text. The code in
2489 2507 Prompts.py got slightly more complicated, but this very old and
2490 2508 annoying bug is finally fixed.
2491 2509
2492 2510 All the credit for nailing down the real origin of this problem
2493 2511 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2494 2512 *Many* thanks to him for spending quite a bit of effort on this.
2495 2513
2496 2514 2003-03-05 *** Released version 0.2.15pre1
2497 2515
2498 2516 2003-03-03 Fernando Perez <fperez@colorado.edu>
2499 2517
2500 2518 * IPython/FakeModule.py: Moved the former _FakeModule to a
2501 2519 separate file, because it's also needed by Magic (to fix a similar
2502 2520 pickle-related issue in @run).
2503 2521
2504 2522 2003-03-02 Fernando Perez <fperez@colorado.edu>
2505 2523
2506 2524 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2507 2525 the autocall option at runtime.
2508 2526 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2509 2527 across Magic.py to start separating Magic from InteractiveShell.
2510 2528 (Magic._ofind): Fixed to return proper namespace for dotted
2511 2529 names. Before, a dotted name would always return 'not currently
2512 2530 defined', because it would find the 'parent'. s.x would be found,
2513 2531 but since 'x' isn't defined by itself, it would get confused.
2514 2532 (Magic.magic_run): Fixed pickling problems reported by Ralf
2515 2533 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2516 2534 that I'd used when Mike Heeter reported similar issues at the
2517 2535 top-level, but now for @run. It boils down to injecting the
2518 2536 namespace where code is being executed with something that looks
2519 2537 enough like a module to fool pickle.dump(). Since a pickle stores
2520 2538 a named reference to the importing module, we need this for
2521 2539 pickles to save something sensible.
2522 2540
2523 2541 * IPython/ipmaker.py (make_IPython): added an autocall option.
2524 2542
2525 2543 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2526 2544 the auto-eval code. Now autocalling is an option, and the code is
2527 2545 also vastly safer. There is no more eval() involved at all.
2528 2546
2529 2547 2003-03-01 Fernando Perez <fperez@colorado.edu>
2530 2548
2531 2549 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2532 2550 dict with named keys instead of a tuple.
2533 2551
2534 2552 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2535 2553
2536 2554 * setup.py (make_shortcut): Fixed message about directories
2537 2555 created during Windows installation (the directories were ok, just
2538 2556 the printed message was misleading). Thanks to Chris Liechti
2539 2557 <cliechti-AT-gmx.net> for the heads up.
2540 2558
2541 2559 2003-02-21 Fernando Perez <fperez@colorado.edu>
2542 2560
2543 2561 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2544 2562 of ValueError exception when checking for auto-execution. This
2545 2563 one is raised by things like Numeric arrays arr.flat when the
2546 2564 array is non-contiguous.
2547 2565
2548 2566 2003-01-31 Fernando Perez <fperez@colorado.edu>
2549 2567
2550 2568 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2551 2569 not return any value at all (even though the command would get
2552 2570 executed).
2553 2571 (xsys): Flush stdout right after printing the command to ensure
2554 2572 proper ordering of commands and command output in the total
2555 2573 output.
2556 2574 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2557 2575 system/getoutput as defaults. The old ones are kept for
2558 2576 compatibility reasons, so no code which uses this library needs
2559 2577 changing.
2560 2578
2561 2579 2003-01-27 *** Released version 0.2.14
2562 2580
2563 2581 2003-01-25 Fernando Perez <fperez@colorado.edu>
2564 2582
2565 2583 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2566 2584 functions defined in previous edit sessions could not be re-edited
2567 2585 (because the temp files were immediately removed). Now temp files
2568 2586 are removed only at IPython's exit.
2569 2587 (Magic.magic_run): Improved @run to perform shell-like expansions
2570 2588 on its arguments (~users and $VARS). With this, @run becomes more
2571 2589 like a normal command-line.
2572 2590
2573 2591 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2574 2592 bugs related to embedding and cleaned up that code. A fairly
2575 2593 important one was the impossibility to access the global namespace
2576 2594 through the embedded IPython (only local variables were visible).
2577 2595
2578 2596 2003-01-14 Fernando Perez <fperez@colorado.edu>
2579 2597
2580 2598 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2581 2599 auto-calling to be a bit more conservative. Now it doesn't get
2582 2600 triggered if any of '!=()<>' are in the rest of the input line, to
2583 2601 allow comparing callables. Thanks to Alex for the heads up.
2584 2602
2585 2603 2003-01-07 Fernando Perez <fperez@colorado.edu>
2586 2604
2587 2605 * IPython/genutils.py (page): fixed estimation of the number of
2588 2606 lines in a string to be paged to simply count newlines. This
2589 2607 prevents over-guessing due to embedded escape sequences. A better
2590 2608 long-term solution would involve stripping out the control chars
2591 2609 for the count, but it's potentially so expensive I just don't
2592 2610 think it's worth doing.
2593 2611
2594 2612 2002-12-19 *** Released version 0.2.14pre50
2595 2613
2596 2614 2002-12-19 Fernando Perez <fperez@colorado.edu>
2597 2615
2598 2616 * tools/release (version): Changed release scripts to inform
2599 2617 Andrea and build a NEWS file with a list of recent changes.
2600 2618
2601 2619 * IPython/ColorANSI.py (__all__): changed terminal detection
2602 2620 code. Seems to work better for xterms without breaking
2603 2621 konsole. Will need more testing to determine if WinXP and Mac OSX
2604 2622 also work ok.
2605 2623
2606 2624 2002-12-18 *** Released version 0.2.14pre49
2607 2625
2608 2626 2002-12-18 Fernando Perez <fperez@colorado.edu>
2609 2627
2610 2628 * Docs: added new info about Mac OSX, from Andrea.
2611 2629
2612 2630 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2613 2631 allow direct plotting of python strings whose format is the same
2614 2632 of gnuplot data files.
2615 2633
2616 2634 2002-12-16 Fernando Perez <fperez@colorado.edu>
2617 2635
2618 2636 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2619 2637 value of exit question to be acknowledged.
2620 2638
2621 2639 2002-12-03 Fernando Perez <fperez@colorado.edu>
2622 2640
2623 2641 * IPython/ipmaker.py: removed generators, which had been added
2624 2642 by mistake in an earlier debugging run. This was causing trouble
2625 2643 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2626 2644 for pointing this out.
2627 2645
2628 2646 2002-11-17 Fernando Perez <fperez@colorado.edu>
2629 2647
2630 2648 * Manual: updated the Gnuplot section.
2631 2649
2632 2650 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2633 2651 a much better split of what goes in Runtime and what goes in
2634 2652 Interactive.
2635 2653
2636 2654 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2637 2655 being imported from iplib.
2638 2656
2639 2657 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2640 2658 for command-passing. Now the global Gnuplot instance is called
2641 2659 'gp' instead of 'g', which was really a far too fragile and
2642 2660 common name.
2643 2661
2644 2662 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2645 2663 bounding boxes generated by Gnuplot for square plots.
2646 2664
2647 2665 * IPython/genutils.py (popkey): new function added. I should
2648 2666 suggest this on c.l.py as a dict method, it seems useful.
2649 2667
2650 2668 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2651 2669 to transparently handle PostScript generation. MUCH better than
2652 2670 the previous plot_eps/replot_eps (which I removed now). The code
2653 2671 is also fairly clean and well documented now (including
2654 2672 docstrings).
2655 2673
2656 2674 2002-11-13 Fernando Perez <fperez@colorado.edu>
2657 2675
2658 2676 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2659 2677 (inconsistent with options).
2660 2678
2661 2679 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2662 2680 manually disabled, I don't know why. Fixed it.
2663 2681 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2664 2682 eps output.
2665 2683
2666 2684 2002-11-12 Fernando Perez <fperez@colorado.edu>
2667 2685
2668 2686 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2669 2687 don't propagate up to caller. Fixes crash reported by François
2670 2688 Pinard.
2671 2689
2672 2690 2002-11-09 Fernando Perez <fperez@colorado.edu>
2673 2691
2674 2692 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2675 2693 history file for new users.
2676 2694 (make_IPython): fixed bug where initial install would leave the
2677 2695 user running in the .ipython dir.
2678 2696 (make_IPython): fixed bug where config dir .ipython would be
2679 2697 created regardless of the given -ipythondir option. Thanks to Cory
2680 2698 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2681 2699
2682 2700 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2683 2701 type confirmations. Will need to use it in all of IPython's code
2684 2702 consistently.
2685 2703
2686 2704 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2687 2705 context to print 31 lines instead of the default 5. This will make
2688 2706 the crash reports extremely detailed in case the problem is in
2689 2707 libraries I don't have access to.
2690 2708
2691 2709 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2692 2710 line of defense' code to still crash, but giving users fair
2693 2711 warning. I don't want internal errors to go unreported: if there's
2694 2712 an internal problem, IPython should crash and generate a full
2695 2713 report.
2696 2714
2697 2715 2002-11-08 Fernando Perez <fperez@colorado.edu>
2698 2716
2699 2717 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2700 2718 otherwise uncaught exceptions which can appear if people set
2701 2719 sys.stdout to something badly broken. Thanks to a crash report
2702 2720 from henni-AT-mail.brainbot.com.
2703 2721
2704 2722 2002-11-04 Fernando Perez <fperez@colorado.edu>
2705 2723
2706 2724 * IPython/iplib.py (InteractiveShell.interact): added
2707 2725 __IPYTHON__active to the builtins. It's a flag which goes on when
2708 2726 the interaction starts and goes off again when it stops. This
2709 2727 allows embedding code to detect being inside IPython. Before this
2710 2728 was done via __IPYTHON__, but that only shows that an IPython
2711 2729 instance has been created.
2712 2730
2713 2731 * IPython/Magic.py (Magic.magic_env): I realized that in a
2714 2732 UserDict, instance.data holds the data as a normal dict. So I
2715 2733 modified @env to return os.environ.data instead of rebuilding a
2716 2734 dict by hand.
2717 2735
2718 2736 2002-11-02 Fernando Perez <fperez@colorado.edu>
2719 2737
2720 2738 * IPython/genutils.py (warn): changed so that level 1 prints no
2721 2739 header. Level 2 is now the default (with 'WARNING' header, as
2722 2740 before). I think I tracked all places where changes were needed in
2723 2741 IPython, but outside code using the old level numbering may have
2724 2742 broken.
2725 2743
2726 2744 * IPython/iplib.py (InteractiveShell.runcode): added this to
2727 2745 handle the tracebacks in SystemExit traps correctly. The previous
2728 2746 code (through interact) was printing more of the stack than
2729 2747 necessary, showing IPython internal code to the user.
2730 2748
2731 2749 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2732 2750 default. Now that the default at the confirmation prompt is yes,
2733 2751 it's not so intrusive. François' argument that ipython sessions
2734 2752 tend to be complex enough not to lose them from an accidental C-d,
2735 2753 is a valid one.
2736 2754
2737 2755 * IPython/iplib.py (InteractiveShell.interact): added a
2738 2756 showtraceback() call to the SystemExit trap, and modified the exit
2739 2757 confirmation to have yes as the default.
2740 2758
2741 2759 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2742 2760 this file. It's been gone from the code for a long time, this was
2743 2761 simply leftover junk.
2744 2762
2745 2763 2002-11-01 Fernando Perez <fperez@colorado.edu>
2746 2764
2747 2765 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2748 2766 added. If set, IPython now traps EOF and asks for
2749 2767 confirmation. After a request by François Pinard.
2750 2768
2751 2769 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2752 2770 of @abort, and with a new (better) mechanism for handling the
2753 2771 exceptions.
2754 2772
2755 2773 2002-10-27 Fernando Perez <fperez@colorado.edu>
2756 2774
2757 2775 * IPython/usage.py (__doc__): updated the --help information and
2758 2776 the ipythonrc file to indicate that -log generates
2759 2777 ./ipython.log. Also fixed the corresponding info in @logstart.
2760 2778 This and several other fixes in the manuals thanks to reports by
2761 2779 François Pinard <pinard-AT-iro.umontreal.ca>.
2762 2780
2763 2781 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2764 2782 refer to @logstart (instead of @log, which doesn't exist).
2765 2783
2766 2784 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2767 2785 AttributeError crash. Thanks to Christopher Armstrong
2768 2786 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2769 2787 introduced recently (in 0.2.14pre37) with the fix to the eval
2770 2788 problem mentioned below.
2771 2789
2772 2790 2002-10-17 Fernando Perez <fperez@colorado.edu>
2773 2791
2774 2792 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2775 2793 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2776 2794
2777 2795 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2778 2796 this function to fix a problem reported by Alex Schmolck. He saw
2779 2797 it with list comprehensions and generators, which were getting
2780 2798 called twice. The real problem was an 'eval' call in testing for
2781 2799 automagic which was evaluating the input line silently.
2782 2800
2783 2801 This is a potentially very nasty bug, if the input has side
2784 2802 effects which must not be repeated. The code is much cleaner now,
2785 2803 without any blanket 'except' left and with a regexp test for
2786 2804 actual function names.
2787 2805
2788 2806 But an eval remains, which I'm not fully comfortable with. I just
2789 2807 don't know how to find out if an expression could be a callable in
2790 2808 the user's namespace without doing an eval on the string. However
2791 2809 that string is now much more strictly checked so that no code
2792 2810 slips by, so the eval should only happen for things that can
2793 2811 really be only function/method names.
2794 2812
2795 2813 2002-10-15 Fernando Perez <fperez@colorado.edu>
2796 2814
2797 2815 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2798 2816 OSX information to main manual, removed README_Mac_OSX file from
2799 2817 distribution. Also updated credits for recent additions.
2800 2818
2801 2819 2002-10-10 Fernando Perez <fperez@colorado.edu>
2802 2820
2803 2821 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2804 2822 terminal-related issues. Many thanks to Andrea Riciputi
2805 2823 <andrea.riciputi-AT-libero.it> for writing it.
2806 2824
2807 2825 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2808 2826 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2809 2827
2810 2828 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2811 2829 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2812 2830 <syver-en-AT-online.no> who both submitted patches for this problem.
2813 2831
2814 2832 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2815 2833 global embedding to make sure that things don't overwrite user
2816 2834 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2817 2835
2818 2836 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2819 2837 compatibility. Thanks to Hayden Callow
2820 2838 <h.callow-AT-elec.canterbury.ac.nz>
2821 2839
2822 2840 2002-10-04 Fernando Perez <fperez@colorado.edu>
2823 2841
2824 2842 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2825 2843 Gnuplot.File objects.
2826 2844
2827 2845 2002-07-23 Fernando Perez <fperez@colorado.edu>
2828 2846
2829 2847 * IPython/genutils.py (timing): Added timings() and timing() for
2830 2848 quick access to the most commonly needed data, the execution
2831 2849 times. Old timing() renamed to timings_out().
2832 2850
2833 2851 2002-07-18 Fernando Perez <fperez@colorado.edu>
2834 2852
2835 2853 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2836 2854 bug with nested instances disrupting the parent's tab completion.
2837 2855
2838 2856 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2839 2857 all_completions code to begin the emacs integration.
2840 2858
2841 2859 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2842 2860 argument to allow titling individual arrays when plotting.
2843 2861
2844 2862 2002-07-15 Fernando Perez <fperez@colorado.edu>
2845 2863
2846 2864 * setup.py (make_shortcut): changed to retrieve the value of
2847 2865 'Program Files' directory from the registry (this value changes in
2848 2866 non-english versions of Windows). Thanks to Thomas Fanslau
2849 2867 <tfanslau-AT-gmx.de> for the report.
2850 2868
2851 2869 2002-07-10 Fernando Perez <fperez@colorado.edu>
2852 2870
2853 2871 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2854 2872 a bug in pdb, which crashes if a line with only whitespace is
2855 2873 entered. Bug report submitted to sourceforge.
2856 2874
2857 2875 2002-07-09 Fernando Perez <fperez@colorado.edu>
2858 2876
2859 2877 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2860 2878 reporting exceptions (it's a bug in inspect.py, I just set a
2861 2879 workaround).
2862 2880
2863 2881 2002-07-08 Fernando Perez <fperez@colorado.edu>
2864 2882
2865 2883 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2866 2884 __IPYTHON__ in __builtins__ to show up in user_ns.
2867 2885
2868 2886 2002-07-03 Fernando Perez <fperez@colorado.edu>
2869 2887
2870 2888 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2871 2889 name from @gp_set_instance to @gp_set_default.
2872 2890
2873 2891 * IPython/ipmaker.py (make_IPython): default editor value set to
2874 2892 '0' (a string), to match the rc file. Otherwise will crash when
2875 2893 .strip() is called on it.
2876 2894
2877 2895
2878 2896 2002-06-28 Fernando Perez <fperez@colorado.edu>
2879 2897
2880 2898 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2881 2899 of files in current directory when a file is executed via
2882 2900 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2883 2901
2884 2902 * setup.py (manfiles): fix for rpm builds, submitted by RA
2885 2903 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2886 2904
2887 2905 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2888 2906 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2889 2907 string!). A. Schmolck caught this one.
2890 2908
2891 2909 2002-06-27 Fernando Perez <fperez@colorado.edu>
2892 2910
2893 2911 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2894 2912 defined files at the cmd line. __name__ wasn't being set to
2895 2913 __main__.
2896 2914
2897 2915 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2898 2916 regular lists and tuples besides Numeric arrays.
2899 2917
2900 2918 * IPython/Prompts.py (CachedOutput.__call__): Added output
2901 2919 supression for input ending with ';'. Similar to Mathematica and
2902 2920 Matlab. The _* vars and Out[] list are still updated, just like
2903 2921 Mathematica behaves.
2904 2922
2905 2923 2002-06-25 Fernando Perez <fperez@colorado.edu>
2906 2924
2907 2925 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2908 2926 .ini extensions for profiels under Windows.
2909 2927
2910 2928 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2911 2929 string form. Fix contributed by Alexander Schmolck
2912 2930 <a.schmolck-AT-gmx.net>
2913 2931
2914 2932 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2915 2933 pre-configured Gnuplot instance.
2916 2934
2917 2935 2002-06-21 Fernando Perez <fperez@colorado.edu>
2918 2936
2919 2937 * IPython/numutils.py (exp_safe): new function, works around the
2920 2938 underflow problems in Numeric.
2921 2939 (log2): New fn. Safe log in base 2: returns exact integer answer
2922 2940 for exact integer powers of 2.
2923 2941
2924 2942 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2925 2943 properly.
2926 2944
2927 2945 2002-06-20 Fernando Perez <fperez@colorado.edu>
2928 2946
2929 2947 * IPython/genutils.py (timing): new function like
2930 2948 Mathematica's. Similar to time_test, but returns more info.
2931 2949
2932 2950 2002-06-18 Fernando Perez <fperez@colorado.edu>
2933 2951
2934 2952 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2935 2953 according to Mike Heeter's suggestions.
2936 2954
2937 2955 2002-06-16 Fernando Perez <fperez@colorado.edu>
2938 2956
2939 2957 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2940 2958 system. GnuplotMagic is gone as a user-directory option. New files
2941 2959 make it easier to use all the gnuplot stuff both from external
2942 2960 programs as well as from IPython. Had to rewrite part of
2943 2961 hardcopy() b/c of a strange bug: often the ps files simply don't
2944 2962 get created, and require a repeat of the command (often several
2945 2963 times).
2946 2964
2947 2965 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2948 2966 resolve output channel at call time, so that if sys.stderr has
2949 2967 been redirected by user this gets honored.
2950 2968
2951 2969 2002-06-13 Fernando Perez <fperez@colorado.edu>
2952 2970
2953 2971 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2954 2972 IPShell. Kept a copy with the old names to avoid breaking people's
2955 2973 embedded code.
2956 2974
2957 2975 * IPython/ipython: simplified it to the bare minimum after
2958 2976 Holger's suggestions. Added info about how to use it in
2959 2977 PYTHONSTARTUP.
2960 2978
2961 2979 * IPython/Shell.py (IPythonShell): changed the options passing
2962 2980 from a string with funky %s replacements to a straight list. Maybe
2963 2981 a bit more typing, but it follows sys.argv conventions, so there's
2964 2982 less special-casing to remember.
2965 2983
2966 2984 2002-06-12 Fernando Perez <fperez@colorado.edu>
2967 2985
2968 2986 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2969 2987 command. Thanks to a suggestion by Mike Heeter.
2970 2988 (Magic.magic_pfile): added behavior to look at filenames if given
2971 2989 arg is not a defined object.
2972 2990 (Magic.magic_save): New @save function to save code snippets. Also
2973 2991 a Mike Heeter idea.
2974 2992
2975 2993 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2976 2994 plot() and replot(). Much more convenient now, especially for
2977 2995 interactive use.
2978 2996
2979 2997 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2980 2998 filenames.
2981 2999
2982 3000 2002-06-02 Fernando Perez <fperez@colorado.edu>
2983 3001
2984 3002 * IPython/Struct.py (Struct.__init__): modified to admit
2985 3003 initialization via another struct.
2986 3004
2987 3005 * IPython/genutils.py (SystemExec.__init__): New stateful
2988 3006 interface to xsys and bq. Useful for writing system scripts.
2989 3007
2990 3008 2002-05-30 Fernando Perez <fperez@colorado.edu>
2991 3009
2992 3010 * MANIFEST.in: Changed docfile selection to exclude all the lyx
2993 3011 documents. This will make the user download smaller (it's getting
2994 3012 too big).
2995 3013
2996 3014 2002-05-29 Fernando Perez <fperez@colorado.edu>
2997 3015
2998 3016 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
2999 3017 fix problems with shelve and pickle. Seems to work, but I don't
3000 3018 know if corner cases break it. Thanks to Mike Heeter
3001 3019 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3002 3020
3003 3021 2002-05-24 Fernando Perez <fperez@colorado.edu>
3004 3022
3005 3023 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3006 3024 macros having broken.
3007 3025
3008 3026 2002-05-21 Fernando Perez <fperez@colorado.edu>
3009 3027
3010 3028 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3011 3029 introduced logging bug: all history before logging started was
3012 3030 being written one character per line! This came from the redesign
3013 3031 of the input history as a special list which slices to strings,
3014 3032 not to lists.
3015 3033
3016 3034 2002-05-20 Fernando Perez <fperez@colorado.edu>
3017 3035
3018 3036 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3019 3037 be an attribute of all classes in this module. The design of these
3020 3038 classes needs some serious overhauling.
3021 3039
3022 3040 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3023 3041 which was ignoring '_' in option names.
3024 3042
3025 3043 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3026 3044 'Verbose_novars' to 'Context' and made it the new default. It's a
3027 3045 bit more readable and also safer than verbose.
3028 3046
3029 3047 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3030 3048 triple-quoted strings.
3031 3049
3032 3050 * IPython/OInspect.py (__all__): new module exposing the object
3033 3051 introspection facilities. Now the corresponding magics are dummy
3034 3052 wrappers around this. Having this module will make it much easier
3035 3053 to put these functions into our modified pdb.
3036 3054 This new object inspector system uses the new colorizing module,
3037 3055 so source code and other things are nicely syntax highlighted.
3038 3056
3039 3057 2002-05-18 Fernando Perez <fperez@colorado.edu>
3040 3058
3041 3059 * IPython/ColorANSI.py: Split the coloring tools into a separate
3042 3060 module so I can use them in other code easier (they were part of
3043 3061 ultraTB).
3044 3062
3045 3063 2002-05-17 Fernando Perez <fperez@colorado.edu>
3046 3064
3047 3065 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3048 3066 fixed it to set the global 'g' also to the called instance, as
3049 3067 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3050 3068 user's 'g' variables).
3051 3069
3052 3070 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3053 3071 global variables (aliases to _ih,_oh) so that users which expect
3054 3072 In[5] or Out[7] to work aren't unpleasantly surprised.
3055 3073 (InputList.__getslice__): new class to allow executing slices of
3056 3074 input history directly. Very simple class, complements the use of
3057 3075 macros.
3058 3076
3059 3077 2002-05-16 Fernando Perez <fperez@colorado.edu>
3060 3078
3061 3079 * setup.py (docdirbase): make doc directory be just doc/IPython
3062 3080 without version numbers, it will reduce clutter for users.
3063 3081
3064 3082 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3065 3083 execfile call to prevent possible memory leak. See for details:
3066 3084 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3067 3085
3068 3086 2002-05-15 Fernando Perez <fperez@colorado.edu>
3069 3087
3070 3088 * IPython/Magic.py (Magic.magic_psource): made the object
3071 3089 introspection names be more standard: pdoc, pdef, pfile and
3072 3090 psource. They all print/page their output, and it makes
3073 3091 remembering them easier. Kept old names for compatibility as
3074 3092 aliases.
3075 3093
3076 3094 2002-05-14 Fernando Perez <fperez@colorado.edu>
3077 3095
3078 3096 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3079 3097 what the mouse problem was. The trick is to use gnuplot with temp
3080 3098 files and NOT with pipes (for data communication), because having
3081 3099 both pipes and the mouse on is bad news.
3082 3100
3083 3101 2002-05-13 Fernando Perez <fperez@colorado.edu>
3084 3102
3085 3103 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3086 3104 bug. Information would be reported about builtins even when
3087 3105 user-defined functions overrode them.
3088 3106
3089 3107 2002-05-11 Fernando Perez <fperez@colorado.edu>
3090 3108
3091 3109 * IPython/__init__.py (__all__): removed FlexCompleter from
3092 3110 __all__ so that things don't fail in platforms without readline.
3093 3111
3094 3112 2002-05-10 Fernando Perez <fperez@colorado.edu>
3095 3113
3096 3114 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3097 3115 it requires Numeric, effectively making Numeric a dependency for
3098 3116 IPython.
3099 3117
3100 3118 * Released 0.2.13
3101 3119
3102 3120 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3103 3121 profiler interface. Now all the major options from the profiler
3104 3122 module are directly supported in IPython, both for single
3105 3123 expressions (@prun) and for full programs (@run -p).
3106 3124
3107 3125 2002-05-09 Fernando Perez <fperez@colorado.edu>
3108 3126
3109 3127 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3110 3128 magic properly formatted for screen.
3111 3129
3112 3130 * setup.py (make_shortcut): Changed things to put pdf version in
3113 3131 doc/ instead of doc/manual (had to change lyxport a bit).
3114 3132
3115 3133 * IPython/Magic.py (Profile.string_stats): made profile runs go
3116 3134 through pager (they are long and a pager allows searching, saving,
3117 3135 etc.)
3118 3136
3119 3137 2002-05-08 Fernando Perez <fperez@colorado.edu>
3120 3138
3121 3139 * Released 0.2.12
3122 3140
3123 3141 2002-05-06 Fernando Perez <fperez@colorado.edu>
3124 3142
3125 3143 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3126 3144 introduced); 'hist n1 n2' was broken.
3127 3145 (Magic.magic_pdb): added optional on/off arguments to @pdb
3128 3146 (Magic.magic_run): added option -i to @run, which executes code in
3129 3147 the IPython namespace instead of a clean one. Also added @irun as
3130 3148 an alias to @run -i.
3131 3149
3132 3150 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3133 3151 fixed (it didn't really do anything, the namespaces were wrong).
3134 3152
3135 3153 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3136 3154
3137 3155 * IPython/__init__.py (__all__): Fixed package namespace, now
3138 3156 'import IPython' does give access to IPython.<all> as
3139 3157 expected. Also renamed __release__ to Release.
3140 3158
3141 3159 * IPython/Debugger.py (__license__): created new Pdb class which
3142 3160 functions like a drop-in for the normal pdb.Pdb but does NOT
3143 3161 import readline by default. This way it doesn't muck up IPython's
3144 3162 readline handling, and now tab-completion finally works in the
3145 3163 debugger -- sort of. It completes things globally visible, but the
3146 3164 completer doesn't track the stack as pdb walks it. That's a bit
3147 3165 tricky, and I'll have to implement it later.
3148 3166
3149 3167 2002-05-05 Fernando Perez <fperez@colorado.edu>
3150 3168
3151 3169 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3152 3170 magic docstrings when printed via ? (explicit \'s were being
3153 3171 printed).
3154 3172
3155 3173 * IPython/ipmaker.py (make_IPython): fixed namespace
3156 3174 identification bug. Now variables loaded via logs or command-line
3157 3175 files are recognized in the interactive namespace by @who.
3158 3176
3159 3177 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3160 3178 log replay system stemming from the string form of Structs.
3161 3179
3162 3180 * IPython/Magic.py (Macro.__init__): improved macros to properly
3163 3181 handle magic commands in them.
3164 3182 (Magic.magic_logstart): usernames are now expanded so 'logstart
3165 3183 ~/mylog' now works.
3166 3184
3167 3185 * IPython/iplib.py (complete): fixed bug where paths starting with
3168 3186 '/' would be completed as magic names.
3169 3187
3170 3188 2002-05-04 Fernando Perez <fperez@colorado.edu>
3171 3189
3172 3190 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3173 3191 allow running full programs under the profiler's control.
3174 3192
3175 3193 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3176 3194 mode to report exceptions verbosely but without formatting
3177 3195 variables. This addresses the issue of ipython 'freezing' (it's
3178 3196 not frozen, but caught in an expensive formatting loop) when huge
3179 3197 variables are in the context of an exception.
3180 3198 (VerboseTB.text): Added '--->' markers at line where exception was
3181 3199 triggered. Much clearer to read, especially in NoColor modes.
3182 3200
3183 3201 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3184 3202 implemented in reverse when changing to the new parse_options().
3185 3203
3186 3204 2002-05-03 Fernando Perez <fperez@colorado.edu>
3187 3205
3188 3206 * IPython/Magic.py (Magic.parse_options): new function so that
3189 3207 magics can parse options easier.
3190 3208 (Magic.magic_prun): new function similar to profile.run(),
3191 3209 suggested by Chris Hart.
3192 3210 (Magic.magic_cd): fixed behavior so that it only changes if
3193 3211 directory actually is in history.
3194 3212
3195 3213 * IPython/usage.py (__doc__): added information about potential
3196 3214 slowness of Verbose exception mode when there are huge data
3197 3215 structures to be formatted (thanks to Archie Paulson).
3198 3216
3199 3217 * IPython/ipmaker.py (make_IPython): Changed default logging
3200 3218 (when simply called with -log) to use curr_dir/ipython.log in
3201 3219 rotate mode. Fixed crash which was occuring with -log before
3202 3220 (thanks to Jim Boyle).
3203 3221
3204 3222 2002-05-01 Fernando Perez <fperez@colorado.edu>
3205 3223
3206 3224 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3207 3225 was nasty -- though somewhat of a corner case).
3208 3226
3209 3227 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3210 3228 text (was a bug).
3211 3229
3212 3230 2002-04-30 Fernando Perez <fperez@colorado.edu>
3213 3231
3214 3232 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3215 3233 a print after ^D or ^C from the user so that the In[] prompt
3216 3234 doesn't over-run the gnuplot one.
3217 3235
3218 3236 2002-04-29 Fernando Perez <fperez@colorado.edu>
3219 3237
3220 3238 * Released 0.2.10
3221 3239
3222 3240 * IPython/__release__.py (version): get date dynamically.
3223 3241
3224 3242 * Misc. documentation updates thanks to Arnd's comments. Also ran
3225 3243 a full spellcheck on the manual (hadn't been done in a while).
3226 3244
3227 3245 2002-04-27 Fernando Perez <fperez@colorado.edu>
3228 3246
3229 3247 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3230 3248 starting a log in mid-session would reset the input history list.
3231 3249
3232 3250 2002-04-26 Fernando Perez <fperez@colorado.edu>
3233 3251
3234 3252 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3235 3253 all files were being included in an update. Now anything in
3236 3254 UserConfig that matches [A-Za-z]*.py will go (this excludes
3237 3255 __init__.py)
3238 3256
3239 3257 2002-04-25 Fernando Perez <fperez@colorado.edu>
3240 3258
3241 3259 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3242 3260 to __builtins__ so that any form of embedded or imported code can
3243 3261 test for being inside IPython.
3244 3262
3245 3263 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3246 3264 changed to GnuplotMagic because it's now an importable module,
3247 3265 this makes the name follow that of the standard Gnuplot module.
3248 3266 GnuplotMagic can now be loaded at any time in mid-session.
3249 3267
3250 3268 2002-04-24 Fernando Perez <fperez@colorado.edu>
3251 3269
3252 3270 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3253 3271 the globals (IPython has its own namespace) and the
3254 3272 PhysicalQuantity stuff is much better anyway.
3255 3273
3256 3274 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3257 3275 embedding example to standard user directory for
3258 3276 distribution. Also put it in the manual.
3259 3277
3260 3278 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3261 3279 instance as first argument (so it doesn't rely on some obscure
3262 3280 hidden global).
3263 3281
3264 3282 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3265 3283 delimiters. While it prevents ().TAB from working, it allows
3266 3284 completions in open (... expressions. This is by far a more common
3267 3285 case.
3268 3286
3269 3287 2002-04-23 Fernando Perez <fperez@colorado.edu>
3270 3288
3271 3289 * IPython/Extensions/InterpreterPasteInput.py: new
3272 3290 syntax-processing module for pasting lines with >>> or ... at the
3273 3291 start.
3274 3292
3275 3293 * IPython/Extensions/PhysicalQ_Interactive.py
3276 3294 (PhysicalQuantityInteractive.__int__): fixed to work with either
3277 3295 Numeric or math.
3278 3296
3279 3297 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3280 3298 provided profiles. Now we have:
3281 3299 -math -> math module as * and cmath with its own namespace.
3282 3300 -numeric -> Numeric as *, plus gnuplot & grace
3283 3301 -physics -> same as before
3284 3302
3285 3303 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3286 3304 user-defined magics wouldn't be found by @magic if they were
3287 3305 defined as class methods. Also cleaned up the namespace search
3288 3306 logic and the string building (to use %s instead of many repeated
3289 3307 string adds).
3290 3308
3291 3309 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3292 3310 of user-defined magics to operate with class methods (cleaner, in
3293 3311 line with the gnuplot code).
3294 3312
3295 3313 2002-04-22 Fernando Perez <fperez@colorado.edu>
3296 3314
3297 3315 * setup.py: updated dependency list so that manual is updated when
3298 3316 all included files change.
3299 3317
3300 3318 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3301 3319 the delimiter removal option (the fix is ugly right now).
3302 3320
3303 3321 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3304 3322 all of the math profile (quicker loading, no conflict between
3305 3323 g-9.8 and g-gnuplot).
3306 3324
3307 3325 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3308 3326 name of post-mortem files to IPython_crash_report.txt.
3309 3327
3310 3328 * Cleanup/update of the docs. Added all the new readline info and
3311 3329 formatted all lists as 'real lists'.
3312 3330
3313 3331 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3314 3332 tab-completion options, since the full readline parse_and_bind is
3315 3333 now accessible.
3316 3334
3317 3335 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3318 3336 handling of readline options. Now users can specify any string to
3319 3337 be passed to parse_and_bind(), as well as the delimiters to be
3320 3338 removed.
3321 3339 (InteractiveShell.__init__): Added __name__ to the global
3322 3340 namespace so that things like Itpl which rely on its existence
3323 3341 don't crash.
3324 3342 (InteractiveShell._prefilter): Defined the default with a _ so
3325 3343 that prefilter() is easier to override, while the default one
3326 3344 remains available.
3327 3345
3328 3346 2002-04-18 Fernando Perez <fperez@colorado.edu>
3329 3347
3330 3348 * Added information about pdb in the docs.
3331 3349
3332 3350 2002-04-17 Fernando Perez <fperez@colorado.edu>
3333 3351
3334 3352 * IPython/ipmaker.py (make_IPython): added rc_override option to
3335 3353 allow passing config options at creation time which may override
3336 3354 anything set in the config files or command line. This is
3337 3355 particularly useful for configuring embedded instances.
3338 3356
3339 3357 2002-04-15 Fernando Perez <fperez@colorado.edu>
3340 3358
3341 3359 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3342 3360 crash embedded instances because of the input cache falling out of
3343 3361 sync with the output counter.
3344 3362
3345 3363 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3346 3364 mode which calls pdb after an uncaught exception in IPython itself.
3347 3365
3348 3366 2002-04-14 Fernando Perez <fperez@colorado.edu>
3349 3367
3350 3368 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3351 3369 readline, fix it back after each call.
3352 3370
3353 3371 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3354 3372 method to force all access via __call__(), which guarantees that
3355 3373 traceback references are properly deleted.
3356 3374
3357 3375 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3358 3376 improve printing when pprint is in use.
3359 3377
3360 3378 2002-04-13 Fernando Perez <fperez@colorado.edu>
3361 3379
3362 3380 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3363 3381 exceptions aren't caught anymore. If the user triggers one, he
3364 3382 should know why he's doing it and it should go all the way up,
3365 3383 just like any other exception. So now @abort will fully kill the
3366 3384 embedded interpreter and the embedding code (unless that happens
3367 3385 to catch SystemExit).
3368 3386
3369 3387 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3370 3388 and a debugger() method to invoke the interactive pdb debugger
3371 3389 after printing exception information. Also added the corresponding
3372 3390 -pdb option and @pdb magic to control this feature, and updated
3373 3391 the docs. After a suggestion from Christopher Hart
3374 3392 (hart-AT-caltech.edu).
3375 3393
3376 3394 2002-04-12 Fernando Perez <fperez@colorado.edu>
3377 3395
3378 3396 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3379 3397 the exception handlers defined by the user (not the CrashHandler)
3380 3398 so that user exceptions don't trigger an ipython bug report.
3381 3399
3382 3400 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3383 3401 configurable (it should have always been so).
3384 3402
3385 3403 2002-03-26 Fernando Perez <fperez@colorado.edu>
3386 3404
3387 3405 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3388 3406 and there to fix embedding namespace issues. This should all be
3389 3407 done in a more elegant way.
3390 3408
3391 3409 2002-03-25 Fernando Perez <fperez@colorado.edu>
3392 3410
3393 3411 * IPython/genutils.py (get_home_dir): Try to make it work under
3394 3412 win9x also.
3395 3413
3396 3414 2002-03-20 Fernando Perez <fperez@colorado.edu>
3397 3415
3398 3416 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3399 3417 sys.displayhook untouched upon __init__.
3400 3418
3401 3419 2002-03-19 Fernando Perez <fperez@colorado.edu>
3402 3420
3403 3421 * Released 0.2.9 (for embedding bug, basically).
3404 3422
3405 3423 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3406 3424 exceptions so that enclosing shell's state can be restored.
3407 3425
3408 3426 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3409 3427 naming conventions in the .ipython/ dir.
3410 3428
3411 3429 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3412 3430 from delimiters list so filenames with - in them get expanded.
3413 3431
3414 3432 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3415 3433 sys.displayhook not being properly restored after an embedded call.
3416 3434
3417 3435 2002-03-18 Fernando Perez <fperez@colorado.edu>
3418 3436
3419 3437 * Released 0.2.8
3420 3438
3421 3439 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3422 3440 some files weren't being included in a -upgrade.
3423 3441 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3424 3442 on' so that the first tab completes.
3425 3443 (InteractiveShell.handle_magic): fixed bug with spaces around
3426 3444 quotes breaking many magic commands.
3427 3445
3428 3446 * setup.py: added note about ignoring the syntax error messages at
3429 3447 installation.
3430 3448
3431 3449 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3432 3450 streamlining the gnuplot interface, now there's only one magic @gp.
3433 3451
3434 3452 2002-03-17 Fernando Perez <fperez@colorado.edu>
3435 3453
3436 3454 * IPython/UserConfig/magic_gnuplot.py: new name for the
3437 3455 example-magic_pm.py file. Much enhanced system, now with a shell
3438 3456 for communicating directly with gnuplot, one command at a time.
3439 3457
3440 3458 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3441 3459 setting __name__=='__main__'.
3442 3460
3443 3461 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3444 3462 mini-shell for accessing gnuplot from inside ipython. Should
3445 3463 extend it later for grace access too. Inspired by Arnd's
3446 3464 suggestion.
3447 3465
3448 3466 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3449 3467 calling magic functions with () in their arguments. Thanks to Arnd
3450 3468 Baecker for pointing this to me.
3451 3469
3452 3470 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3453 3471 infinitely for integer or complex arrays (only worked with floats).
3454 3472
3455 3473 2002-03-16 Fernando Perez <fperez@colorado.edu>
3456 3474
3457 3475 * setup.py: Merged setup and setup_windows into a single script
3458 3476 which properly handles things for windows users.
3459 3477
3460 3478 2002-03-15 Fernando Perez <fperez@colorado.edu>
3461 3479
3462 3480 * Big change to the manual: now the magics are all automatically
3463 3481 documented. This information is generated from their docstrings
3464 3482 and put in a latex file included by the manual lyx file. This way
3465 3483 we get always up to date information for the magics. The manual
3466 3484 now also has proper version information, also auto-synced.
3467 3485
3468 3486 For this to work, an undocumented --magic_docstrings option was added.
3469 3487
3470 3488 2002-03-13 Fernando Perez <fperez@colorado.edu>
3471 3489
3472 3490 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3473 3491 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3474 3492
3475 3493 2002-03-12 Fernando Perez <fperez@colorado.edu>
3476 3494
3477 3495 * IPython/ultraTB.py (TermColors): changed color escapes again to
3478 3496 fix the (old, reintroduced) line-wrapping bug. Basically, if
3479 3497 \001..\002 aren't given in the color escapes, lines get wrapped
3480 3498 weirdly. But giving those screws up old xterms and emacs terms. So
3481 3499 I added some logic for emacs terms to be ok, but I can't identify old
3482 3500 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3483 3501
3484 3502 2002-03-10 Fernando Perez <fperez@colorado.edu>
3485 3503
3486 3504 * IPython/usage.py (__doc__): Various documentation cleanups and
3487 3505 updates, both in usage docstrings and in the manual.
3488 3506
3489 3507 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3490 3508 handling of caching. Set minimum acceptabe value for having a
3491 3509 cache at 20 values.
3492 3510
3493 3511 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3494 3512 install_first_time function to a method, renamed it and added an
3495 3513 'upgrade' mode. Now people can update their config directory with
3496 3514 a simple command line switch (-upgrade, also new).
3497 3515
3498 3516 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3499 3517 @file (convenient for automagic users under Python >= 2.2).
3500 3518 Removed @files (it seemed more like a plural than an abbrev. of
3501 3519 'file show').
3502 3520
3503 3521 * IPython/iplib.py (install_first_time): Fixed crash if there were
3504 3522 backup files ('~') in .ipython/ install directory.
3505 3523
3506 3524 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3507 3525 system. Things look fine, but these changes are fairly
3508 3526 intrusive. Test them for a few days.
3509 3527
3510 3528 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3511 3529 the prompts system. Now all in/out prompt strings are user
3512 3530 controllable. This is particularly useful for embedding, as one
3513 3531 can tag embedded instances with particular prompts.
3514 3532
3515 3533 Also removed global use of sys.ps1/2, which now allows nested
3516 3534 embeddings without any problems. Added command-line options for
3517 3535 the prompt strings.
3518 3536
3519 3537 2002-03-08 Fernando Perez <fperez@colorado.edu>
3520 3538
3521 3539 * IPython/UserConfig/example-embed-short.py (ipshell): added
3522 3540 example file with the bare minimum code for embedding.
3523 3541
3524 3542 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3525 3543 functionality for the embeddable shell to be activated/deactivated
3526 3544 either globally or at each call.
3527 3545
3528 3546 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3529 3547 rewriting the prompt with '--->' for auto-inputs with proper
3530 3548 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3531 3549 this is handled by the prompts class itself, as it should.
3532 3550
3533 3551 2002-03-05 Fernando Perez <fperez@colorado.edu>
3534 3552
3535 3553 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3536 3554 @logstart to avoid name clashes with the math log function.
3537 3555
3538 3556 * Big updates to X/Emacs section of the manual.
3539 3557
3540 3558 * Removed ipython_emacs. Milan explained to me how to pass
3541 3559 arguments to ipython through Emacs. Some day I'm going to end up
3542 3560 learning some lisp...
3543 3561
3544 3562 2002-03-04 Fernando Perez <fperez@colorado.edu>
3545 3563
3546 3564 * IPython/ipython_emacs: Created script to be used as the
3547 3565 py-python-command Emacs variable so we can pass IPython
3548 3566 parameters. I can't figure out how to tell Emacs directly to pass
3549 3567 parameters to IPython, so a dummy shell script will do it.
3550 3568
3551 3569 Other enhancements made for things to work better under Emacs'
3552 3570 various types of terminals. Many thanks to Milan Zamazal
3553 3571 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3554 3572
3555 3573 2002-03-01 Fernando Perez <fperez@colorado.edu>
3556 3574
3557 3575 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3558 3576 that loading of readline is now optional. This gives better
3559 3577 control to emacs users.
3560 3578
3561 3579 * IPython/ultraTB.py (__date__): Modified color escape sequences
3562 3580 and now things work fine under xterm and in Emacs' term buffers
3563 3581 (though not shell ones). Well, in emacs you get colors, but all
3564 3582 seem to be 'light' colors (no difference between dark and light
3565 3583 ones). But the garbage chars are gone, and also in xterms. It
3566 3584 seems that now I'm using 'cleaner' ansi sequences.
3567 3585
3568 3586 2002-02-21 Fernando Perez <fperez@colorado.edu>
3569 3587
3570 3588 * Released 0.2.7 (mainly to publish the scoping fix).
3571 3589
3572 3590 * IPython/Logger.py (Logger.logstate): added. A corresponding
3573 3591 @logstate magic was created.
3574 3592
3575 3593 * IPython/Magic.py: fixed nested scoping problem under Python
3576 3594 2.1.x (automagic wasn't working).
3577 3595
3578 3596 2002-02-20 Fernando Perez <fperez@colorado.edu>
3579 3597
3580 3598 * Released 0.2.6.
3581 3599
3582 3600 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3583 3601 option so that logs can come out without any headers at all.
3584 3602
3585 3603 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3586 3604 SciPy.
3587 3605
3588 3606 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3589 3607 that embedded IPython calls don't require vars() to be explicitly
3590 3608 passed. Now they are extracted from the caller's frame (code
3591 3609 snatched from Eric Jones' weave). Added better documentation to
3592 3610 the section on embedding and the example file.
3593 3611
3594 3612 * IPython/genutils.py (page): Changed so that under emacs, it just
3595 3613 prints the string. You can then page up and down in the emacs
3596 3614 buffer itself. This is how the builtin help() works.
3597 3615
3598 3616 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3599 3617 macro scoping: macros need to be executed in the user's namespace
3600 3618 to work as if they had been typed by the user.
3601 3619
3602 3620 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3603 3621 execute automatically (no need to type 'exec...'). They then
3604 3622 behave like 'true macros'. The printing system was also modified
3605 3623 for this to work.
3606 3624
3607 3625 2002-02-19 Fernando Perez <fperez@colorado.edu>
3608 3626
3609 3627 * IPython/genutils.py (page_file): new function for paging files
3610 3628 in an OS-independent way. Also necessary for file viewing to work
3611 3629 well inside Emacs buffers.
3612 3630 (page): Added checks for being in an emacs buffer.
3613 3631 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3614 3632 same bug in iplib.
3615 3633
3616 3634 2002-02-18 Fernando Perez <fperez@colorado.edu>
3617 3635
3618 3636 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3619 3637 of readline so that IPython can work inside an Emacs buffer.
3620 3638
3621 3639 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3622 3640 method signatures (they weren't really bugs, but it looks cleaner
3623 3641 and keeps PyChecker happy).
3624 3642
3625 3643 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3626 3644 for implementing various user-defined hooks. Currently only
3627 3645 display is done.
3628 3646
3629 3647 * IPython/Prompts.py (CachedOutput._display): changed display
3630 3648 functions so that they can be dynamically changed by users easily.
3631 3649
3632 3650 * IPython/Extensions/numeric_formats.py (num_display): added an
3633 3651 extension for printing NumPy arrays in flexible manners. It
3634 3652 doesn't do anything yet, but all the structure is in
3635 3653 place. Ultimately the plan is to implement output format control
3636 3654 like in Octave.
3637 3655
3638 3656 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3639 3657 methods are found at run-time by all the automatic machinery.
3640 3658
3641 3659 2002-02-17 Fernando Perez <fperez@colorado.edu>
3642 3660
3643 3661 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3644 3662 whole file a little.
3645 3663
3646 3664 * ToDo: closed this document. Now there's a new_design.lyx
3647 3665 document for all new ideas. Added making a pdf of it for the
3648 3666 end-user distro.
3649 3667
3650 3668 * IPython/Logger.py (Logger.switch_log): Created this to replace
3651 3669 logon() and logoff(). It also fixes a nasty crash reported by
3652 3670 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3653 3671
3654 3672 * IPython/iplib.py (complete): got auto-completion to work with
3655 3673 automagic (I had wanted this for a long time).
3656 3674
3657 3675 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3658 3676 to @file, since file() is now a builtin and clashes with automagic
3659 3677 for @file.
3660 3678
3661 3679 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3662 3680 of this was previously in iplib, which had grown to more than 2000
3663 3681 lines, way too long. No new functionality, but it makes managing
3664 3682 the code a bit easier.
3665 3683
3666 3684 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3667 3685 information to crash reports.
3668 3686
3669 3687 2002-02-12 Fernando Perez <fperez@colorado.edu>
3670 3688
3671 3689 * Released 0.2.5.
3672 3690
3673 3691 2002-02-11 Fernando Perez <fperez@colorado.edu>
3674 3692
3675 3693 * Wrote a relatively complete Windows installer. It puts
3676 3694 everything in place, creates Start Menu entries and fixes the
3677 3695 color issues. Nothing fancy, but it works.
3678 3696
3679 3697 2002-02-10 Fernando Perez <fperez@colorado.edu>
3680 3698
3681 3699 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3682 3700 os.path.expanduser() call so that we can type @run ~/myfile.py and
3683 3701 have thigs work as expected.
3684 3702
3685 3703 * IPython/genutils.py (page): fixed exception handling so things
3686 3704 work both in Unix and Windows correctly. Quitting a pager triggers
3687 3705 an IOError/broken pipe in Unix, and in windows not finding a pager
3688 3706 is also an IOError, so I had to actually look at the return value
3689 3707 of the exception, not just the exception itself. Should be ok now.
3690 3708
3691 3709 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3692 3710 modified to allow case-insensitive color scheme changes.
3693 3711
3694 3712 2002-02-09 Fernando Perez <fperez@colorado.edu>
3695 3713
3696 3714 * IPython/genutils.py (native_line_ends): new function to leave
3697 3715 user config files with os-native line-endings.
3698 3716
3699 3717 * README and manual updates.
3700 3718
3701 3719 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3702 3720 instead of StringType to catch Unicode strings.
3703 3721
3704 3722 * IPython/genutils.py (filefind): fixed bug for paths with
3705 3723 embedded spaces (very common in Windows).
3706 3724
3707 3725 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3708 3726 files under Windows, so that they get automatically associated
3709 3727 with a text editor. Windows makes it a pain to handle
3710 3728 extension-less files.
3711 3729
3712 3730 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3713 3731 warning about readline only occur for Posix. In Windows there's no
3714 3732 way to get readline, so why bother with the warning.
3715 3733
3716 3734 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3717 3735 for __str__ instead of dir(self), since dir() changed in 2.2.
3718 3736
3719 3737 * Ported to Windows! Tested on XP, I suspect it should work fine
3720 3738 on NT/2000, but I don't think it will work on 98 et al. That
3721 3739 series of Windows is such a piece of junk anyway that I won't try
3722 3740 porting it there. The XP port was straightforward, showed a few
3723 3741 bugs here and there (fixed all), in particular some string
3724 3742 handling stuff which required considering Unicode strings (which
3725 3743 Windows uses). This is good, but hasn't been too tested :) No
3726 3744 fancy installer yet, I'll put a note in the manual so people at
3727 3745 least make manually a shortcut.
3728 3746
3729 3747 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3730 3748 into a single one, "colors". This now controls both prompt and
3731 3749 exception color schemes, and can be changed both at startup
3732 3750 (either via command-line switches or via ipythonrc files) and at
3733 3751 runtime, with @colors.
3734 3752 (Magic.magic_run): renamed @prun to @run and removed the old
3735 3753 @run. The two were too similar to warrant keeping both.
3736 3754
3737 3755 2002-02-03 Fernando Perez <fperez@colorado.edu>
3738 3756
3739 3757 * IPython/iplib.py (install_first_time): Added comment on how to
3740 3758 configure the color options for first-time users. Put a <return>
3741 3759 request at the end so that small-terminal users get a chance to
3742 3760 read the startup info.
3743 3761
3744 3762 2002-01-23 Fernando Perez <fperez@colorado.edu>
3745 3763
3746 3764 * IPython/iplib.py (CachedOutput.update): Changed output memory
3747 3765 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3748 3766 input history we still use _i. Did this b/c these variable are
3749 3767 very commonly used in interactive work, so the less we need to
3750 3768 type the better off we are.
3751 3769 (Magic.magic_prun): updated @prun to better handle the namespaces
3752 3770 the file will run in, including a fix for __name__ not being set
3753 3771 before.
3754 3772
3755 3773 2002-01-20 Fernando Perez <fperez@colorado.edu>
3756 3774
3757 3775 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3758 3776 extra garbage for Python 2.2. Need to look more carefully into
3759 3777 this later.
3760 3778
3761 3779 2002-01-19 Fernando Perez <fperez@colorado.edu>
3762 3780
3763 3781 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3764 3782 display SyntaxError exceptions properly formatted when they occur
3765 3783 (they can be triggered by imported code).
3766 3784
3767 3785 2002-01-18 Fernando Perez <fperez@colorado.edu>
3768 3786
3769 3787 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3770 3788 SyntaxError exceptions are reported nicely formatted, instead of
3771 3789 spitting out only offset information as before.
3772 3790 (Magic.magic_prun): Added the @prun function for executing
3773 3791 programs with command line args inside IPython.
3774 3792
3775 3793 2002-01-16 Fernando Perez <fperez@colorado.edu>
3776 3794
3777 3795 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3778 3796 to *not* include the last item given in a range. This brings their
3779 3797 behavior in line with Python's slicing:
3780 3798 a[n1:n2] -> a[n1]...a[n2-1]
3781 3799 It may be a bit less convenient, but I prefer to stick to Python's
3782 3800 conventions *everywhere*, so users never have to wonder.
3783 3801 (Magic.magic_macro): Added @macro function to ease the creation of
3784 3802 macros.
3785 3803
3786 3804 2002-01-05 Fernando Perez <fperez@colorado.edu>
3787 3805
3788 3806 * Released 0.2.4.
3789 3807
3790 3808 * IPython/iplib.py (Magic.magic_pdef):
3791 3809 (InteractiveShell.safe_execfile): report magic lines and error
3792 3810 lines without line numbers so one can easily copy/paste them for
3793 3811 re-execution.
3794 3812
3795 3813 * Updated manual with recent changes.
3796 3814
3797 3815 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3798 3816 docstring printing when class? is called. Very handy for knowing
3799 3817 how to create class instances (as long as __init__ is well
3800 3818 documented, of course :)
3801 3819 (Magic.magic_doc): print both class and constructor docstrings.
3802 3820 (Magic.magic_pdef): give constructor info if passed a class and
3803 3821 __call__ info for callable object instances.
3804 3822
3805 3823 2002-01-04 Fernando Perez <fperez@colorado.edu>
3806 3824
3807 3825 * Made deep_reload() off by default. It doesn't always work
3808 3826 exactly as intended, so it's probably safer to have it off. It's
3809 3827 still available as dreload() anyway, so nothing is lost.
3810 3828
3811 3829 2002-01-02 Fernando Perez <fperez@colorado.edu>
3812 3830
3813 3831 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3814 3832 so I wanted an updated release).
3815 3833
3816 3834 2001-12-27 Fernando Perez <fperez@colorado.edu>
3817 3835
3818 3836 * IPython/iplib.py (InteractiveShell.interact): Added the original
3819 3837 code from 'code.py' for this module in order to change the
3820 3838 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3821 3839 the history cache would break when the user hit Ctrl-C, and
3822 3840 interact() offers no way to add any hooks to it.
3823 3841
3824 3842 2001-12-23 Fernando Perez <fperez@colorado.edu>
3825 3843
3826 3844 * setup.py: added check for 'MANIFEST' before trying to remove
3827 3845 it. Thanks to Sean Reifschneider.
3828 3846
3829 3847 2001-12-22 Fernando Perez <fperez@colorado.edu>
3830 3848
3831 3849 * Released 0.2.2.
3832 3850
3833 3851 * Finished (reasonably) writing the manual. Later will add the
3834 3852 python-standard navigation stylesheets, but for the time being
3835 3853 it's fairly complete. Distribution will include html and pdf
3836 3854 versions.
3837 3855
3838 3856 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3839 3857 (MayaVi author).
3840 3858
3841 3859 2001-12-21 Fernando Perez <fperez@colorado.edu>
3842 3860
3843 3861 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3844 3862 good public release, I think (with the manual and the distutils
3845 3863 installer). The manual can use some work, but that can go
3846 3864 slowly. Otherwise I think it's quite nice for end users. Next
3847 3865 summer, rewrite the guts of it...
3848 3866
3849 3867 * Changed format of ipythonrc files to use whitespace as the
3850 3868 separator instead of an explicit '='. Cleaner.
3851 3869
3852 3870 2001-12-20 Fernando Perez <fperez@colorado.edu>
3853 3871
3854 3872 * Started a manual in LyX. For now it's just a quick merge of the
3855 3873 various internal docstrings and READMEs. Later it may grow into a
3856 3874 nice, full-blown manual.
3857 3875
3858 3876 * Set up a distutils based installer. Installation should now be
3859 3877 trivially simple for end-users.
3860 3878
3861 3879 2001-12-11 Fernando Perez <fperez@colorado.edu>
3862 3880
3863 3881 * Released 0.2.0. First public release, announced it at
3864 3882 comp.lang.python. From now on, just bugfixes...
3865 3883
3866 3884 * Went through all the files, set copyright/license notices and
3867 3885 cleaned up things. Ready for release.
3868 3886
3869 3887 2001-12-10 Fernando Perez <fperez@colorado.edu>
3870 3888
3871 3889 * Changed the first-time installer not to use tarfiles. It's more
3872 3890 robust now and less unix-dependent. Also makes it easier for
3873 3891 people to later upgrade versions.
3874 3892
3875 3893 * Changed @exit to @abort to reflect the fact that it's pretty
3876 3894 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3877 3895 becomes significant only when IPyhton is embedded: in that case,
3878 3896 C-D closes IPython only, but @abort kills the enclosing program
3879 3897 too (unless it had called IPython inside a try catching
3880 3898 SystemExit).
3881 3899
3882 3900 * Created Shell module which exposes the actuall IPython Shell
3883 3901 classes, currently the normal and the embeddable one. This at
3884 3902 least offers a stable interface we won't need to change when
3885 3903 (later) the internals are rewritten. That rewrite will be confined
3886 3904 to iplib and ipmaker, but the Shell interface should remain as is.
3887 3905
3888 3906 * Added embed module which offers an embeddable IPShell object,
3889 3907 useful to fire up IPython *inside* a running program. Great for
3890 3908 debugging or dynamical data analysis.
3891 3909
3892 3910 2001-12-08 Fernando Perez <fperez@colorado.edu>
3893 3911
3894 3912 * Fixed small bug preventing seeing info from methods of defined
3895 3913 objects (incorrect namespace in _ofind()).
3896 3914
3897 3915 * Documentation cleanup. Moved the main usage docstrings to a
3898 3916 separate file, usage.py (cleaner to maintain, and hopefully in the
3899 3917 future some perlpod-like way of producing interactive, man and
3900 3918 html docs out of it will be found).
3901 3919
3902 3920 * Added @profile to see your profile at any time.
3903 3921
3904 3922 * Added @p as an alias for 'print'. It's especially convenient if
3905 3923 using automagic ('p x' prints x).
3906 3924
3907 3925 * Small cleanups and fixes after a pychecker run.
3908 3926
3909 3927 * Changed the @cd command to handle @cd - and @cd -<n> for
3910 3928 visiting any directory in _dh.
3911 3929
3912 3930 * Introduced _dh, a history of visited directories. @dhist prints
3913 3931 it out with numbers.
3914 3932
3915 3933 2001-12-07 Fernando Perez <fperez@colorado.edu>
3916 3934
3917 3935 * Released 0.1.22
3918 3936
3919 3937 * Made initialization a bit more robust against invalid color
3920 3938 options in user input (exit, not traceback-crash).
3921 3939
3922 3940 * Changed the bug crash reporter to write the report only in the
3923 3941 user's .ipython directory. That way IPython won't litter people's
3924 3942 hard disks with crash files all over the place. Also print on
3925 3943 screen the necessary mail command.
3926 3944
3927 3945 * With the new ultraTB, implemented LightBG color scheme for light
3928 3946 background terminals. A lot of people like white backgrounds, so I
3929 3947 guess we should at least give them something readable.
3930 3948
3931 3949 2001-12-06 Fernando Perez <fperez@colorado.edu>
3932 3950
3933 3951 * Modified the structure of ultraTB. Now there's a proper class
3934 3952 for tables of color schemes which allow adding schemes easily and
3935 3953 switching the active scheme without creating a new instance every
3936 3954 time (which was ridiculous). The syntax for creating new schemes
3937 3955 is also cleaner. I think ultraTB is finally done, with a clean
3938 3956 class structure. Names are also much cleaner (now there's proper
3939 3957 color tables, no need for every variable to also have 'color' in
3940 3958 its name).
3941 3959
3942 3960 * Broke down genutils into separate files. Now genutils only
3943 3961 contains utility functions, and classes have been moved to their
3944 3962 own files (they had enough independent functionality to warrant
3945 3963 it): ConfigLoader, OutputTrap, Struct.
3946 3964
3947 3965 2001-12-05 Fernando Perez <fperez@colorado.edu>
3948 3966
3949 3967 * IPython turns 21! Released version 0.1.21, as a candidate for
3950 3968 public consumption. If all goes well, release in a few days.
3951 3969
3952 3970 * Fixed path bug (files in Extensions/ directory wouldn't be found
3953 3971 unless IPython/ was explicitly in sys.path).
3954 3972
3955 3973 * Extended the FlexCompleter class as MagicCompleter to allow
3956 3974 completion of @-starting lines.
3957 3975
3958 3976 * Created __release__.py file as a central repository for release
3959 3977 info that other files can read from.
3960 3978
3961 3979 * Fixed small bug in logging: when logging was turned on in
3962 3980 mid-session, old lines with special meanings (!@?) were being
3963 3981 logged without the prepended comment, which is necessary since
3964 3982 they are not truly valid python syntax. This should make session
3965 3983 restores produce less errors.
3966 3984
3967 3985 * The namespace cleanup forced me to make a FlexCompleter class
3968 3986 which is nothing but a ripoff of rlcompleter, but with selectable
3969 3987 namespace (rlcompleter only works in __main__.__dict__). I'll try
3970 3988 to submit a note to the authors to see if this change can be
3971 3989 incorporated in future rlcompleter releases (Dec.6: done)
3972 3990
3973 3991 * More fixes to namespace handling. It was a mess! Now all
3974 3992 explicit references to __main__.__dict__ are gone (except when
3975 3993 really needed) and everything is handled through the namespace
3976 3994 dicts in the IPython instance. We seem to be getting somewhere
3977 3995 with this, finally...
3978 3996
3979 3997 * Small documentation updates.
3980 3998
3981 3999 * Created the Extensions directory under IPython (with an
3982 4000 __init__.py). Put the PhysicalQ stuff there. This directory should
3983 4001 be used for all special-purpose extensions.
3984 4002
3985 4003 * File renaming:
3986 4004 ipythonlib --> ipmaker
3987 4005 ipplib --> iplib
3988 4006 This makes a bit more sense in terms of what these files actually do.
3989 4007
3990 4008 * Moved all the classes and functions in ipythonlib to ipplib, so
3991 4009 now ipythonlib only has make_IPython(). This will ease up its
3992 4010 splitting in smaller functional chunks later.
3993 4011
3994 4012 * Cleaned up (done, I think) output of @whos. Better column
3995 4013 formatting, and now shows str(var) for as much as it can, which is
3996 4014 typically what one gets with a 'print var'.
3997 4015
3998 4016 2001-12-04 Fernando Perez <fperez@colorado.edu>
3999 4017
4000 4018 * Fixed namespace problems. Now builtin/IPyhton/user names get
4001 4019 properly reported in their namespace. Internal namespace handling
4002 4020 is finally getting decent (not perfect yet, but much better than
4003 4021 the ad-hoc mess we had).
4004 4022
4005 4023 * Removed -exit option. If people just want to run a python
4006 4024 script, that's what the normal interpreter is for. Less
4007 4025 unnecessary options, less chances for bugs.
4008 4026
4009 4027 * Added a crash handler which generates a complete post-mortem if
4010 4028 IPython crashes. This will help a lot in tracking bugs down the
4011 4029 road.
4012 4030
4013 4031 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4014 4032 which were boud to functions being reassigned would bypass the
4015 4033 logger, breaking the sync of _il with the prompt counter. This
4016 4034 would then crash IPython later when a new line was logged.
4017 4035
4018 4036 2001-12-02 Fernando Perez <fperez@colorado.edu>
4019 4037
4020 4038 * Made IPython a package. This means people don't have to clutter
4021 4039 their sys.path with yet another directory. Changed the INSTALL
4022 4040 file accordingly.
4023 4041
4024 4042 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4025 4043 sorts its output (so @who shows it sorted) and @whos formats the
4026 4044 table according to the width of the first column. Nicer, easier to
4027 4045 read. Todo: write a generic table_format() which takes a list of
4028 4046 lists and prints it nicely formatted, with optional row/column
4029 4047 separators and proper padding and justification.
4030 4048
4031 4049 * Released 0.1.20
4032 4050
4033 4051 * Fixed bug in @log which would reverse the inputcache list (a
4034 4052 copy operation was missing).
4035 4053
4036 4054 * Code cleanup. @config was changed to use page(). Better, since
4037 4055 its output is always quite long.
4038 4056
4039 4057 * Itpl is back as a dependency. I was having too many problems
4040 4058 getting the parametric aliases to work reliably, and it's just
4041 4059 easier to code weird string operations with it than playing %()s
4042 4060 games. It's only ~6k, so I don't think it's too big a deal.
4043 4061
4044 4062 * Found (and fixed) a very nasty bug with history. !lines weren't
4045 4063 getting cached, and the out of sync caches would crash
4046 4064 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4047 4065 division of labor a bit better. Bug fixed, cleaner structure.
4048 4066
4049 4067 2001-12-01 Fernando Perez <fperez@colorado.edu>
4050 4068
4051 4069 * Released 0.1.19
4052 4070
4053 4071 * Added option -n to @hist to prevent line number printing. Much
4054 4072 easier to copy/paste code this way.
4055 4073
4056 4074 * Created global _il to hold the input list. Allows easy
4057 4075 re-execution of blocks of code by slicing it (inspired by Janko's
4058 4076 comment on 'macros').
4059 4077
4060 4078 * Small fixes and doc updates.
4061 4079
4062 4080 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4063 4081 much too fragile with automagic. Handles properly multi-line
4064 4082 statements and takes parameters.
4065 4083
4066 4084 2001-11-30 Fernando Perez <fperez@colorado.edu>
4067 4085
4068 4086 * Version 0.1.18 released.
4069 4087
4070 4088 * Fixed nasty namespace bug in initial module imports.
4071 4089
4072 4090 * Added copyright/license notes to all code files (except
4073 4091 DPyGetOpt). For the time being, LGPL. That could change.
4074 4092
4075 4093 * Rewrote a much nicer README, updated INSTALL, cleaned up
4076 4094 ipythonrc-* samples.
4077 4095
4078 4096 * Overall code/documentation cleanup. Basically ready for
4079 4097 release. Only remaining thing: licence decision (LGPL?).
4080 4098
4081 4099 * Converted load_config to a class, ConfigLoader. Now recursion
4082 4100 control is better organized. Doesn't include the same file twice.
4083 4101
4084 4102 2001-11-29 Fernando Perez <fperez@colorado.edu>
4085 4103
4086 4104 * Got input history working. Changed output history variables from
4087 4105 _p to _o so that _i is for input and _o for output. Just cleaner
4088 4106 convention.
4089 4107
4090 4108 * Implemented parametric aliases. This pretty much allows the
4091 4109 alias system to offer full-blown shell convenience, I think.
4092 4110
4093 4111 * Version 0.1.17 released, 0.1.18 opened.
4094 4112
4095 4113 * dot_ipython/ipythonrc (alias): added documentation.
4096 4114 (xcolor): Fixed small bug (xcolors -> xcolor)
4097 4115
4098 4116 * Changed the alias system. Now alias is a magic command to define
4099 4117 aliases just like the shell. Rationale: the builtin magics should
4100 4118 be there for things deeply connected to IPython's
4101 4119 architecture. And this is a much lighter system for what I think
4102 4120 is the really important feature: allowing users to define quickly
4103 4121 magics that will do shell things for them, so they can customize
4104 4122 IPython easily to match their work habits. If someone is really
4105 4123 desperate to have another name for a builtin alias, they can
4106 4124 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4107 4125 works.
4108 4126
4109 4127 2001-11-28 Fernando Perez <fperez@colorado.edu>
4110 4128
4111 4129 * Changed @file so that it opens the source file at the proper
4112 4130 line. Since it uses less, if your EDITOR environment is
4113 4131 configured, typing v will immediately open your editor of choice
4114 4132 right at the line where the object is defined. Not as quick as
4115 4133 having a direct @edit command, but for all intents and purposes it
4116 4134 works. And I don't have to worry about writing @edit to deal with
4117 4135 all the editors, less does that.
4118 4136
4119 4137 * Version 0.1.16 released, 0.1.17 opened.
4120 4138
4121 4139 * Fixed some nasty bugs in the page/page_dumb combo that could
4122 4140 crash IPython.
4123 4141
4124 4142 2001-11-27 Fernando Perez <fperez@colorado.edu>
4125 4143
4126 4144 * Version 0.1.15 released, 0.1.16 opened.
4127 4145
4128 4146 * Finally got ? and ?? to work for undefined things: now it's
4129 4147 possible to type {}.get? and get information about the get method
4130 4148 of dicts, or os.path? even if only os is defined (so technically
4131 4149 os.path isn't). Works at any level. For example, after import os,
4132 4150 os?, os.path?, os.path.abspath? all work. This is great, took some
4133 4151 work in _ofind.
4134 4152
4135 4153 * Fixed more bugs with logging. The sanest way to do it was to add
4136 4154 to @log a 'mode' parameter. Killed two in one shot (this mode
4137 4155 option was a request of Janko's). I think it's finally clean
4138 4156 (famous last words).
4139 4157
4140 4158 * Added a page_dumb() pager which does a decent job of paging on
4141 4159 screen, if better things (like less) aren't available. One less
4142 4160 unix dependency (someday maybe somebody will port this to
4143 4161 windows).
4144 4162
4145 4163 * Fixed problem in magic_log: would lock of logging out if log
4146 4164 creation failed (because it would still think it had succeeded).
4147 4165
4148 4166 * Improved the page() function using curses to auto-detect screen
4149 4167 size. Now it can make a much better decision on whether to print
4150 4168 or page a string. Option screen_length was modified: a value 0
4151 4169 means auto-detect, and that's the default now.
4152 4170
4153 4171 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4154 4172 go out. I'll test it for a few days, then talk to Janko about
4155 4173 licences and announce it.
4156 4174
4157 4175 * Fixed the length of the auto-generated ---> prompt which appears
4158 4176 for auto-parens and auto-quotes. Getting this right isn't trivial,
4159 4177 with all the color escapes, different prompt types and optional
4160 4178 separators. But it seems to be working in all the combinations.
4161 4179
4162 4180 2001-11-26 Fernando Perez <fperez@colorado.edu>
4163 4181
4164 4182 * Wrote a regexp filter to get option types from the option names
4165 4183 string. This eliminates the need to manually keep two duplicate
4166 4184 lists.
4167 4185
4168 4186 * Removed the unneeded check_option_names. Now options are handled
4169 4187 in a much saner manner and it's easy to visually check that things
4170 4188 are ok.
4171 4189
4172 4190 * Updated version numbers on all files I modified to carry a
4173 4191 notice so Janko and Nathan have clear version markers.
4174 4192
4175 4193 * Updated docstring for ultraTB with my changes. I should send
4176 4194 this to Nathan.
4177 4195
4178 4196 * Lots of small fixes. Ran everything through pychecker again.
4179 4197
4180 4198 * Made loading of deep_reload an cmd line option. If it's not too
4181 4199 kosher, now people can just disable it. With -nodeep_reload it's
4182 4200 still available as dreload(), it just won't overwrite reload().
4183 4201
4184 4202 * Moved many options to the no| form (-opt and -noopt
4185 4203 accepted). Cleaner.
4186 4204
4187 4205 * Changed magic_log so that if called with no parameters, it uses
4188 4206 'rotate' mode. That way auto-generated logs aren't automatically
4189 4207 over-written. For normal logs, now a backup is made if it exists
4190 4208 (only 1 level of backups). A new 'backup' mode was added to the
4191 4209 Logger class to support this. This was a request by Janko.
4192 4210
4193 4211 * Added @logoff/@logon to stop/restart an active log.
4194 4212
4195 4213 * Fixed a lot of bugs in log saving/replay. It was pretty
4196 4214 broken. Now special lines (!@,/) appear properly in the command
4197 4215 history after a log replay.
4198 4216
4199 4217 * Tried and failed to implement full session saving via pickle. My
4200 4218 idea was to pickle __main__.__dict__, but modules can't be
4201 4219 pickled. This would be a better alternative to replaying logs, but
4202 4220 seems quite tricky to get to work. Changed -session to be called
4203 4221 -logplay, which more accurately reflects what it does. And if we
4204 4222 ever get real session saving working, -session is now available.
4205 4223
4206 4224 * Implemented color schemes for prompts also. As for tracebacks,
4207 4225 currently only NoColor and Linux are supported. But now the
4208 4226 infrastructure is in place, based on a generic ColorScheme
4209 4227 class. So writing and activating new schemes both for the prompts
4210 4228 and the tracebacks should be straightforward.
4211 4229
4212 4230 * Version 0.1.13 released, 0.1.14 opened.
4213 4231
4214 4232 * Changed handling of options for output cache. Now counter is
4215 4233 hardwired starting at 1 and one specifies the maximum number of
4216 4234 entries *in the outcache* (not the max prompt counter). This is
4217 4235 much better, since many statements won't increase the cache
4218 4236 count. It also eliminated some confusing options, now there's only
4219 4237 one: cache_size.
4220 4238
4221 4239 * Added 'alias' magic function and magic_alias option in the
4222 4240 ipythonrc file. Now the user can easily define whatever names he
4223 4241 wants for the magic functions without having to play weird
4224 4242 namespace games. This gives IPython a real shell-like feel.
4225 4243
4226 4244 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4227 4245 @ or not).
4228 4246
4229 4247 This was one of the last remaining 'visible' bugs (that I know
4230 4248 of). I think if I can clean up the session loading so it works
4231 4249 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4232 4250 about licensing).
4233 4251
4234 4252 2001-11-25 Fernando Perez <fperez@colorado.edu>
4235 4253
4236 4254 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4237 4255 there's a cleaner distinction between what ? and ?? show.
4238 4256
4239 4257 * Added screen_length option. Now the user can define his own
4240 4258 screen size for page() operations.
4241 4259
4242 4260 * Implemented magic shell-like functions with automatic code
4243 4261 generation. Now adding another function is just a matter of adding
4244 4262 an entry to a dict, and the function is dynamically generated at
4245 4263 run-time. Python has some really cool features!
4246 4264
4247 4265 * Renamed many options to cleanup conventions a little. Now all
4248 4266 are lowercase, and only underscores where needed. Also in the code
4249 4267 option name tables are clearer.
4250 4268
4251 4269 * Changed prompts a little. Now input is 'In [n]:' instead of
4252 4270 'In[n]:='. This allows it the numbers to be aligned with the
4253 4271 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4254 4272 Python (it was a Mathematica thing). The '...' continuation prompt
4255 4273 was also changed a little to align better.
4256 4274
4257 4275 * Fixed bug when flushing output cache. Not all _p<n> variables
4258 4276 exist, so their deletion needs to be wrapped in a try:
4259 4277
4260 4278 * Figured out how to properly use inspect.formatargspec() (it
4261 4279 requires the args preceded by *). So I removed all the code from
4262 4280 _get_pdef in Magic, which was just replicating that.
4263 4281
4264 4282 * Added test to prefilter to allow redefining magic function names
4265 4283 as variables. This is ok, since the @ form is always available,
4266 4284 but whe should allow the user to define a variable called 'ls' if
4267 4285 he needs it.
4268 4286
4269 4287 * Moved the ToDo information from README into a separate ToDo.
4270 4288
4271 4289 * General code cleanup and small bugfixes. I think it's close to a
4272 4290 state where it can be released, obviously with a big 'beta'
4273 4291 warning on it.
4274 4292
4275 4293 * Got the magic function split to work. Now all magics are defined
4276 4294 in a separate class. It just organizes things a bit, and now
4277 4295 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4278 4296 was too long).
4279 4297
4280 4298 * Changed @clear to @reset to avoid potential confusions with
4281 4299 the shell command clear. Also renamed @cl to @clear, which does
4282 4300 exactly what people expect it to from their shell experience.
4283 4301
4284 4302 Added a check to the @reset command (since it's so
4285 4303 destructive, it's probably a good idea to ask for confirmation).
4286 4304 But now reset only works for full namespace resetting. Since the
4287 4305 del keyword is already there for deleting a few specific
4288 4306 variables, I don't see the point of having a redundant magic
4289 4307 function for the same task.
4290 4308
4291 4309 2001-11-24 Fernando Perez <fperez@colorado.edu>
4292 4310
4293 4311 * Updated the builtin docs (esp. the ? ones).
4294 4312
4295 4313 * Ran all the code through pychecker. Not terribly impressed with
4296 4314 it: lots of spurious warnings and didn't really find anything of
4297 4315 substance (just a few modules being imported and not used).
4298 4316
4299 4317 * Implemented the new ultraTB functionality into IPython. New
4300 4318 option: xcolors. This chooses color scheme. xmode now only selects
4301 4319 between Plain and Verbose. Better orthogonality.
4302 4320
4303 4321 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4304 4322 mode and color scheme for the exception handlers. Now it's
4305 4323 possible to have the verbose traceback with no coloring.
4306 4324
4307 4325 2001-11-23 Fernando Perez <fperez@colorado.edu>
4308 4326
4309 4327 * Version 0.1.12 released, 0.1.13 opened.
4310 4328
4311 4329 * Removed option to set auto-quote and auto-paren escapes by
4312 4330 user. The chances of breaking valid syntax are just too high. If
4313 4331 someone *really* wants, they can always dig into the code.
4314 4332
4315 4333 * Made prompt separators configurable.
4316 4334
4317 4335 2001-11-22 Fernando Perez <fperez@colorado.edu>
4318 4336
4319 4337 * Small bugfixes in many places.
4320 4338
4321 4339 * Removed the MyCompleter class from ipplib. It seemed redundant
4322 4340 with the C-p,C-n history search functionality. Less code to
4323 4341 maintain.
4324 4342
4325 4343 * Moved all the original ipython.py code into ipythonlib.py. Right
4326 4344 now it's just one big dump into a function called make_IPython, so
4327 4345 no real modularity has been gained. But at least it makes the
4328 4346 wrapper script tiny, and since ipythonlib is a module, it gets
4329 4347 compiled and startup is much faster.
4330 4348
4331 4349 This is a reasobably 'deep' change, so we should test it for a
4332 4350 while without messing too much more with the code.
4333 4351
4334 4352 2001-11-21 Fernando Perez <fperez@colorado.edu>
4335 4353
4336 4354 * Version 0.1.11 released, 0.1.12 opened for further work.
4337 4355
4338 4356 * Removed dependency on Itpl. It was only needed in one place. It
4339 4357 would be nice if this became part of python, though. It makes life
4340 4358 *a lot* easier in some cases.
4341 4359
4342 4360 * Simplified the prefilter code a bit. Now all handlers are
4343 4361 expected to explicitly return a value (at least a blank string).
4344 4362
4345 4363 * Heavy edits in ipplib. Removed the help system altogether. Now
4346 4364 obj?/?? is used for inspecting objects, a magic @doc prints
4347 4365 docstrings, and full-blown Python help is accessed via the 'help'
4348 4366 keyword. This cleans up a lot of code (less to maintain) and does
4349 4367 the job. Since 'help' is now a standard Python component, might as
4350 4368 well use it and remove duplicate functionality.
4351 4369
4352 4370 Also removed the option to use ipplib as a standalone program. By
4353 4371 now it's too dependent on other parts of IPython to function alone.
4354 4372
4355 4373 * Fixed bug in genutils.pager. It would crash if the pager was
4356 4374 exited immediately after opening (broken pipe).
4357 4375
4358 4376 * Trimmed down the VerboseTB reporting a little. The header is
4359 4377 much shorter now and the repeated exception arguments at the end
4360 4378 have been removed. For interactive use the old header seemed a bit
4361 4379 excessive.
4362 4380
4363 4381 * Fixed small bug in output of @whos for variables with multi-word
4364 4382 types (only first word was displayed).
4365 4383
4366 4384 2001-11-17 Fernando Perez <fperez@colorado.edu>
4367 4385
4368 4386 * Version 0.1.10 released, 0.1.11 opened for further work.
4369 4387
4370 4388 * Modified dirs and friends. dirs now *returns* the stack (not
4371 4389 prints), so one can manipulate it as a variable. Convenient to
4372 4390 travel along many directories.
4373 4391
4374 4392 * Fixed bug in magic_pdef: would only work with functions with
4375 4393 arguments with default values.
4376 4394
4377 4395 2001-11-14 Fernando Perez <fperez@colorado.edu>
4378 4396
4379 4397 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4380 4398 example with IPython. Various other minor fixes and cleanups.
4381 4399
4382 4400 * Version 0.1.9 released, 0.1.10 opened for further work.
4383 4401
4384 4402 * Added sys.path to the list of directories searched in the
4385 4403 execfile= option. It used to be the current directory and the
4386 4404 user's IPYTHONDIR only.
4387 4405
4388 4406 2001-11-13 Fernando Perez <fperez@colorado.edu>
4389 4407
4390 4408 * Reinstated the raw_input/prefilter separation that Janko had
4391 4409 initially. This gives a more convenient setup for extending the
4392 4410 pre-processor from the outside: raw_input always gets a string,
4393 4411 and prefilter has to process it. We can then redefine prefilter
4394 4412 from the outside and implement extensions for special
4395 4413 purposes.
4396 4414
4397 4415 Today I got one for inputting PhysicalQuantity objects
4398 4416 (from Scientific) without needing any function calls at
4399 4417 all. Extremely convenient, and it's all done as a user-level
4400 4418 extension (no IPython code was touched). Now instead of:
4401 4419 a = PhysicalQuantity(4.2,'m/s**2')
4402 4420 one can simply say
4403 4421 a = 4.2 m/s**2
4404 4422 or even
4405 4423 a = 4.2 m/s^2
4406 4424
4407 4425 I use this, but it's also a proof of concept: IPython really is
4408 4426 fully user-extensible, even at the level of the parsing of the
4409 4427 command line. It's not trivial, but it's perfectly doable.
4410 4428
4411 4429 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4412 4430 the problem of modules being loaded in the inverse order in which
4413 4431 they were defined in
4414 4432
4415 4433 * Version 0.1.8 released, 0.1.9 opened for further work.
4416 4434
4417 4435 * Added magics pdef, source and file. They respectively show the
4418 4436 definition line ('prototype' in C), source code and full python
4419 4437 file for any callable object. The object inspector oinfo uses
4420 4438 these to show the same information.
4421 4439
4422 4440 * Version 0.1.7 released, 0.1.8 opened for further work.
4423 4441
4424 4442 * Separated all the magic functions into a class called Magic. The
4425 4443 InteractiveShell class was becoming too big for Xemacs to handle
4426 4444 (de-indenting a line would lock it up for 10 seconds while it
4427 4445 backtracked on the whole class!)
4428 4446
4429 4447 FIXME: didn't work. It can be done, but right now namespaces are
4430 4448 all messed up. Do it later (reverted it for now, so at least
4431 4449 everything works as before).
4432 4450
4433 4451 * Got the object introspection system (magic_oinfo) working! I
4434 4452 think this is pretty much ready for release to Janko, so he can
4435 4453 test it for a while and then announce it. Pretty much 100% of what
4436 4454 I wanted for the 'phase 1' release is ready. Happy, tired.
4437 4455
4438 4456 2001-11-12 Fernando Perez <fperez@colorado.edu>
4439 4457
4440 4458 * Version 0.1.6 released, 0.1.7 opened for further work.
4441 4459
4442 4460 * Fixed bug in printing: it used to test for truth before
4443 4461 printing, so 0 wouldn't print. Now checks for None.
4444 4462
4445 4463 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4446 4464 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4447 4465 reaches by hand into the outputcache. Think of a better way to do
4448 4466 this later.
4449 4467
4450 4468 * Various small fixes thanks to Nathan's comments.
4451 4469
4452 4470 * Changed magic_pprint to magic_Pprint. This way it doesn't
4453 4471 collide with pprint() and the name is consistent with the command
4454 4472 line option.
4455 4473
4456 4474 * Changed prompt counter behavior to be fully like
4457 4475 Mathematica's. That is, even input that doesn't return a result
4458 4476 raises the prompt counter. The old behavior was kind of confusing
4459 4477 (getting the same prompt number several times if the operation
4460 4478 didn't return a result).
4461 4479
4462 4480 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4463 4481
4464 4482 * Fixed -Classic mode (wasn't working anymore).
4465 4483
4466 4484 * Added colored prompts using Nathan's new code. Colors are
4467 4485 currently hardwired, they can be user-configurable. For
4468 4486 developers, they can be chosen in file ipythonlib.py, at the
4469 4487 beginning of the CachedOutput class def.
4470 4488
4471 4489 2001-11-11 Fernando Perez <fperez@colorado.edu>
4472 4490
4473 4491 * Version 0.1.5 released, 0.1.6 opened for further work.
4474 4492
4475 4493 * Changed magic_env to *return* the environment as a dict (not to
4476 4494 print it). This way it prints, but it can also be processed.
4477 4495
4478 4496 * Added Verbose exception reporting to interactive
4479 4497 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4480 4498 traceback. Had to make some changes to the ultraTB file. This is
4481 4499 probably the last 'big' thing in my mental todo list. This ties
4482 4500 in with the next entry:
4483 4501
4484 4502 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4485 4503 has to specify is Plain, Color or Verbose for all exception
4486 4504 handling.
4487 4505
4488 4506 * Removed ShellServices option. All this can really be done via
4489 4507 the magic system. It's easier to extend, cleaner and has automatic
4490 4508 namespace protection and documentation.
4491 4509
4492 4510 2001-11-09 Fernando Perez <fperez@colorado.edu>
4493 4511
4494 4512 * Fixed bug in output cache flushing (missing parameter to
4495 4513 __init__). Other small bugs fixed (found using pychecker).
4496 4514
4497 4515 * Version 0.1.4 opened for bugfixing.
4498 4516
4499 4517 2001-11-07 Fernando Perez <fperez@colorado.edu>
4500 4518
4501 4519 * Version 0.1.3 released, mainly because of the raw_input bug.
4502 4520
4503 4521 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4504 4522 and when testing for whether things were callable, a call could
4505 4523 actually be made to certain functions. They would get called again
4506 4524 once 'really' executed, with a resulting double call. A disaster
4507 4525 in many cases (list.reverse() would never work!).
4508 4526
4509 4527 * Removed prefilter() function, moved its code to raw_input (which
4510 4528 after all was just a near-empty caller for prefilter). This saves
4511 4529 a function call on every prompt, and simplifies the class a tiny bit.
4512 4530
4513 4531 * Fix _ip to __ip name in magic example file.
4514 4532
4515 4533 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4516 4534 work with non-gnu versions of tar.
4517 4535
4518 4536 2001-11-06 Fernando Perez <fperez@colorado.edu>
4519 4537
4520 4538 * Version 0.1.2. Just to keep track of the recent changes.
4521 4539
4522 4540 * Fixed nasty bug in output prompt routine. It used to check 'if
4523 4541 arg != None...'. Problem is, this fails if arg implements a
4524 4542 special comparison (__cmp__) which disallows comparing to
4525 4543 None. Found it when trying to use the PhysicalQuantity module from
4526 4544 ScientificPython.
4527 4545
4528 4546 2001-11-05 Fernando Perez <fperez@colorado.edu>
4529 4547
4530 4548 * Also added dirs. Now the pushd/popd/dirs family functions
4531 4549 basically like the shell, with the added convenience of going home
4532 4550 when called with no args.
4533 4551
4534 4552 * pushd/popd slightly modified to mimic shell behavior more
4535 4553 closely.
4536 4554
4537 4555 * Added env,pushd,popd from ShellServices as magic functions. I
4538 4556 think the cleanest will be to port all desired functions from
4539 4557 ShellServices as magics and remove ShellServices altogether. This
4540 4558 will provide a single, clean way of adding functionality
4541 4559 (shell-type or otherwise) to IP.
4542 4560
4543 4561 2001-11-04 Fernando Perez <fperez@colorado.edu>
4544 4562
4545 4563 * Added .ipython/ directory to sys.path. This way users can keep
4546 4564 customizations there and access them via import.
4547 4565
4548 4566 2001-11-03 Fernando Perez <fperez@colorado.edu>
4549 4567
4550 4568 * Opened version 0.1.1 for new changes.
4551 4569
4552 4570 * Changed version number to 0.1.0: first 'public' release, sent to
4553 4571 Nathan and Janko.
4554 4572
4555 4573 * Lots of small fixes and tweaks.
4556 4574
4557 4575 * Minor changes to whos format. Now strings are shown, snipped if
4558 4576 too long.
4559 4577
4560 4578 * Changed ShellServices to work on __main__ so they show up in @who
4561 4579
4562 4580 * Help also works with ? at the end of a line:
4563 4581 ?sin and sin?
4564 4582 both produce the same effect. This is nice, as often I use the
4565 4583 tab-complete to find the name of a method, but I used to then have
4566 4584 to go to the beginning of the line to put a ? if I wanted more
4567 4585 info. Now I can just add the ? and hit return. Convenient.
4568 4586
4569 4587 2001-11-02 Fernando Perez <fperez@colorado.edu>
4570 4588
4571 4589 * Python version check (>=2.1) added.
4572 4590
4573 4591 * Added LazyPython documentation. At this point the docs are quite
4574 4592 a mess. A cleanup is in order.
4575 4593
4576 4594 * Auto-installer created. For some bizarre reason, the zipfiles
4577 4595 module isn't working on my system. So I made a tar version
4578 4596 (hopefully the command line options in various systems won't kill
4579 4597 me).
4580 4598
4581 4599 * Fixes to Struct in genutils. Now all dictionary-like methods are
4582 4600 protected (reasonably).
4583 4601
4584 4602 * Added pager function to genutils and changed ? to print usage
4585 4603 note through it (it was too long).
4586 4604
4587 4605 * Added the LazyPython functionality. Works great! I changed the
4588 4606 auto-quote escape to ';', it's on home row and next to '. But
4589 4607 both auto-quote and auto-paren (still /) escapes are command-line
4590 4608 parameters.
4591 4609
4592 4610
4593 4611 2001-11-01 Fernando Perez <fperez@colorado.edu>
4594 4612
4595 4613 * Version changed to 0.0.7. Fairly large change: configuration now
4596 4614 is all stored in a directory, by default .ipython. There, all
4597 4615 config files have normal looking names (not .names)
4598 4616
4599 4617 * Version 0.0.6 Released first to Lucas and Archie as a test
4600 4618 run. Since it's the first 'semi-public' release, change version to
4601 4619 > 0.0.6 for any changes now.
4602 4620
4603 4621 * Stuff I had put in the ipplib.py changelog:
4604 4622
4605 4623 Changes to InteractiveShell:
4606 4624
4607 4625 - Made the usage message a parameter.
4608 4626
4609 4627 - Require the name of the shell variable to be given. It's a bit
4610 4628 of a hack, but allows the name 'shell' not to be hardwire in the
4611 4629 magic (@) handler, which is problematic b/c it requires
4612 4630 polluting the global namespace with 'shell'. This in turn is
4613 4631 fragile: if a user redefines a variable called shell, things
4614 4632 break.
4615 4633
4616 4634 - magic @: all functions available through @ need to be defined
4617 4635 as magic_<name>, even though they can be called simply as
4618 4636 @<name>. This allows the special command @magic to gather
4619 4637 information automatically about all existing magic functions,
4620 4638 even if they are run-time user extensions, by parsing the shell
4621 4639 instance __dict__ looking for special magic_ names.
4622 4640
4623 4641 - mainloop: added *two* local namespace parameters. This allows
4624 4642 the class to differentiate between parameters which were there
4625 4643 before and after command line initialization was processed. This
4626 4644 way, later @who can show things loaded at startup by the
4627 4645 user. This trick was necessary to make session saving/reloading
4628 4646 really work: ideally after saving/exiting/reloading a session,
4629 4647 *everythin* should look the same, including the output of @who. I
4630 4648 was only able to make this work with this double namespace
4631 4649 trick.
4632 4650
4633 4651 - added a header to the logfile which allows (almost) full
4634 4652 session restoring.
4635 4653
4636 4654 - prepend lines beginning with @ or !, with a and log
4637 4655 them. Why? !lines: may be useful to know what you did @lines:
4638 4656 they may affect session state. So when restoring a session, at
4639 4657 least inform the user of their presence. I couldn't quite get
4640 4658 them to properly re-execute, but at least the user is warned.
4641 4659
4642 4660 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now