##// END OF EJS Templates
- Add a new ipconfig() public function for manipulating the internal rc...
fptest -
Show More
@@ -1,3021 +1,3070 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 1846 2006-10-28 07:51:56Z vivainio $"""
4 $Id: Magic.py 1879 2006-11-04 00:34:34Z fptest $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2006 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 import textwrap
35 35 from cStringIO import StringIO
36 36 from getopt import getopt,GetoptError
37 37 from pprint import pprint, pformat
38 38
39 39 # profile isn't bundled by default in Debian for license reasons
40 40 try:
41 41 import profile,pstats
42 42 except ImportError:
43 43 profile = pstats = None
44 44
45 45 # Homebrewed
46 46 import IPython
47 47 from IPython import Debugger, OInspect, wildcard
48 48 from IPython.FakeModule import FakeModule
49 49 from IPython.Itpl import Itpl, itpl, printpl,itplns
50 50 from IPython.PyColorize import Parser
51 51 from IPython.ipstruct import Struct
52 52 from IPython.macro import Macro
53 53 from IPython.genutils import *
54 54 from IPython import platutils
55 55
56 56 #***************************************************************************
57 57 # Utility functions
58 58 def on_off(tag):
59 59 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
60 60 return ['OFF','ON'][tag]
61 61
62 62 class Bunch: pass
63 63
64 64 #***************************************************************************
65 65 # Main class implementing Magic functionality
66 66 class Magic:
67 67 """Magic functions for InteractiveShell.
68 68
69 69 Shell functions which can be reached as %function_name. All magic
70 70 functions should accept a string, which they can parse for their own
71 71 needs. This can make some functions easier to type, eg `%cd ../`
72 72 vs. `%cd("../")`
73 73
74 74 ALL definitions MUST begin with the prefix magic_. The user won't need it
75 75 at the command line, but it is is needed in the definition. """
76 76
77 77 # class globals
78 78 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
79 79 'Automagic is ON, % prefix NOT needed for magic functions.']
80 80
81 81 #......................................................................
82 82 # some utility functions
83 83
84 84 def __init__(self,shell):
85 85
86 86 self.options_table = {}
87 87 if profile is None:
88 88 self.magic_prun = self.profile_missing_notice
89 89 self.shell = shell
90 90
91 91 # namespace for holding state we may need
92 92 self._magic_state = Bunch()
93 93
94 94 def profile_missing_notice(self, *args, **kwargs):
95 95 error("""\
96 96 The profile module could not be found. If you are a Debian user,
97 97 it has been removed from the standard Debian package because of its non-free
98 98 license. To use profiling, please install"python2.3-profiler" from non-free.""")
99 99
100 100 def default_option(self,fn,optstr):
101 101 """Make an entry in the options_table for fn, with value optstr"""
102 102
103 103 if fn not in self.lsmagic():
104 104 error("%s is not a magic function" % fn)
105 105 self.options_table[fn] = optstr
106 106
107 107 def lsmagic(self):
108 108 """Return a list of currently available magic functions.
109 109
110 110 Gives a list of the bare names after mangling (['ls','cd', ...], not
111 111 ['magic_ls','magic_cd',...]"""
112 112
113 113 # FIXME. This needs a cleanup, in the way the magics list is built.
114 114
115 115 # magics in class definition
116 116 class_magic = lambda fn: fn.startswith('magic_') and \
117 117 callable(Magic.__dict__[fn])
118 118 # in instance namespace (run-time user additions)
119 119 inst_magic = lambda fn: fn.startswith('magic_') and \
120 120 callable(self.__dict__[fn])
121 121 # and bound magics by user (so they can access self):
122 122 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
123 123 callable(self.__class__.__dict__[fn])
124 124 magics = filter(class_magic,Magic.__dict__.keys()) + \
125 125 filter(inst_magic,self.__dict__.keys()) + \
126 126 filter(inst_bound_magic,self.__class__.__dict__.keys())
127 127 out = []
128 128 for fn in magics:
129 129 out.append(fn.replace('magic_','',1))
130 130 out.sort()
131 131 return out
132 132
133 133 def extract_input_slices(self,slices,raw=False):
134 134 """Return as a string a set of input history slices.
135 135
136 136 Inputs:
137 137
138 138 - slices: the set of slices is given as a list of strings (like
139 139 ['1','4:8','9'], since this function is for use by magic functions
140 140 which get their arguments as strings.
141 141
142 142 Optional inputs:
143 143
144 144 - raw(False): by default, the processed input is used. If this is
145 145 true, the raw input history is used instead.
146 146
147 147 Note that slices can be called with two notations:
148 148
149 149 N:M -> standard python form, means including items N...(M-1).
150 150
151 151 N-M -> include items N..M (closed endpoint)."""
152 152
153 153 if raw:
154 154 hist = self.shell.input_hist_raw
155 155 else:
156 156 hist = self.shell.input_hist
157 157
158 158 cmds = []
159 159 for chunk in slices:
160 160 if ':' in chunk:
161 161 ini,fin = map(int,chunk.split(':'))
162 162 elif '-' in chunk:
163 163 ini,fin = map(int,chunk.split('-'))
164 164 fin += 1
165 165 else:
166 166 ini = int(chunk)
167 167 fin = ini+1
168 168 cmds.append(hist[ini:fin])
169 169 return cmds
170 170
171 171 def _ofind(self, oname, namespaces=None):
172 172 """Find an object in the available namespaces.
173 173
174 174 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
175 175
176 176 Has special code to detect magic functions.
177 177 """
178 178
179 179 oname = oname.strip()
180 180
181 181 alias_ns = None
182 182 if namespaces is None:
183 183 # Namespaces to search in:
184 184 # Put them in a list. The order is important so that we
185 185 # find things in the same order that Python finds them.
186 186 namespaces = [ ('Interactive', self.shell.user_ns),
187 187 ('IPython internal', self.shell.internal_ns),
188 188 ('Python builtin', __builtin__.__dict__),
189 189 ('Alias', self.shell.alias_table),
190 190 ]
191 191 alias_ns = self.shell.alias_table
192 192
193 193 # initialize results to 'null'
194 194 found = 0; obj = None; ospace = None; ds = None;
195 195 ismagic = 0; isalias = 0; parent = None
196 196
197 197 # Look for the given name by splitting it in parts. If the head is
198 198 # found, then we look for all the remaining parts as members, and only
199 199 # declare success if we can find them all.
200 200 oname_parts = oname.split('.')
201 201 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
202 202 for nsname,ns in namespaces:
203 203 try:
204 204 obj = ns[oname_head]
205 205 except KeyError:
206 206 continue
207 207 else:
208 208 for part in oname_rest:
209 209 try:
210 210 parent = obj
211 211 obj = getattr(obj,part)
212 212 except:
213 213 # Blanket except b/c some badly implemented objects
214 214 # allow __getattr__ to raise exceptions other than
215 215 # AttributeError, which then crashes IPython.
216 216 break
217 217 else:
218 218 # If we finish the for loop (no break), we got all members
219 219 found = 1
220 220 ospace = nsname
221 221 if ns == alias_ns:
222 222 isalias = 1
223 223 break # namespace loop
224 224
225 225 # Try to see if it's magic
226 226 if not found:
227 227 if oname.startswith(self.shell.ESC_MAGIC):
228 228 oname = oname[1:]
229 229 obj = getattr(self,'magic_'+oname,None)
230 230 if obj is not None:
231 231 found = 1
232 232 ospace = 'IPython internal'
233 233 ismagic = 1
234 234
235 235 # Last try: special-case some literals like '', [], {}, etc:
236 236 if not found and oname_head in ["''",'""','[]','{}','()']:
237 237 obj = eval(oname_head)
238 238 found = 1
239 239 ospace = 'Interactive'
240 240
241 241 return {'found':found, 'obj':obj, 'namespace':ospace,
242 242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
243 243
244 244 def arg_err(self,func):
245 245 """Print docstring if incorrect arguments were passed"""
246 246 print 'Error in arguments:'
247 247 print OInspect.getdoc(func)
248 248
249 249 def format_latex(self,strng):
250 250 """Format a string for latex inclusion."""
251 251
252 252 # Characters that need to be escaped for latex:
253 253 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
254 254 # Magic command names as headers:
255 255 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
256 256 re.MULTILINE)
257 257 # Magic commands
258 258 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
259 259 re.MULTILINE)
260 260 # Paragraph continue
261 261 par_re = re.compile(r'\\$',re.MULTILINE)
262 262
263 263 # The "\n" symbol
264 264 newline_re = re.compile(r'\\n')
265 265
266 266 # Now build the string for output:
267 267 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
268 268 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
269 269 strng)
270 270 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
271 271 strng = par_re.sub(r'\\\\',strng)
272 272 strng = escape_re.sub(r'\\\1',strng)
273 273 strng = newline_re.sub(r'\\textbackslash{}n',strng)
274 274 return strng
275 275
276 276 def format_screen(self,strng):
277 277 """Format a string for screen printing.
278 278
279 279 This removes some latex-type format codes."""
280 280 # Paragraph continue
281 281 par_re = re.compile(r'\\$',re.MULTILINE)
282 282 strng = par_re.sub('',strng)
283 283 return strng
284 284
285 285 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
286 286 """Parse options passed to an argument string.
287 287
288 288 The interface is similar to that of getopt(), but it returns back a
289 289 Struct with the options as keys and the stripped argument string still
290 290 as a string.
291 291
292 292 arg_str is quoted as a true sys.argv vector by using shlex.split.
293 293 This allows us to easily expand variables, glob files, quote
294 294 arguments, etc.
295 295
296 296 Options:
297 297 -mode: default 'string'. If given as 'list', the argument string is
298 298 returned as a list (split on whitespace) instead of a string.
299 299
300 300 -list_all: put all option values in lists. Normally only options
301 301 appearing more than once are put in a list.
302 302
303 303 -posix (True): whether to split the input line in POSIX mode or not,
304 304 as per the conventions outlined in the shlex module from the
305 305 standard library."""
306 306
307 307 # inject default options at the beginning of the input line
308 308 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
309 309 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
310 310
311 311 mode = kw.get('mode','string')
312 312 if mode not in ['string','list']:
313 313 raise ValueError,'incorrect mode given: %s' % mode
314 314 # Get options
315 315 list_all = kw.get('list_all',0)
316 316 posix = kw.get('posix',True)
317 317
318 318 # Check if we have more than one argument to warrant extra processing:
319 319 odict = {} # Dictionary with options
320 320 args = arg_str.split()
321 321 if len(args) >= 1:
322 322 # If the list of inputs only has 0 or 1 thing in it, there's no
323 323 # need to look for options
324 324 argv = arg_split(arg_str,posix)
325 325 # Do regular option processing
326 326 try:
327 327 opts,args = getopt(argv,opt_str,*long_opts)
328 328 except GetoptError,e:
329 329 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
330 330 " ".join(long_opts)))
331 331 for o,a in opts:
332 332 if o.startswith('--'):
333 333 o = o[2:]
334 334 else:
335 335 o = o[1:]
336 336 try:
337 337 odict[o].append(a)
338 338 except AttributeError:
339 339 odict[o] = [odict[o],a]
340 340 except KeyError:
341 341 if list_all:
342 342 odict[o] = [a]
343 343 else:
344 344 odict[o] = a
345 345
346 346 # Prepare opts,args for return
347 347 opts = Struct(odict)
348 348 if mode == 'string':
349 349 args = ' '.join(args)
350 350
351 351 return opts,args
352 352
353 353 #......................................................................
354 354 # And now the actual magic functions
355 355
356 356 # Functions for IPython shell work (vars,funcs, config, etc)
357 357 def magic_lsmagic(self, parameter_s = ''):
358 358 """List currently available magic functions."""
359 359 mesc = self.shell.ESC_MAGIC
360 360 print 'Available magic functions:\n'+mesc+\
361 361 (' '+mesc).join(self.lsmagic())
362 362 print '\n' + Magic.auto_status[self.shell.rc.automagic]
363 363 return None
364 364
365 365 def magic_magic(self, parameter_s = ''):
366 366 """Print information about the magic function system."""
367 367
368 368 mode = ''
369 369 try:
370 370 if parameter_s.split()[0] == '-latex':
371 371 mode = 'latex'
372 372 if parameter_s.split()[0] == '-brief':
373 373 mode = 'brief'
374 374 except:
375 375 pass
376 376
377 377 magic_docs = []
378 378 for fname in self.lsmagic():
379 379 mname = 'magic_' + fname
380 380 for space in (Magic,self,self.__class__):
381 381 try:
382 382 fn = space.__dict__[mname]
383 383 except KeyError:
384 384 pass
385 385 else:
386 386 break
387 387 if mode == 'brief':
388 388 # only first line
389 389 fndoc = fn.__doc__.split('\n',1)[0]
390 390 else:
391 391 fndoc = fn.__doc__
392 392
393 393 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
394 394 fname,fndoc))
395 395 magic_docs = ''.join(magic_docs)
396 396
397 397 if mode == 'latex':
398 398 print self.format_latex(magic_docs)
399 399 return
400 400 else:
401 401 magic_docs = self.format_screen(magic_docs)
402 402 if mode == 'brief':
403 403 return magic_docs
404 404
405 405 outmsg = """
406 406 IPython's 'magic' functions
407 407 ===========================
408 408
409 409 The magic function system provides a series of functions which allow you to
410 410 control the behavior of IPython itself, plus a lot of system-type
411 411 features. All these functions are prefixed with a % character, but parameters
412 412 are given without parentheses or quotes.
413 413
414 414 NOTE: If you have 'automagic' enabled (via the command line option or with the
415 415 %automagic function), you don't need to type in the % explicitly. By default,
416 416 IPython ships with automagic on, so you should only rarely need the % escape.
417 417
418 418 Example: typing '%cd mydir' (without the quotes) changes you working directory
419 419 to 'mydir', if it exists.
420 420
421 421 You can define your own magic functions to extend the system. See the supplied
422 422 ipythonrc and example-magic.py files for details (in your ipython
423 423 configuration directory, typically $HOME/.ipython/).
424 424
425 425 You can also define your own aliased names for magic functions. In your
426 426 ipythonrc file, placing a line like:
427 427
428 428 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
429 429
430 430 will define %pf as a new name for %profile.
431 431
432 432 You can also call magics in code using the ipmagic() function, which IPython
433 433 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
434 434
435 435 For a list of the available magic functions, use %lsmagic. For a description
436 436 of any of them, type %magic_name?, e.g. '%cd?'.
437 437
438 438 Currently the magic system has the following functions:\n"""
439 439
440 440 mesc = self.shell.ESC_MAGIC
441 441 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
442 442 "\n\n%s%s\n\n%s" % (outmsg,
443 443 magic_docs,mesc,mesc,
444 444 (' '+mesc).join(self.lsmagic()),
445 445 Magic.auto_status[self.shell.rc.automagic] ) )
446 446
447 447 page(outmsg,screen_lines=self.shell.rc.screen_length)
448 448
449 449 def magic_automagic(self, parameter_s = ''):
450 450 """Make magic functions callable without having to type the initial %.
451 451
452 452 Toggles on/off (when off, you must call it as %automagic, of
453 453 course). Note that magic functions have lowest priority, so if there's
454 454 a variable whose name collides with that of a magic fn, automagic
455 455 won't work for that function (you get the variable instead). However,
456 456 if you delete the variable (del var), the previously shadowed magic
457 457 function becomes visible to automagic again."""
458 458
459 459 rc = self.shell.rc
460 460 rc.automagic = not rc.automagic
461 461 print '\n' + Magic.auto_status[rc.automagic]
462 462
463 463 def magic_autocall(self, parameter_s = ''):
464 464 """Make functions callable without having to type parentheses.
465 465
466 466 Usage:
467 467
468 468 %autocall [mode]
469 469
470 470 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
471 471 value is toggled on and off (remembering the previous state)."""
472 472
473 473 rc = self.shell.rc
474 474
475 475 if parameter_s:
476 476 arg = int(parameter_s)
477 477 else:
478 478 arg = 'toggle'
479 479
480 480 if not arg in (0,1,2,'toggle'):
481 481 error('Valid modes: (0->Off, 1->Smart, 2->Full')
482 482 return
483 483
484 484 if arg in (0,1,2):
485 485 rc.autocall = arg
486 486 else: # toggle
487 487 if rc.autocall:
488 488 self._magic_state.autocall_save = rc.autocall
489 489 rc.autocall = 0
490 490 else:
491 491 try:
492 492 rc.autocall = self._magic_state.autocall_save
493 493 except AttributeError:
494 494 rc.autocall = self._magic_state.autocall_save = 1
495 495
496 496 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
497 497
498 498 def magic_autoindent(self, parameter_s = ''):
499 499 """Toggle autoindent on/off (if available)."""
500 500
501 501 self.shell.set_autoindent()
502 502 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
503 503
504 504 def magic_system_verbose(self, parameter_s = ''):
505 """Toggle verbose printing of system calls on/off."""
505 """Set verbose printing of system calls.
506 506
507 self.shell.rc_set_toggle('system_verbose')
507 If called without an argument, act as a toggle"""
508
509 if parameter_s:
510 val = bool(eval(parameter_s))
511 else:
512 val = None
513
514 self.shell.rc_set_toggle('system_verbose',val)
508 515 print "System verbose printing is:",\
509 516 ['OFF','ON'][self.shell.rc.system_verbose]
510 517
511 518 def magic_history(self, parameter_s = ''):
512 519 """Print input history (_i<n> variables), with most recent last.
513 520
514 %history -> print at most 40 inputs (some may be multi-line)\\
521 %history -> print at most 40 inputs (some may be multi-line)\\
515 522 %history n -> print at most n inputs\\
516 523 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
517 524
518 525 Each input's number <n> is shown, and is accessible as the
519 526 automatically generated variable _i<n>. Multi-line statements are
520 527 printed starting at a new line for easy copy/paste.
521 528
522 529
523 530 Options:
524 531
525 532 -n: do NOT print line numbers. This is useful if you want to get a
526 533 printout of many lines which can be directly pasted into a text
527 534 editor.
528 535
529 536 This feature is only available if numbered prompts are in use.
530 537
531 538 -r: print the 'raw' history. IPython filters your input and
532 539 converts it all into valid Python source before executing it (things
533 540 like magics or aliases are turned into function calls, for
534 541 example). With this option, you'll see the unfiltered history
535 542 instead of the filtered version: '%cd /' will be seen as '%cd /'
536 543 instead of '_ip.magic("%cd /")'.
537 544 """
538 545
539 546 shell = self.shell
540 547 if not shell.outputcache.do_full_cache:
541 548 print 'This feature is only available if numbered prompts are in use.'
542 549 return
543 550 opts,args = self.parse_options(parameter_s,'nr',mode='list')
544 551
545 552 if opts.has_key('r'):
546 553 input_hist = shell.input_hist_raw
547 554 else:
548 555 input_hist = shell.input_hist
549 556
550 557 default_length = 40
551 558 if len(args) == 0:
552 559 final = len(input_hist)
553 560 init = max(1,final-default_length)
554 561 elif len(args) == 1:
555 562 final = len(input_hist)
556 563 init = max(1,final-int(args[0]))
557 564 elif len(args) == 2:
558 565 init,final = map(int,args)
559 566 else:
560 567 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
561 568 print self.magic_hist.__doc__
562 569 return
563 570 width = len(str(final))
564 571 line_sep = ['','\n']
565 572 print_nums = not opts.has_key('n')
566 573 for in_num in range(init,final):
567 574 inline = input_hist[in_num]
568 575 multiline = int(inline.count('\n') > 1)
569 576 if print_nums:
570 577 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
571 578 print inline,
572 579
573 580 def magic_hist(self, parameter_s=''):
574 581 """Alternate name for %history."""
575 582 return self.magic_history(parameter_s)
576 583
577 584 def magic_p(self, parameter_s=''):
578 585 """Just a short alias for Python's 'print'."""
579 586 exec 'print ' + parameter_s in self.shell.user_ns
580 587
581 588 def magic_r(self, parameter_s=''):
582 589 """Repeat previous input.
583 590
584 591 If given an argument, repeats the previous command which starts with
585 592 the same string, otherwise it just repeats the previous input.
586 593
587 594 Shell escaped commands (with ! as first character) are not recognized
588 595 by this system, only pure python code and magic commands.
589 596 """
590 597
591 598 start = parameter_s.strip()
592 599 esc_magic = self.shell.ESC_MAGIC
593 600 # Identify magic commands even if automagic is on (which means
594 601 # the in-memory version is different from that typed by the user).
595 602 if self.shell.rc.automagic:
596 603 start_magic = esc_magic+start
597 604 else:
598 605 start_magic = start
599 606 # Look through the input history in reverse
600 607 for n in range(len(self.shell.input_hist)-2,0,-1):
601 608 input = self.shell.input_hist[n]
602 609 # skip plain 'r' lines so we don't recurse to infinity
603 610 if input != '_ip.magic("r")\n' and \
604 611 (input.startswith(start) or input.startswith(start_magic)):
605 612 #print 'match',`input` # dbg
606 613 print 'Executing:',input,
607 614 self.shell.runlines(input)
608 615 return
609 616 print 'No previous input matching `%s` found.' % start
610 617
611 618 def magic_page(self, parameter_s=''):
612 619 """Pretty print the object and display it through a pager.
613 620
614 621 If no parameter is given, use _ (last output)."""
615 622 # After a function contributed by Olivier Aubert, slightly modified.
616 623
617 624 oname = parameter_s and parameter_s or '_'
618 625 info = self._ofind(oname)
619 626 if info['found']:
620 627 page(pformat(info['obj']))
621 628 else:
622 629 print 'Object `%s` not found' % oname
623 630
624 631 def magic_profile(self, parameter_s=''):
625 632 """Print your currently active IPyhton profile."""
626 633 if self.shell.rc.profile:
627 634 printpl('Current IPython profile: $self.shell.rc.profile.')
628 635 else:
629 636 print 'No profile active.'
630 637
631 638 def _inspect(self,meth,oname,namespaces=None,**kw):
632 639 """Generic interface to the inspector system.
633 640
634 641 This function is meant to be called by pdef, pdoc & friends."""
635 642
636 643 oname = oname.strip()
637 644 info = Struct(self._ofind(oname, namespaces))
638 645
639 646 if info.found:
640 647 # Get the docstring of the class property if it exists.
641 648 path = oname.split('.')
642 649 root = '.'.join(path[:-1])
643 650 if info.parent is not None:
644 651 try:
645 652 target = getattr(info.parent, '__class__')
646 653 # The object belongs to a class instance.
647 654 try:
648 655 target = getattr(target, path[-1])
649 656 # The class defines the object.
650 657 if isinstance(target, property):
651 658 oname = root + '.__class__.' + path[-1]
652 659 info = Struct(self._ofind(oname))
653 660 except AttributeError: pass
654 661 except AttributeError: pass
655 662
656 663 pmethod = getattr(self.shell.inspector,meth)
657 664 formatter = info.ismagic and self.format_screen or None
658 665 if meth == 'pdoc':
659 666 pmethod(info.obj,oname,formatter)
660 667 elif meth == 'pinfo':
661 668 pmethod(info.obj,oname,formatter,info,**kw)
662 669 else:
663 670 pmethod(info.obj,oname)
664 671 else:
665 672 print 'Object `%s` not found.' % oname
666 673 return 'not found' # so callers can take other action
667 674
668 675 def magic_pdef(self, parameter_s='', namespaces=None):
669 676 """Print the definition header for any callable object.
670 677
671 678 If the object is a class, print the constructor information."""
672 679 print "+++"
673 680 self._inspect('pdef',parameter_s, namespaces)
674 681
675 682 def magic_pdoc(self, parameter_s='', namespaces=None):
676 683 """Print the docstring for an object.
677 684
678 685 If the given object is a class, it will print both the class and the
679 686 constructor docstrings."""
680 687 self._inspect('pdoc',parameter_s, namespaces)
681 688
682 689 def magic_psource(self, parameter_s='', namespaces=None):
683 690 """Print (or run through pager) the source code for an object."""
684 691 self._inspect('psource',parameter_s, namespaces)
685 692
686 693 def magic_pfile(self, parameter_s=''):
687 694 """Print (or run through pager) the file where an object is defined.
688 695
689 696 The file opens at the line where the object definition begins. IPython
690 697 will honor the environment variable PAGER if set, and otherwise will
691 698 do its best to print the file in a convenient form.
692 699
693 700 If the given argument is not an object currently defined, IPython will
694 701 try to interpret it as a filename (automatically adding a .py extension
695 702 if needed). You can thus use %pfile as a syntax highlighting code
696 703 viewer."""
697 704
698 705 # first interpret argument as an object name
699 706 out = self._inspect('pfile',parameter_s)
700 707 # if not, try the input as a filename
701 708 if out == 'not found':
702 709 try:
703 710 filename = get_py_filename(parameter_s)
704 711 except IOError,msg:
705 712 print msg
706 713 return
707 714 page(self.shell.inspector.format(file(filename).read()))
708 715
709 716 def magic_pinfo(self, parameter_s='', namespaces=None):
710 717 """Provide detailed information about an object.
711 718
712 719 '%pinfo object' is just a synonym for object? or ?object."""
713 720
714 721 #print 'pinfo par: <%s>' % parameter_s # dbg
715 722
716 723 # detail_level: 0 -> obj? , 1 -> obj??
717 724 detail_level = 0
718 725 # We need to detect if we got called as 'pinfo pinfo foo', which can
719 726 # happen if the user types 'pinfo foo?' at the cmd line.
720 727 pinfo,qmark1,oname,qmark2 = \
721 728 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
722 729 if pinfo or qmark1 or qmark2:
723 730 detail_level = 1
724 731 if "*" in oname:
725 732 self.magic_psearch(oname)
726 733 else:
727 734 self._inspect('pinfo', oname, detail_level=detail_level,
728 735 namespaces=namespaces)
729 736
730 737 def magic_psearch(self, parameter_s=''):
731 738 """Search for object in namespaces by wildcard.
732 739
733 740 %psearch [options] PATTERN [OBJECT TYPE]
734 741
735 742 Note: ? can be used as a synonym for %psearch, at the beginning or at
736 743 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
737 744 rest of the command line must be unchanged (options come first), so
738 745 for example the following forms are equivalent
739 746
740 747 %psearch -i a* function
741 748 -i a* function?
742 749 ?-i a* function
743 750
744 751 Arguments:
745 752
746 753 PATTERN
747 754
748 755 where PATTERN is a string containing * as a wildcard similar to its
749 756 use in a shell. The pattern is matched in all namespaces on the
750 757 search path. By default objects starting with a single _ are not
751 758 matched, many IPython generated objects have a single
752 759 underscore. The default is case insensitive matching. Matching is
753 760 also done on the attributes of objects and not only on the objects
754 761 in a module.
755 762
756 763 [OBJECT TYPE]
757 764
758 765 Is the name of a python type from the types module. The name is
759 766 given in lowercase without the ending type, ex. StringType is
760 767 written string. By adding a type here only objects matching the
761 768 given type are matched. Using all here makes the pattern match all
762 769 types (this is the default).
763 770
764 771 Options:
765 772
766 773 -a: makes the pattern match even objects whose names start with a
767 774 single underscore. These names are normally ommitted from the
768 775 search.
769 776
770 777 -i/-c: make the pattern case insensitive/sensitive. If neither of
771 778 these options is given, the default is read from your ipythonrc
772 779 file. The option name which sets this value is
773 780 'wildcards_case_sensitive'. If this option is not specified in your
774 781 ipythonrc file, IPython's internal default is to do a case sensitive
775 782 search.
776 783
777 784 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
778 785 specifiy can be searched in any of the following namespaces:
779 786 'builtin', 'user', 'user_global','internal', 'alias', where
780 787 'builtin' and 'user' are the search defaults. Note that you should
781 788 not use quotes when specifying namespaces.
782 789
783 790 'Builtin' contains the python module builtin, 'user' contains all
784 791 user data, 'alias' only contain the shell aliases and no python
785 792 objects, 'internal' contains objects used by IPython. The
786 793 'user_global' namespace is only used by embedded IPython instances,
787 794 and it contains module-level globals. You can add namespaces to the
788 795 search with -s or exclude them with -e (these options can be given
789 796 more than once).
790 797
791 798 Examples:
792 799
793 800 %psearch a* -> objects beginning with an a
794 801 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
795 802 %psearch a* function -> all functions beginning with an a
796 803 %psearch re.e* -> objects beginning with an e in module re
797 804 %psearch r*.e* -> objects that start with e in modules starting in r
798 805 %psearch r*.* string -> all strings in modules beginning with r
799 806
800 807 Case sensitve search:
801 808
802 809 %psearch -c a* list all object beginning with lower case a
803 810
804 811 Show objects beginning with a single _:
805 812
806 813 %psearch -a _* list objects beginning with a single underscore"""
807 814
808 815 # default namespaces to be searched
809 816 def_search = ['user','builtin']
810 817
811 818 # Process options/args
812 819 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
813 820 opt = opts.get
814 821 shell = self.shell
815 822 psearch = shell.inspector.psearch
816 823
817 824 # select case options
818 825 if opts.has_key('i'):
819 826 ignore_case = True
820 827 elif opts.has_key('c'):
821 828 ignore_case = False
822 829 else:
823 830 ignore_case = not shell.rc.wildcards_case_sensitive
824 831
825 832 # Build list of namespaces to search from user options
826 833 def_search.extend(opt('s',[]))
827 834 ns_exclude = ns_exclude=opt('e',[])
828 835 ns_search = [nm for nm in def_search if nm not in ns_exclude]
829 836
830 837 # Call the actual search
831 838 try:
832 839 psearch(args,shell.ns_table,ns_search,
833 840 show_all=opt('a'),ignore_case=ignore_case)
834 841 except:
835 842 shell.showtraceback()
836 843
837 844 def magic_who_ls(self, parameter_s=''):
838 845 """Return a sorted list of all interactive variables.
839 846
840 847 If arguments are given, only variables of types matching these
841 848 arguments are returned."""
842 849
843 850 user_ns = self.shell.user_ns
844 851 internal_ns = self.shell.internal_ns
845 852 user_config_ns = self.shell.user_config_ns
846 853 out = []
847 854 typelist = parameter_s.split()
848 855
849 856 for i in user_ns:
850 857 if not (i.startswith('_') or i.startswith('_i')) \
851 858 and not (i in internal_ns or i in user_config_ns):
852 859 if typelist:
853 860 if type(user_ns[i]).__name__ in typelist:
854 861 out.append(i)
855 862 else:
856 863 out.append(i)
857 864 out.sort()
858 865 return out
859 866
860 867 def magic_who(self, parameter_s=''):
861 868 """Print all interactive variables, with some minimal formatting.
862 869
863 870 If any arguments are given, only variables whose type matches one of
864 871 these are printed. For example:
865 872
866 873 %who function str
867 874
868 875 will only list functions and strings, excluding all other types of
869 876 variables. To find the proper type names, simply use type(var) at a
870 877 command line to see how python prints type names. For example:
871 878
872 879 In [1]: type('hello')\\
873 880 Out[1]: <type 'str'>
874 881
875 882 indicates that the type name for strings is 'str'.
876 883
877 884 %who always excludes executed names loaded through your configuration
878 885 file and things which are internal to IPython.
879 886
880 887 This is deliberate, as typically you may load many modules and the
881 888 purpose of %who is to show you only what you've manually defined."""
882 889
883 890 varlist = self.magic_who_ls(parameter_s)
884 891 if not varlist:
885 892 print 'Interactive namespace is empty.'
886 893 return
887 894
888 895 # if we have variables, move on...
889 896
890 897 # stupid flushing problem: when prompts have no separators, stdout is
891 898 # getting lost. I'm starting to think this is a python bug. I'm having
892 899 # to force a flush with a print because even a sys.stdout.flush
893 900 # doesn't seem to do anything!
894 901
895 902 count = 0
896 903 for i in varlist:
897 904 print i+'\t',
898 905 count += 1
899 906 if count > 8:
900 907 count = 0
901 908 print
902 909 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
903 910
904 911 print # well, this does force a flush at the expense of an extra \n
905 912
906 913 def magic_whos(self, parameter_s=''):
907 914 """Like %who, but gives some extra information about each variable.
908 915
909 916 The same type filtering of %who can be applied here.
910 917
911 918 For all variables, the type is printed. Additionally it prints:
912 919
913 920 - For {},[],(): their length.
914 921
915 922 - For Numeric arrays, a summary with shape, number of elements,
916 923 typecode and size in memory.
917 924
918 925 - Everything else: a string representation, snipping their middle if
919 926 too long."""
920 927
921 928 varnames = self.magic_who_ls(parameter_s)
922 929 if not varnames:
923 930 print 'Interactive namespace is empty.'
924 931 return
925 932
926 933 # if we have variables, move on...
927 934
928 935 # for these types, show len() instead of data:
929 936 seq_types = [types.DictType,types.ListType,types.TupleType]
930 937
931 938 # for Numeric arrays, display summary info
932 939 try:
933 940 import Numeric
934 941 except ImportError:
935 942 array_type = None
936 943 else:
937 944 array_type = Numeric.ArrayType.__name__
938 945
939 946 # Find all variable names and types so we can figure out column sizes
940 947 get_vars = lambda i: self.shell.user_ns[i]
941 948 type_name = lambda v: type(v).__name__
942 949 varlist = map(get_vars,varnames)
943 950
944 951 typelist = []
945 952 for vv in varlist:
946 953 tt = type_name(vv)
947 954 if tt=='instance':
948 955 typelist.append(str(vv.__class__))
949 956 else:
950 957 typelist.append(tt)
951 958
952 959 # column labels and # of spaces as separator
953 960 varlabel = 'Variable'
954 961 typelabel = 'Type'
955 962 datalabel = 'Data/Info'
956 963 colsep = 3
957 964 # variable format strings
958 965 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
959 966 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
960 967 aformat = "%s: %s elems, type `%s`, %s bytes"
961 968 # find the size of the columns to format the output nicely
962 969 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
963 970 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
964 971 # table header
965 972 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
966 973 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
967 974 # and the table itself
968 975 kb = 1024
969 976 Mb = 1048576 # kb**2
970 977 for vname,var,vtype in zip(varnames,varlist,typelist):
971 978 print itpl(vformat),
972 979 if vtype in seq_types:
973 980 print len(var)
974 981 elif vtype==array_type:
975 982 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
976 983 vsize = Numeric.size(var)
977 984 vbytes = vsize*var.itemsize()
978 985 if vbytes < 100000:
979 986 print aformat % (vshape,vsize,var.typecode(),vbytes)
980 987 else:
981 988 print aformat % (vshape,vsize,var.typecode(),vbytes),
982 989 if vbytes < Mb:
983 990 print '(%s kb)' % (vbytes/kb,)
984 991 else:
985 992 print '(%s Mb)' % (vbytes/Mb,)
986 993 else:
987 994 vstr = str(var).replace('\n','\\n')
988 995 if len(vstr) < 50:
989 996 print vstr
990 997 else:
991 998 printpl(vfmt_short)
992 999
993 1000 def magic_reset(self, parameter_s=''):
994 1001 """Resets the namespace by removing all names defined by the user.
995 1002
996 1003 Input/Output history are left around in case you need them."""
997 1004
998 1005 ans = self.shell.ask_yes_no(
999 1006 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1000 1007 if not ans:
1001 1008 print 'Nothing done.'
1002 1009 return
1003 1010 user_ns = self.shell.user_ns
1004 1011 for i in self.magic_who_ls():
1005 1012 del(user_ns[i])
1006 1013
1007 1014 def magic_config(self,parameter_s=''):
1008 """Show IPython's internal configuration."""
1009
1010 page('Current configuration structure:\n'+
1011 pformat(self.shell.rc.dict()))
1015 """Handle IPython's internal configuration.
1016
1017 If called without arguments, it will print IPython's complete internal
1018 configuration.
1019
1020 If called with one argument, it will print the value of that key in
1021 the configuration.
1022
1023 If called with more than one argument, the first is interpreted as a
1024 key and the rest as a Python expression which gets eval()'d.
1025
1026 Examples:
1027
1028 In [1]: s='A Python string'
1029
1030 In [2]: !echo $s
1031 A Python string
1032
1033 In [3]: config system_verbose True
1034
1035 In [4]: !echo $s
1036 IPython system call: echo A Python string
1037 A Python string
1038
1039 In [5]: %config system_header 'sys> '
1040
1041 In [6]: !echo $s
1042 sys> echo A Python string
1043 A Python string
1044
1045 # Notice the extra quotes to protect the string after interpolation:
1046 In [7]: header = "'sys2> '"
1047
1048 In [8]: %config system_header $header
1049
1050 In [9]: !echo $s
1051 sys2> echo A Python string
1052 A Python string
1053 """
1054
1055 args = parameter_s.split(None,1)
1056 key = args[0]
1057 if len(args)==1:
1058 self.shell.ipconfig(key)
1059 else:
1060 self.shell.ipconfig(key,eval(args[1]))
1012 1061
1013 1062 def magic_logstart(self,parameter_s=''):
1014 1063 """Start logging anywhere in a session.
1015 1064
1016 1065 %logstart [-o|-r|-t] [log_name [log_mode]]
1017 1066
1018 1067 If no name is given, it defaults to a file named 'ipython_log.py' in your
1019 1068 current directory, in 'rotate' mode (see below).
1020 1069
1021 1070 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1022 1071 history up to that point and then continues logging.
1023 1072
1024 1073 %logstart takes a second optional parameter: logging mode. This can be one
1025 1074 of (note that the modes are given unquoted):\\
1026 1075 append: well, that says it.\\
1027 1076 backup: rename (if exists) to name~ and start name.\\
1028 1077 global: single logfile in your home dir, appended to.\\
1029 1078 over : overwrite existing log.\\
1030 1079 rotate: create rotating logs name.1~, name.2~, etc.
1031 1080
1032 1081 Options:
1033 1082
1034 1083 -o: log also IPython's output. In this mode, all commands which
1035 1084 generate an Out[NN] prompt are recorded to the logfile, right after
1036 1085 their corresponding input line. The output lines are always
1037 1086 prepended with a '#[Out]# ' marker, so that the log remains valid
1038 1087 Python code.
1039 1088
1040 1089 Since this marker is always the same, filtering only the output from
1041 1090 a log is very easy, using for example a simple awk call:
1042 1091
1043 1092 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1044 1093
1045 1094 -r: log 'raw' input. Normally, IPython's logs contain the processed
1046 1095 input, so that user lines are logged in their final form, converted
1047 1096 into valid Python. For example, %Exit is logged as
1048 1097 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1049 1098 exactly as typed, with no transformations applied.
1050 1099
1051 1100 -t: put timestamps before each input line logged (these are put in
1052 1101 comments)."""
1053 1102
1054 1103 opts,par = self.parse_options(parameter_s,'ort')
1055 1104 log_output = 'o' in opts
1056 1105 log_raw_input = 'r' in opts
1057 1106 timestamp = 't' in opts
1058 1107
1059 1108 rc = self.shell.rc
1060 1109 logger = self.shell.logger
1061 1110
1062 1111 # if no args are given, the defaults set in the logger constructor by
1063 1112 # ipytohn remain valid
1064 1113 if par:
1065 1114 try:
1066 1115 logfname,logmode = par.split()
1067 1116 except:
1068 1117 logfname = par
1069 1118 logmode = 'backup'
1070 1119 else:
1071 1120 logfname = logger.logfname
1072 1121 logmode = logger.logmode
1073 1122 # put logfname into rc struct as if it had been called on the command
1074 1123 # line, so it ends up saved in the log header Save it in case we need
1075 1124 # to restore it...
1076 1125 old_logfile = rc.opts.get('logfile','')
1077 1126 if logfname:
1078 1127 logfname = os.path.expanduser(logfname)
1079 1128 rc.opts.logfile = logfname
1080 1129 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1081 1130 try:
1082 1131 started = logger.logstart(logfname,loghead,logmode,
1083 1132 log_output,timestamp,log_raw_input)
1084 1133 except:
1085 1134 rc.opts.logfile = old_logfile
1086 1135 warn("Couldn't start log: %s" % sys.exc_info()[1])
1087 1136 else:
1088 1137 # log input history up to this point, optionally interleaving
1089 1138 # output if requested
1090 1139
1091 1140 if timestamp:
1092 1141 # disable timestamping for the previous history, since we've
1093 1142 # lost those already (no time machine here).
1094 1143 logger.timestamp = False
1095 1144
1096 1145 if log_raw_input:
1097 1146 input_hist = self.shell.input_hist_raw
1098 1147 else:
1099 1148 input_hist = self.shell.input_hist
1100 1149
1101 1150 if log_output:
1102 1151 log_write = logger.log_write
1103 1152 output_hist = self.shell.output_hist
1104 1153 for n in range(1,len(input_hist)-1):
1105 1154 log_write(input_hist[n].rstrip())
1106 1155 if n in output_hist:
1107 1156 log_write(repr(output_hist[n]),'output')
1108 1157 else:
1109 1158 logger.log_write(input_hist[1:])
1110 1159 if timestamp:
1111 1160 # re-enable timestamping
1112 1161 logger.timestamp = True
1113 1162
1114 1163 print ('Activating auto-logging. '
1115 1164 'Current session state plus future input saved.')
1116 1165 logger.logstate()
1117 1166
1118 1167 def magic_logoff(self,parameter_s=''):
1119 1168 """Temporarily stop logging.
1120 1169
1121 1170 You must have previously started logging."""
1122 1171 self.shell.logger.switch_log(0)
1123 1172
1124 1173 def magic_logon(self,parameter_s=''):
1125 1174 """Restart logging.
1126 1175
1127 1176 This function is for restarting logging which you've temporarily
1128 1177 stopped with %logoff. For starting logging for the first time, you
1129 1178 must use the %logstart function, which allows you to specify an
1130 1179 optional log filename."""
1131 1180
1132 1181 self.shell.logger.switch_log(1)
1133 1182
1134 1183 def magic_logstate(self,parameter_s=''):
1135 1184 """Print the status of the logging system."""
1136 1185
1137 1186 self.shell.logger.logstate()
1138 1187
1139 1188 def magic_pdb(self, parameter_s=''):
1140 1189 """Control the calling of the pdb interactive debugger.
1141 1190
1142 1191 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1143 1192 argument it works as a toggle.
1144 1193
1145 1194 When an exception is triggered, IPython can optionally call the
1146 1195 interactive pdb debugger after the traceback printout. %pdb toggles
1147 1196 this feature on and off."""
1148 1197
1149 1198 par = parameter_s.strip().lower()
1150 1199
1151 1200 if par:
1152 1201 try:
1153 1202 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1154 1203 except KeyError:
1155 1204 print ('Incorrect argument. Use on/1, off/0, '
1156 1205 'or nothing for a toggle.')
1157 1206 return
1158 1207 else:
1159 1208 # toggle
1160 1209 new_pdb = not self.shell.InteractiveTB.call_pdb
1161 1210
1162 1211 # set on the shell
1163 1212 self.shell.call_pdb = new_pdb
1164 1213 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1165 1214
1166 1215 def magic_prun(self, parameter_s ='',user_mode=1,
1167 1216 opts=None,arg_lst=None,prog_ns=None):
1168 1217
1169 1218 """Run a statement through the python code profiler.
1170 1219
1171 1220 Usage:\\
1172 1221 %prun [options] statement
1173 1222
1174 1223 The given statement (which doesn't require quote marks) is run via the
1175 1224 python profiler in a manner similar to the profile.run() function.
1176 1225 Namespaces are internally managed to work correctly; profile.run
1177 1226 cannot be used in IPython because it makes certain assumptions about
1178 1227 namespaces which do not hold under IPython.
1179 1228
1180 1229 Options:
1181 1230
1182 1231 -l <limit>: you can place restrictions on what or how much of the
1183 1232 profile gets printed. The limit value can be:
1184 1233
1185 1234 * A string: only information for function names containing this string
1186 1235 is printed.
1187 1236
1188 1237 * An integer: only these many lines are printed.
1189 1238
1190 1239 * A float (between 0 and 1): this fraction of the report is printed
1191 1240 (for example, use a limit of 0.4 to see the topmost 40% only).
1192 1241
1193 1242 You can combine several limits with repeated use of the option. For
1194 1243 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1195 1244 information about class constructors.
1196 1245
1197 1246 -r: return the pstats.Stats object generated by the profiling. This
1198 1247 object has all the information about the profile in it, and you can
1199 1248 later use it for further analysis or in other functions.
1200 1249
1201 1250 Since magic functions have a particular form of calling which prevents
1202 1251 you from writing something like:\\
1203 1252 In [1]: p = %prun -r print 4 # invalid!\\
1204 1253 you must instead use IPython's automatic variables to assign this:\\
1205 1254 In [1]: %prun -r print 4 \\
1206 1255 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1207 1256 In [2]: stats = _
1208 1257
1209 1258 If you really need to assign this value via an explicit function call,
1210 1259 you can always tap directly into the true name of the magic function
1211 1260 by using the _ip.magic function:\\
1212 1261 In [3]: stats = _ip.magic('prun','-r print 4')
1213 1262
1214 1263 You can type _ip.magic? for more details.
1215 1264
1216 1265 -s <key>: sort profile by given key. You can provide more than one key
1217 1266 by using the option several times: '-s key1 -s key2 -s key3...'. The
1218 1267 default sorting key is 'time'.
1219 1268
1220 1269 The following is copied verbatim from the profile documentation
1221 1270 referenced below:
1222 1271
1223 1272 When more than one key is provided, additional keys are used as
1224 1273 secondary criteria when the there is equality in all keys selected
1225 1274 before them.
1226 1275
1227 1276 Abbreviations can be used for any key names, as long as the
1228 1277 abbreviation is unambiguous. The following are the keys currently
1229 1278 defined:
1230 1279
1231 1280 Valid Arg Meaning\\
1232 1281 "calls" call count\\
1233 1282 "cumulative" cumulative time\\
1234 1283 "file" file name\\
1235 1284 "module" file name\\
1236 1285 "pcalls" primitive call count\\
1237 1286 "line" line number\\
1238 1287 "name" function name\\
1239 1288 "nfl" name/file/line\\
1240 1289 "stdname" standard name\\
1241 1290 "time" internal time
1242 1291
1243 1292 Note that all sorts on statistics are in descending order (placing
1244 1293 most time consuming items first), where as name, file, and line number
1245 1294 searches are in ascending order (i.e., alphabetical). The subtle
1246 1295 distinction between "nfl" and "stdname" is that the standard name is a
1247 1296 sort of the name as printed, which means that the embedded line
1248 1297 numbers get compared in an odd way. For example, lines 3, 20, and 40
1249 1298 would (if the file names were the same) appear in the string order
1250 1299 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1251 1300 line numbers. In fact, sort_stats("nfl") is the same as
1252 1301 sort_stats("name", "file", "line").
1253 1302
1254 1303 -T <filename>: save profile results as shown on screen to a text
1255 1304 file. The profile is still shown on screen.
1256 1305
1257 1306 -D <filename>: save (via dump_stats) profile statistics to given
1258 1307 filename. This data is in a format understod by the pstats module, and
1259 1308 is generated by a call to the dump_stats() method of profile
1260 1309 objects. The profile is still shown on screen.
1261 1310
1262 1311 If you want to run complete programs under the profiler's control, use
1263 1312 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1264 1313 contains profiler specific options as described here.
1265 1314
1266 1315 You can read the complete documentation for the profile module with:\\
1267 1316 In [1]: import profile; profile.help() """
1268 1317
1269 1318 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1270 1319 # protect user quote marks
1271 1320 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1272 1321
1273 1322 if user_mode: # regular user call
1274 1323 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1275 1324 list_all=1)
1276 1325 namespace = self.shell.user_ns
1277 1326 else: # called to run a program by %run -p
1278 1327 try:
1279 1328 filename = get_py_filename(arg_lst[0])
1280 1329 except IOError,msg:
1281 1330 error(msg)
1282 1331 return
1283 1332
1284 1333 arg_str = 'execfile(filename,prog_ns)'
1285 1334 namespace = locals()
1286 1335
1287 1336 opts.merge(opts_def)
1288 1337
1289 1338 prof = profile.Profile()
1290 1339 try:
1291 1340 prof = prof.runctx(arg_str,namespace,namespace)
1292 1341 sys_exit = ''
1293 1342 except SystemExit:
1294 1343 sys_exit = """*** SystemExit exception caught in code being profiled."""
1295 1344
1296 1345 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1297 1346
1298 1347 lims = opts.l
1299 1348 if lims:
1300 1349 lims = [] # rebuild lims with ints/floats/strings
1301 1350 for lim in opts.l:
1302 1351 try:
1303 1352 lims.append(int(lim))
1304 1353 except ValueError:
1305 1354 try:
1306 1355 lims.append(float(lim))
1307 1356 except ValueError:
1308 1357 lims.append(lim)
1309 1358
1310 1359 # trap output
1311 1360 sys_stdout = sys.stdout
1312 1361 stdout_trap = StringIO()
1313 1362 try:
1314 1363 sys.stdout = stdout_trap
1315 1364 stats.print_stats(*lims)
1316 1365 finally:
1317 1366 sys.stdout = sys_stdout
1318 1367 output = stdout_trap.getvalue()
1319 1368 output = output.rstrip()
1320 1369
1321 1370 page(output,screen_lines=self.shell.rc.screen_length)
1322 1371 print sys_exit,
1323 1372
1324 1373 dump_file = opts.D[0]
1325 1374 text_file = opts.T[0]
1326 1375 if dump_file:
1327 1376 prof.dump_stats(dump_file)
1328 1377 print '\n*** Profile stats marshalled to file',\
1329 1378 `dump_file`+'.',sys_exit
1330 1379 if text_file:
1331 1380 file(text_file,'w').write(output)
1332 1381 print '\n*** Profile printout saved to text file',\
1333 1382 `text_file`+'.',sys_exit
1334 1383
1335 1384 if opts.has_key('r'):
1336 1385 return stats
1337 1386 else:
1338 1387 return None
1339 1388
1340 1389 def magic_run(self, parameter_s ='',runner=None):
1341 1390 """Run the named file inside IPython as a program.
1342 1391
1343 1392 Usage:\\
1344 1393 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1345 1394
1346 1395 Parameters after the filename are passed as command-line arguments to
1347 1396 the program (put in sys.argv). Then, control returns to IPython's
1348 1397 prompt.
1349 1398
1350 1399 This is similar to running at a system prompt:\\
1351 1400 $ python file args\\
1352 1401 but with the advantage of giving you IPython's tracebacks, and of
1353 1402 loading all variables into your interactive namespace for further use
1354 1403 (unless -p is used, see below).
1355 1404
1356 1405 The file is executed in a namespace initially consisting only of
1357 1406 __name__=='__main__' and sys.argv constructed as indicated. It thus
1358 1407 sees its environment as if it were being run as a stand-alone
1359 1408 program. But after execution, the IPython interactive namespace gets
1360 1409 updated with all variables defined in the program (except for __name__
1361 1410 and sys.argv). This allows for very convenient loading of code for
1362 1411 interactive work, while giving each program a 'clean sheet' to run in.
1363 1412
1364 1413 Options:
1365 1414
1366 1415 -n: __name__ is NOT set to '__main__', but to the running file's name
1367 1416 without extension (as python does under import). This allows running
1368 1417 scripts and reloading the definitions in them without calling code
1369 1418 protected by an ' if __name__ == "__main__" ' clause.
1370 1419
1371 1420 -i: run the file in IPython's namespace instead of an empty one. This
1372 1421 is useful if you are experimenting with code written in a text editor
1373 1422 which depends on variables defined interactively.
1374 1423
1375 1424 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1376 1425 being run. This is particularly useful if IPython is being used to
1377 1426 run unittests, which always exit with a sys.exit() call. In such
1378 1427 cases you are interested in the output of the test results, not in
1379 1428 seeing a traceback of the unittest module.
1380 1429
1381 1430 -t: print timing information at the end of the run. IPython will give
1382 1431 you an estimated CPU time consumption for your script, which under
1383 1432 Unix uses the resource module to avoid the wraparound problems of
1384 1433 time.clock(). Under Unix, an estimate of time spent on system tasks
1385 1434 is also given (for Windows platforms this is reported as 0.0).
1386 1435
1387 1436 If -t is given, an additional -N<N> option can be given, where <N>
1388 1437 must be an integer indicating how many times you want the script to
1389 1438 run. The final timing report will include total and per run results.
1390 1439
1391 1440 For example (testing the script uniq_stable.py):
1392 1441
1393 1442 In [1]: run -t uniq_stable
1394 1443
1395 1444 IPython CPU timings (estimated):\\
1396 1445 User : 0.19597 s.\\
1397 1446 System: 0.0 s.\\
1398 1447
1399 1448 In [2]: run -t -N5 uniq_stable
1400 1449
1401 1450 IPython CPU timings (estimated):\\
1402 1451 Total runs performed: 5\\
1403 1452 Times : Total Per run\\
1404 1453 User : 0.910862 s, 0.1821724 s.\\
1405 1454 System: 0.0 s, 0.0 s.
1406 1455
1407 1456 -d: run your program under the control of pdb, the Python debugger.
1408 1457 This allows you to execute your program step by step, watch variables,
1409 1458 etc. Internally, what IPython does is similar to calling:
1410 1459
1411 1460 pdb.run('execfile("YOURFILENAME")')
1412 1461
1413 1462 with a breakpoint set on line 1 of your file. You can change the line
1414 1463 number for this automatic breakpoint to be <N> by using the -bN option
1415 1464 (where N must be an integer). For example:
1416 1465
1417 1466 %run -d -b40 myscript
1418 1467
1419 1468 will set the first breakpoint at line 40 in myscript.py. Note that
1420 1469 the first breakpoint must be set on a line which actually does
1421 1470 something (not a comment or docstring) for it to stop execution.
1422 1471
1423 1472 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1424 1473 first enter 'c' (without qoutes) to start execution up to the first
1425 1474 breakpoint.
1426 1475
1427 1476 Entering 'help' gives information about the use of the debugger. You
1428 1477 can easily see pdb's full documentation with "import pdb;pdb.help()"
1429 1478 at a prompt.
1430 1479
1431 1480 -p: run program under the control of the Python profiler module (which
1432 1481 prints a detailed report of execution times, function calls, etc).
1433 1482
1434 1483 You can pass other options after -p which affect the behavior of the
1435 1484 profiler itself. See the docs for %prun for details.
1436 1485
1437 1486 In this mode, the program's variables do NOT propagate back to the
1438 1487 IPython interactive namespace (because they remain in the namespace
1439 1488 where the profiler executes them).
1440 1489
1441 1490 Internally this triggers a call to %prun, see its documentation for
1442 1491 details on the options available specifically for profiling."""
1443 1492
1444 1493 # get arguments and set sys.argv for program to be run.
1445 1494 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1446 1495 mode='list',list_all=1)
1447 1496
1448 1497 try:
1449 1498 filename = get_py_filename(arg_lst[0])
1450 1499 except IndexError:
1451 1500 warn('you must provide at least a filename.')
1452 1501 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1453 1502 return
1454 1503 except IOError,msg:
1455 1504 error(msg)
1456 1505 return
1457 1506
1458 1507 # Control the response to exit() calls made by the script being run
1459 1508 exit_ignore = opts.has_key('e')
1460 1509
1461 1510 # Make sure that the running script gets a proper sys.argv as if it
1462 1511 # were run from a system shell.
1463 1512 save_argv = sys.argv # save it for later restoring
1464 1513 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1465 1514
1466 1515 if opts.has_key('i'):
1467 1516 prog_ns = self.shell.user_ns
1468 1517 __name__save = self.shell.user_ns['__name__']
1469 1518 prog_ns['__name__'] = '__main__'
1470 1519 else:
1471 1520 if opts.has_key('n'):
1472 1521 name = os.path.splitext(os.path.basename(filename))[0]
1473 1522 else:
1474 1523 name = '__main__'
1475 1524 prog_ns = {'__name__':name}
1476 1525
1477 1526 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1478 1527 # set the __file__ global in the script's namespace
1479 1528 prog_ns['__file__'] = filename
1480 1529
1481 1530 # pickle fix. See iplib for an explanation. But we need to make sure
1482 1531 # that, if we overwrite __main__, we replace it at the end
1483 1532 if prog_ns['__name__'] == '__main__':
1484 1533 restore_main = sys.modules['__main__']
1485 1534 else:
1486 1535 restore_main = False
1487 1536
1488 1537 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1489 1538
1490 1539 stats = None
1491 1540 try:
1492 1541 if self.shell.has_readline:
1493 1542 self.shell.savehist()
1494 1543
1495 1544 if opts.has_key('p'):
1496 1545 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1497 1546 else:
1498 1547 if opts.has_key('d'):
1499 1548 deb = Debugger.Pdb(self.shell.rc.colors)
1500 1549 # reset Breakpoint state, which is moronically kept
1501 1550 # in a class
1502 1551 bdb.Breakpoint.next = 1
1503 1552 bdb.Breakpoint.bplist = {}
1504 1553 bdb.Breakpoint.bpbynumber = [None]
1505 1554 # Set an initial breakpoint to stop execution
1506 1555 maxtries = 10
1507 1556 bp = int(opts.get('b',[1])[0])
1508 1557 checkline = deb.checkline(filename,bp)
1509 1558 if not checkline:
1510 1559 for bp in range(bp+1,bp+maxtries+1):
1511 1560 if deb.checkline(filename,bp):
1512 1561 break
1513 1562 else:
1514 1563 msg = ("\nI failed to find a valid line to set "
1515 1564 "a breakpoint\n"
1516 1565 "after trying up to line: %s.\n"
1517 1566 "Please set a valid breakpoint manually "
1518 1567 "with the -b option." % bp)
1519 1568 error(msg)
1520 1569 return
1521 1570 # if we find a good linenumber, set the breakpoint
1522 1571 deb.do_break('%s:%s' % (filename,bp))
1523 1572 # Start file run
1524 1573 print "NOTE: Enter 'c' at the",
1525 1574 print "%s prompt to start your script." % deb.prompt
1526 1575 try:
1527 1576 deb.run('execfile("%s")' % filename,prog_ns)
1528 1577
1529 1578 except:
1530 1579 etype, value, tb = sys.exc_info()
1531 1580 # Skip three frames in the traceback: the %run one,
1532 1581 # one inside bdb.py, and the command-line typed by the
1533 1582 # user (run by exec in pdb itself).
1534 1583 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1535 1584 else:
1536 1585 if runner is None:
1537 1586 runner = self.shell.safe_execfile
1538 1587 if opts.has_key('t'):
1539 1588 try:
1540 1589 nruns = int(opts['N'][0])
1541 1590 if nruns < 1:
1542 1591 error('Number of runs must be >=1')
1543 1592 return
1544 1593 except (KeyError):
1545 1594 nruns = 1
1546 1595 if nruns == 1:
1547 1596 t0 = clock2()
1548 1597 runner(filename,prog_ns,prog_ns,
1549 1598 exit_ignore=exit_ignore)
1550 1599 t1 = clock2()
1551 1600 t_usr = t1[0]-t0[0]
1552 1601 t_sys = t1[1]-t1[1]
1553 1602 print "\nIPython CPU timings (estimated):"
1554 1603 print " User : %10s s." % t_usr
1555 1604 print " System: %10s s." % t_sys
1556 1605 else:
1557 1606 runs = range(nruns)
1558 1607 t0 = clock2()
1559 1608 for nr in runs:
1560 1609 runner(filename,prog_ns,prog_ns,
1561 1610 exit_ignore=exit_ignore)
1562 1611 t1 = clock2()
1563 1612 t_usr = t1[0]-t0[0]
1564 1613 t_sys = t1[1]-t1[1]
1565 1614 print "\nIPython CPU timings (estimated):"
1566 1615 print "Total runs performed:",nruns
1567 1616 print " Times : %10s %10s" % ('Total','Per run')
1568 1617 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1569 1618 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1570 1619
1571 1620 else:
1572 1621 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1573 1622 if opts.has_key('i'):
1574 1623 self.shell.user_ns['__name__'] = __name__save
1575 1624 else:
1576 1625 # update IPython interactive namespace
1577 1626 del prog_ns['__name__']
1578 1627 self.shell.user_ns.update(prog_ns)
1579 1628 finally:
1580 1629 sys.argv = save_argv
1581 1630 if restore_main:
1582 1631 sys.modules['__main__'] = restore_main
1583 1632 if self.shell.has_readline:
1584 1633 self.shell.readline.read_history_file(self.shell.histfile)
1585 1634
1586 1635 return stats
1587 1636
1588 1637 def magic_runlog(self, parameter_s =''):
1589 1638 """Run files as logs.
1590 1639
1591 1640 Usage:\\
1592 1641 %runlog file1 file2 ...
1593 1642
1594 1643 Run the named files (treating them as log files) in sequence inside
1595 1644 the interpreter, and return to the prompt. This is much slower than
1596 1645 %run because each line is executed in a try/except block, but it
1597 1646 allows running files with syntax errors in them.
1598 1647
1599 1648 Normally IPython will guess when a file is one of its own logfiles, so
1600 1649 you can typically use %run even for logs. This shorthand allows you to
1601 1650 force any file to be treated as a log file."""
1602 1651
1603 1652 for f in parameter_s.split():
1604 1653 self.shell.safe_execfile(f,self.shell.user_ns,
1605 1654 self.shell.user_ns,islog=1)
1606 1655
1607 1656 def magic_timeit(self, parameter_s =''):
1608 1657 """Time execution of a Python statement or expression
1609 1658
1610 1659 Usage:\\
1611 1660 %timeit [-n<N> -r<R> [-t|-c]] statement
1612 1661
1613 1662 Time execution of a Python statement or expression using the timeit
1614 1663 module.
1615 1664
1616 1665 Options:
1617 1666 -n<N>: execute the given statement <N> times in a loop. If this value
1618 1667 is not given, a fitting value is chosen.
1619 1668
1620 1669 -r<R>: repeat the loop iteration <R> times and take the best result.
1621 1670 Default: 3
1622 1671
1623 1672 -t: use time.time to measure the time, which is the default on Unix.
1624 1673 This function measures wall time.
1625 1674
1626 1675 -c: use time.clock to measure the time, which is the default on
1627 1676 Windows and measures wall time. On Unix, resource.getrusage is used
1628 1677 instead and returns the CPU user time.
1629 1678
1630 1679 -p<P>: use a precision of <P> digits to display the timing result.
1631 1680 Default: 3
1632 1681
1633 1682
1634 1683 Examples:\\
1635 1684 In [1]: %timeit pass
1636 1685 10000000 loops, best of 3: 53.3 ns per loop
1637 1686
1638 1687 In [2]: u = None
1639 1688
1640 1689 In [3]: %timeit u is None
1641 1690 10000000 loops, best of 3: 184 ns per loop
1642 1691
1643 1692 In [4]: %timeit -r 4 u == None
1644 1693 1000000 loops, best of 4: 242 ns per loop
1645 1694
1646 1695 In [5]: import time
1647 1696
1648 1697 In [6]: %timeit -n1 time.sleep(2)
1649 1698 1 loops, best of 3: 2 s per loop
1650 1699
1651 1700
1652 1701 The times reported by %timeit will be slightly higher than those
1653 1702 reported by the timeit.py script when variables are accessed. This is
1654 1703 due to the fact that %timeit executes the statement in the namespace
1655 1704 of the shell, compared with timeit.py, which uses a single setup
1656 1705 statement to import function or create variables. Generally, the bias
1657 1706 does not matter as long as results from timeit.py are not mixed with
1658 1707 those from %timeit."""
1659 1708
1660 1709 import timeit
1661 1710 import math
1662 1711
1663 1712 units = ["s", "ms", "\xc2\xb5s", "ns"]
1664 1713 scaling = [1, 1e3, 1e6, 1e9]
1665 1714
1666 1715 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1667 1716 posix=False)
1668 1717 if stmt == "":
1669 1718 return
1670 1719 timefunc = timeit.default_timer
1671 1720 number = int(getattr(opts, "n", 0))
1672 1721 repeat = int(getattr(opts, "r", timeit.default_repeat))
1673 1722 precision = int(getattr(opts, "p", 3))
1674 1723 if hasattr(opts, "t"):
1675 1724 timefunc = time.time
1676 1725 if hasattr(opts, "c"):
1677 1726 timefunc = clock
1678 1727
1679 1728 timer = timeit.Timer(timer=timefunc)
1680 1729 # this code has tight coupling to the inner workings of timeit.Timer,
1681 1730 # but is there a better way to achieve that the code stmt has access
1682 1731 # to the shell namespace?
1683 1732
1684 1733 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1685 1734 'setup': "pass"}
1686 1735 code = compile(src, "<magic-timeit>", "exec")
1687 1736 ns = {}
1688 1737 exec code in self.shell.user_ns, ns
1689 1738 timer.inner = ns["inner"]
1690 1739
1691 1740 if number == 0:
1692 1741 # determine number so that 0.2 <= total time < 2.0
1693 1742 number = 1
1694 1743 for i in range(1, 10):
1695 1744 number *= 10
1696 1745 if timer.timeit(number) >= 0.2:
1697 1746 break
1698 1747
1699 1748 best = min(timer.repeat(repeat, number)) / number
1700 1749
1701 1750 if best > 0.0:
1702 1751 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1703 1752 else:
1704 1753 order = 3
1705 1754 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1706 1755 precision,
1707 1756 best * scaling[order],
1708 1757 units[order])
1709 1758
1710 1759 def magic_time(self,parameter_s = ''):
1711 1760 """Time execution of a Python statement or expression.
1712 1761
1713 1762 The CPU and wall clock times are printed, and the value of the
1714 1763 expression (if any) is returned. Note that under Win32, system time
1715 1764 is always reported as 0, since it can not be measured.
1716 1765
1717 1766 This function provides very basic timing functionality. In Python
1718 1767 2.3, the timeit module offers more control and sophistication, so this
1719 1768 could be rewritten to use it (patches welcome).
1720 1769
1721 1770 Some examples:
1722 1771
1723 1772 In [1]: time 2**128
1724 1773 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1725 1774 Wall time: 0.00
1726 1775 Out[1]: 340282366920938463463374607431768211456L
1727 1776
1728 1777 In [2]: n = 1000000
1729 1778
1730 1779 In [3]: time sum(range(n))
1731 1780 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1732 1781 Wall time: 1.37
1733 1782 Out[3]: 499999500000L
1734 1783
1735 1784 In [4]: time print 'hello world'
1736 1785 hello world
1737 1786 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1738 1787 Wall time: 0.00
1739 1788 """
1740 1789
1741 1790 # fail immediately if the given expression can't be compiled
1742 1791 try:
1743 1792 mode = 'eval'
1744 1793 code = compile(parameter_s,'<timed eval>',mode)
1745 1794 except SyntaxError:
1746 1795 mode = 'exec'
1747 1796 code = compile(parameter_s,'<timed exec>',mode)
1748 1797 # skew measurement as little as possible
1749 1798 glob = self.shell.user_ns
1750 1799 clk = clock2
1751 1800 wtime = time.time
1752 1801 # time execution
1753 1802 wall_st = wtime()
1754 1803 if mode=='eval':
1755 1804 st = clk()
1756 1805 out = eval(code,glob)
1757 1806 end = clk()
1758 1807 else:
1759 1808 st = clk()
1760 1809 exec code in glob
1761 1810 end = clk()
1762 1811 out = None
1763 1812 wall_end = wtime()
1764 1813 # Compute actual times and report
1765 1814 wall_time = wall_end-wall_st
1766 1815 cpu_user = end[0]-st[0]
1767 1816 cpu_sys = end[1]-st[1]
1768 1817 cpu_tot = cpu_user+cpu_sys
1769 1818 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1770 1819 (cpu_user,cpu_sys,cpu_tot)
1771 1820 print "Wall time: %.2f" % wall_time
1772 1821 return out
1773 1822
1774 1823 def magic_macro(self,parameter_s = ''):
1775 1824 """Define a set of input lines as a macro for future re-execution.
1776 1825
1777 1826 Usage:\\
1778 1827 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1779 1828
1780 1829 Options:
1781 1830
1782 1831 -r: use 'raw' input. By default, the 'processed' history is used,
1783 1832 so that magics are loaded in their transformed version to valid
1784 1833 Python. If this option is given, the raw input as typed as the
1785 1834 command line is used instead.
1786 1835
1787 1836 This will define a global variable called `name` which is a string
1788 1837 made of joining the slices and lines you specify (n1,n2,... numbers
1789 1838 above) from your input history into a single string. This variable
1790 1839 acts like an automatic function which re-executes those lines as if
1791 1840 you had typed them. You just type 'name' at the prompt and the code
1792 1841 executes.
1793 1842
1794 1843 The notation for indicating number ranges is: n1-n2 means 'use line
1795 1844 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1796 1845 using the lines numbered 5,6 and 7.
1797 1846
1798 1847 Note: as a 'hidden' feature, you can also use traditional python slice
1799 1848 notation, where N:M means numbers N through M-1.
1800 1849
1801 1850 For example, if your history contains (%hist prints it):
1802 1851
1803 1852 44: x=1\\
1804 1853 45: y=3\\
1805 1854 46: z=x+y\\
1806 1855 47: print x\\
1807 1856 48: a=5\\
1808 1857 49: print 'x',x,'y',y\\
1809 1858
1810 1859 you can create a macro with lines 44 through 47 (included) and line 49
1811 1860 called my_macro with:
1812 1861
1813 1862 In [51]: %macro my_macro 44-47 49
1814 1863
1815 1864 Now, typing `my_macro` (without quotes) will re-execute all this code
1816 1865 in one pass.
1817 1866
1818 1867 You don't need to give the line-numbers in order, and any given line
1819 1868 number can appear multiple times. You can assemble macros with any
1820 1869 lines from your input history in any order.
1821 1870
1822 1871 The macro is a simple object which holds its value in an attribute,
1823 1872 but IPython's display system checks for macros and executes them as
1824 1873 code instead of printing them when you type their name.
1825 1874
1826 1875 You can view a macro's contents by explicitly printing it with:
1827 1876
1828 1877 'print macro_name'.
1829 1878
1830 1879 For one-off cases which DON'T contain magic function calls in them you
1831 1880 can obtain similar results by explicitly executing slices from your
1832 1881 input history with:
1833 1882
1834 1883 In [60]: exec In[44:48]+In[49]"""
1835 1884
1836 1885 opts,args = self.parse_options(parameter_s,'r',mode='list')
1837 1886 name,ranges = args[0], args[1:]
1838 1887 #print 'rng',ranges # dbg
1839 1888 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1840 1889 macro = Macro(lines)
1841 1890 self.shell.user_ns.update({name:macro})
1842 1891 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1843 1892 print 'Macro contents:'
1844 1893 print macro,
1845 1894
1846 1895 def magic_save(self,parameter_s = ''):
1847 1896 """Save a set of lines to a given filename.
1848 1897
1849 1898 Usage:\\
1850 1899 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1851 1900
1852 1901 Options:
1853 1902
1854 1903 -r: use 'raw' input. By default, the 'processed' history is used,
1855 1904 so that magics are loaded in their transformed version to valid
1856 1905 Python. If this option is given, the raw input as typed as the
1857 1906 command line is used instead.
1858 1907
1859 1908 This function uses the same syntax as %macro for line extraction, but
1860 1909 instead of creating a macro it saves the resulting string to the
1861 1910 filename you specify.
1862 1911
1863 1912 It adds a '.py' extension to the file if you don't do so yourself, and
1864 1913 it asks for confirmation before overwriting existing files."""
1865 1914
1866 1915 opts,args = self.parse_options(parameter_s,'r',mode='list')
1867 1916 fname,ranges = args[0], args[1:]
1868 1917 if not fname.endswith('.py'):
1869 1918 fname += '.py'
1870 1919 if os.path.isfile(fname):
1871 1920 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1872 1921 if ans.lower() not in ['y','yes']:
1873 1922 print 'Operation cancelled.'
1874 1923 return
1875 1924 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1876 1925 f = file(fname,'w')
1877 1926 f.write(cmds)
1878 1927 f.close()
1879 1928 print 'The following commands were written to file `%s`:' % fname
1880 1929 print cmds
1881 1930
1882 1931 def _edit_macro(self,mname,macro):
1883 1932 """open an editor with the macro data in a file"""
1884 1933 filename = self.shell.mktempfile(macro.value)
1885 1934 self.shell.hooks.editor(filename)
1886 1935
1887 1936 # and make a new macro object, to replace the old one
1888 1937 mfile = open(filename)
1889 1938 mvalue = mfile.read()
1890 1939 mfile.close()
1891 1940 self.shell.user_ns[mname] = Macro(mvalue)
1892 1941
1893 1942 def magic_ed(self,parameter_s=''):
1894 1943 """Alias to %edit."""
1895 1944 return self.magic_edit(parameter_s)
1896 1945
1897 1946 def magic_edit(self,parameter_s='',last_call=['','']):
1898 1947 """Bring up an editor and execute the resulting code.
1899 1948
1900 1949 Usage:
1901 1950 %edit [options] [args]
1902 1951
1903 1952 %edit runs IPython's editor hook. The default version of this hook is
1904 1953 set to call the __IPYTHON__.rc.editor command. This is read from your
1905 1954 environment variable $EDITOR. If this isn't found, it will default to
1906 1955 vi under Linux/Unix and to notepad under Windows. See the end of this
1907 1956 docstring for how to change the editor hook.
1908 1957
1909 1958 You can also set the value of this editor via the command line option
1910 1959 '-editor' or in your ipythonrc file. This is useful if you wish to use
1911 1960 specifically for IPython an editor different from your typical default
1912 1961 (and for Windows users who typically don't set environment variables).
1913 1962
1914 1963 This command allows you to conveniently edit multi-line code right in
1915 1964 your IPython session.
1916 1965
1917 1966 If called without arguments, %edit opens up an empty editor with a
1918 1967 temporary file and will execute the contents of this file when you
1919 1968 close it (don't forget to save it!).
1920 1969
1921 1970
1922 1971 Options:
1923 1972
1924 1973 -n <number>: open the editor at a specified line number. By default,
1925 1974 the IPython editor hook uses the unix syntax 'editor +N filename', but
1926 1975 you can configure this by providing your own modified hook if your
1927 1976 favorite editor supports line-number specifications with a different
1928 1977 syntax.
1929 1978
1930 1979 -p: this will call the editor with the same data as the previous time
1931 1980 it was used, regardless of how long ago (in your current session) it
1932 1981 was.
1933 1982
1934 1983 -r: use 'raw' input. This option only applies to input taken from the
1935 1984 user's history. By default, the 'processed' history is used, so that
1936 1985 magics are loaded in their transformed version to valid Python. If
1937 1986 this option is given, the raw input as typed as the command line is
1938 1987 used instead. When you exit the editor, it will be executed by
1939 1988 IPython's own processor.
1940 1989
1941 1990 -x: do not execute the edited code immediately upon exit. This is
1942 1991 mainly useful if you are editing programs which need to be called with
1943 1992 command line arguments, which you can then do using %run.
1944 1993
1945 1994
1946 1995 Arguments:
1947 1996
1948 1997 If arguments are given, the following possibilites exist:
1949 1998
1950 1999 - The arguments are numbers or pairs of colon-separated numbers (like
1951 2000 1 4:8 9). These are interpreted as lines of previous input to be
1952 2001 loaded into the editor. The syntax is the same of the %macro command.
1953 2002
1954 2003 - If the argument doesn't start with a number, it is evaluated as a
1955 2004 variable and its contents loaded into the editor. You can thus edit
1956 2005 any string which contains python code (including the result of
1957 2006 previous edits).
1958 2007
1959 2008 - If the argument is the name of an object (other than a string),
1960 2009 IPython will try to locate the file where it was defined and open the
1961 2010 editor at the point where it is defined. You can use `%edit function`
1962 2011 to load an editor exactly at the point where 'function' is defined,
1963 2012 edit it and have the file be executed automatically.
1964 2013
1965 2014 If the object is a macro (see %macro for details), this opens up your
1966 2015 specified editor with a temporary file containing the macro's data.
1967 2016 Upon exit, the macro is reloaded with the contents of the file.
1968 2017
1969 2018 Note: opening at an exact line is only supported under Unix, and some
1970 2019 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1971 2020 '+NUMBER' parameter necessary for this feature. Good editors like
1972 2021 (X)Emacs, vi, jed, pico and joe all do.
1973 2022
1974 2023 - If the argument is not found as a variable, IPython will look for a
1975 2024 file with that name (adding .py if necessary) and load it into the
1976 2025 editor. It will execute its contents with execfile() when you exit,
1977 2026 loading any code in the file into your interactive namespace.
1978 2027
1979 2028 After executing your code, %edit will return as output the code you
1980 2029 typed in the editor (except when it was an existing file). This way
1981 2030 you can reload the code in further invocations of %edit as a variable,
1982 2031 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1983 2032 the output.
1984 2033
1985 2034 Note that %edit is also available through the alias %ed.
1986 2035
1987 2036 This is an example of creating a simple function inside the editor and
1988 2037 then modifying it. First, start up the editor:
1989 2038
1990 2039 In [1]: ed\\
1991 2040 Editing... done. Executing edited code...\\
1992 2041 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1993 2042
1994 2043 We can then call the function foo():
1995 2044
1996 2045 In [2]: foo()\\
1997 2046 foo() was defined in an editing session
1998 2047
1999 2048 Now we edit foo. IPython automatically loads the editor with the
2000 2049 (temporary) file where foo() was previously defined:
2001 2050
2002 2051 In [3]: ed foo\\
2003 2052 Editing... done. Executing edited code...
2004 2053
2005 2054 And if we call foo() again we get the modified version:
2006 2055
2007 2056 In [4]: foo()\\
2008 2057 foo() has now been changed!
2009 2058
2010 2059 Here is an example of how to edit a code snippet successive
2011 2060 times. First we call the editor:
2012 2061
2013 2062 In [8]: ed\\
2014 2063 Editing... done. Executing edited code...\\
2015 2064 hello\\
2016 2065 Out[8]: "print 'hello'\\n"
2017 2066
2018 2067 Now we call it again with the previous output (stored in _):
2019 2068
2020 2069 In [9]: ed _\\
2021 2070 Editing... done. Executing edited code...\\
2022 2071 hello world\\
2023 2072 Out[9]: "print 'hello world'\\n"
2024 2073
2025 2074 Now we call it with the output #8 (stored in _8, also as Out[8]):
2026 2075
2027 2076 In [10]: ed _8\\
2028 2077 Editing... done. Executing edited code...\\
2029 2078 hello again\\
2030 2079 Out[10]: "print 'hello again'\\n"
2031 2080
2032 2081
2033 2082 Changing the default editor hook:
2034 2083
2035 2084 If you wish to write your own editor hook, you can put it in a
2036 2085 configuration file which you load at startup time. The default hook
2037 2086 is defined in the IPython.hooks module, and you can use that as a
2038 2087 starting example for further modifications. That file also has
2039 2088 general instructions on how to set a new hook for use once you've
2040 2089 defined it."""
2041 2090
2042 2091 # FIXME: This function has become a convoluted mess. It needs a
2043 2092 # ground-up rewrite with clean, simple logic.
2044 2093
2045 2094 def make_filename(arg):
2046 2095 "Make a filename from the given args"
2047 2096 try:
2048 2097 filename = get_py_filename(arg)
2049 2098 except IOError:
2050 2099 if args.endswith('.py'):
2051 2100 filename = arg
2052 2101 else:
2053 2102 filename = None
2054 2103 return filename
2055 2104
2056 2105 # custom exceptions
2057 2106 class DataIsObject(Exception): pass
2058 2107
2059 2108 opts,args = self.parse_options(parameter_s,'prxn:')
2060 2109 # Set a few locals from the options for convenience:
2061 2110 opts_p = opts.has_key('p')
2062 2111 opts_r = opts.has_key('r')
2063 2112
2064 2113 # Default line number value
2065 2114 lineno = opts.get('n',None)
2066 2115
2067 2116 if opts_p:
2068 2117 args = '_%s' % last_call[0]
2069 2118 if not self.shell.user_ns.has_key(args):
2070 2119 args = last_call[1]
2071 2120
2072 2121 # use last_call to remember the state of the previous call, but don't
2073 2122 # let it be clobbered by successive '-p' calls.
2074 2123 try:
2075 2124 last_call[0] = self.shell.outputcache.prompt_count
2076 2125 if not opts_p:
2077 2126 last_call[1] = parameter_s
2078 2127 except:
2079 2128 pass
2080 2129
2081 2130 # by default this is done with temp files, except when the given
2082 2131 # arg is a filename
2083 2132 use_temp = 1
2084 2133
2085 2134 if re.match(r'\d',args):
2086 2135 # Mode where user specifies ranges of lines, like in %macro.
2087 2136 # This means that you can't edit files whose names begin with
2088 2137 # numbers this way. Tough.
2089 2138 ranges = args.split()
2090 2139 data = ''.join(self.extract_input_slices(ranges,opts_r))
2091 2140 elif args.endswith('.py'):
2092 2141 filename = make_filename(args)
2093 2142 data = ''
2094 2143 use_temp = 0
2095 2144 elif args:
2096 2145 try:
2097 2146 # Load the parameter given as a variable. If not a string,
2098 2147 # process it as an object instead (below)
2099 2148
2100 2149 #print '*** args',args,'type',type(args) # dbg
2101 2150 data = eval(args,self.shell.user_ns)
2102 2151 if not type(data) in StringTypes:
2103 2152 raise DataIsObject
2104 2153
2105 2154 except (NameError,SyntaxError):
2106 2155 # given argument is not a variable, try as a filename
2107 2156 filename = make_filename(args)
2108 2157 if filename is None:
2109 2158 warn("Argument given (%s) can't be found as a variable "
2110 2159 "or as a filename." % args)
2111 2160 return
2112 2161
2113 2162 data = ''
2114 2163 use_temp = 0
2115 2164 except DataIsObject:
2116 2165
2117 2166 # macros have a special edit function
2118 2167 if isinstance(data,Macro):
2119 2168 self._edit_macro(args,data)
2120 2169 return
2121 2170
2122 2171 # For objects, try to edit the file where they are defined
2123 2172 try:
2124 2173 filename = inspect.getabsfile(data)
2125 2174 datafile = 1
2126 2175 except TypeError:
2127 2176 filename = make_filename(args)
2128 2177 datafile = 1
2129 2178 warn('Could not find file where `%s` is defined.\n'
2130 2179 'Opening a file named `%s`' % (args,filename))
2131 2180 # Now, make sure we can actually read the source (if it was in
2132 2181 # a temp file it's gone by now).
2133 2182 if datafile:
2134 2183 try:
2135 2184 if lineno is None:
2136 2185 lineno = inspect.getsourcelines(data)[1]
2137 2186 except IOError:
2138 2187 filename = make_filename(args)
2139 2188 if filename is None:
2140 2189 warn('The file `%s` where `%s` was defined cannot '
2141 2190 'be read.' % (filename,data))
2142 2191 return
2143 2192 use_temp = 0
2144 2193 else:
2145 2194 data = ''
2146 2195
2147 2196 if use_temp:
2148 2197 filename = self.shell.mktempfile(data)
2149 2198 print 'IPython will make a temporary file named:',filename
2150 2199
2151 2200 # do actual editing here
2152 2201 print 'Editing...',
2153 2202 sys.stdout.flush()
2154 2203 self.shell.hooks.editor(filename,lineno)
2155 2204 if opts.has_key('x'): # -x prevents actual execution
2156 2205 print
2157 2206 else:
2158 2207 print 'done. Executing edited code...'
2159 2208 if opts_r:
2160 2209 self.shell.runlines(file_read(filename))
2161 2210 else:
2162 2211 self.shell.safe_execfile(filename,self.shell.user_ns)
2163 2212 if use_temp:
2164 2213 try:
2165 2214 return open(filename).read()
2166 2215 except IOError,msg:
2167 2216 if msg.filename == filename:
2168 2217 warn('File not found. Did you forget to save?')
2169 2218 return
2170 2219 else:
2171 2220 self.shell.showtraceback()
2172 2221
2173 2222 def magic_xmode(self,parameter_s = ''):
2174 2223 """Switch modes for the exception handlers.
2175 2224
2176 2225 Valid modes: Plain, Context and Verbose.
2177 2226
2178 2227 If called without arguments, acts as a toggle."""
2179 2228
2180 2229 def xmode_switch_err(name):
2181 2230 warn('Error changing %s exception modes.\n%s' %
2182 2231 (name,sys.exc_info()[1]))
2183 2232
2184 2233 shell = self.shell
2185 2234 new_mode = parameter_s.strip().capitalize()
2186 2235 try:
2187 2236 shell.InteractiveTB.set_mode(mode=new_mode)
2188 2237 print 'Exception reporting mode:',shell.InteractiveTB.mode
2189 2238 except:
2190 2239 xmode_switch_err('user')
2191 2240
2192 2241 # threaded shells use a special handler in sys.excepthook
2193 2242 if shell.isthreaded:
2194 2243 try:
2195 2244 shell.sys_excepthook.set_mode(mode=new_mode)
2196 2245 except:
2197 2246 xmode_switch_err('threaded')
2198 2247
2199 2248 def magic_colors(self,parameter_s = ''):
2200 2249 """Switch color scheme for prompts, info system and exception handlers.
2201 2250
2202 2251 Currently implemented schemes: NoColor, Linux, LightBG.
2203 2252
2204 2253 Color scheme names are not case-sensitive."""
2205 2254
2206 2255 def color_switch_err(name):
2207 2256 warn('Error changing %s color schemes.\n%s' %
2208 2257 (name,sys.exc_info()[1]))
2209 2258
2210 2259
2211 2260 new_scheme = parameter_s.strip()
2212 2261 if not new_scheme:
2213 2262 print 'You must specify a color scheme.'
2214 2263 return
2215 2264 import IPython.rlineimpl as readline
2216 2265 if not readline.have_readline:
2217 2266 msg = """\
2218 2267 Proper color support under MS Windows requires the pyreadline library.
2219 2268 You can find it at:
2220 2269 http://ipython.scipy.org/moin/PyReadline/Intro
2221 2270 Gary's readline needs the ctypes module, from:
2222 2271 http://starship.python.net/crew/theller/ctypes
2223 2272 (Note that ctypes is already part of Python versions 2.5 and newer).
2224 2273
2225 2274 Defaulting color scheme to 'NoColor'"""
2226 2275 new_scheme = 'NoColor'
2227 2276 warn(msg)
2228 2277 # local shortcut
2229 2278 shell = self.shell
2230 2279
2231 2280 # Set prompt colors
2232 2281 try:
2233 2282 shell.outputcache.set_colors(new_scheme)
2234 2283 except:
2235 2284 color_switch_err('prompt')
2236 2285 else:
2237 2286 shell.rc.colors = \
2238 2287 shell.outputcache.color_table.active_scheme_name
2239 2288 # Set exception colors
2240 2289 try:
2241 2290 shell.InteractiveTB.set_colors(scheme = new_scheme)
2242 2291 shell.SyntaxTB.set_colors(scheme = new_scheme)
2243 2292 except:
2244 2293 color_switch_err('exception')
2245 2294
2246 2295 # threaded shells use a verbose traceback in sys.excepthook
2247 2296 if shell.isthreaded:
2248 2297 try:
2249 2298 shell.sys_excepthook.set_colors(scheme=new_scheme)
2250 2299 except:
2251 2300 color_switch_err('system exception handler')
2252 2301
2253 2302 # Set info (for 'object?') colors
2254 2303 if shell.rc.color_info:
2255 2304 try:
2256 2305 shell.inspector.set_active_scheme(new_scheme)
2257 2306 except:
2258 2307 color_switch_err('object inspector')
2259 2308 else:
2260 2309 shell.inspector.set_active_scheme('NoColor')
2261 2310
2262 2311 def magic_color_info(self,parameter_s = ''):
2263 2312 """Toggle color_info.
2264 2313
2265 2314 The color_info configuration parameter controls whether colors are
2266 2315 used for displaying object details (by things like %psource, %pfile or
2267 2316 the '?' system). This function toggles this value with each call.
2268 2317
2269 2318 Note that unless you have a fairly recent pager (less works better
2270 2319 than more) in your system, using colored object information displays
2271 2320 will not work properly. Test it and see."""
2272 2321
2273 2322 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2274 2323 self.magic_colors(self.shell.rc.colors)
2275 2324 print 'Object introspection functions have now coloring:',
2276 2325 print ['OFF','ON'][self.shell.rc.color_info]
2277 2326
2278 2327 def magic_Pprint(self, parameter_s=''):
2279 2328 """Toggle pretty printing on/off."""
2280 2329
2281 2330 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2282 2331 print 'Pretty printing has been turned', \
2283 2332 ['OFF','ON'][self.shell.rc.pprint]
2284 2333
2285 2334 def magic_exit(self, parameter_s=''):
2286 2335 """Exit IPython, confirming if configured to do so.
2287 2336
2288 2337 You can configure whether IPython asks for confirmation upon exit by
2289 2338 setting the confirm_exit flag in the ipythonrc file."""
2290 2339
2291 2340 self.shell.exit()
2292 2341
2293 2342 def magic_quit(self, parameter_s=''):
2294 2343 """Exit IPython, confirming if configured to do so (like %exit)"""
2295 2344
2296 2345 self.shell.exit()
2297 2346
2298 2347 def magic_Exit(self, parameter_s=''):
2299 2348 """Exit IPython without confirmation."""
2300 2349
2301 2350 self.shell.exit_now = True
2302 2351
2303 2352 def magic_Quit(self, parameter_s=''):
2304 2353 """Exit IPython without confirmation (like %Exit)."""
2305 2354
2306 2355 self.shell.exit_now = True
2307 2356
2308 2357 #......................................................................
2309 2358 # Functions to implement unix shell-type things
2310 2359
2311 2360 def magic_alias(self, parameter_s = ''):
2312 2361 """Define an alias for a system command.
2313 2362
2314 2363 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2315 2364
2316 2365 Then, typing 'alias_name params' will execute the system command 'cmd
2317 2366 params' (from your underlying operating system).
2318 2367
2319 2368 Aliases have lower precedence than magic functions and Python normal
2320 2369 variables, so if 'foo' is both a Python variable and an alias, the
2321 2370 alias can not be executed until 'del foo' removes the Python variable.
2322 2371
2323 2372 You can use the %l specifier in an alias definition to represent the
2324 2373 whole line when the alias is called. For example:
2325 2374
2326 2375 In [2]: alias all echo "Input in brackets: <%l>"\\
2327 2376 In [3]: all hello world\\
2328 2377 Input in brackets: <hello world>
2329 2378
2330 2379 You can also define aliases with parameters using %s specifiers (one
2331 2380 per parameter):
2332 2381
2333 2382 In [1]: alias parts echo first %s second %s\\
2334 2383 In [2]: %parts A B\\
2335 2384 first A second B\\
2336 2385 In [3]: %parts A\\
2337 2386 Incorrect number of arguments: 2 expected.\\
2338 2387 parts is an alias to: 'echo first %s second %s'
2339 2388
2340 2389 Note that %l and %s are mutually exclusive. You can only use one or
2341 2390 the other in your aliases.
2342 2391
2343 2392 Aliases expand Python variables just like system calls using ! or !!
2344 2393 do: all expressions prefixed with '$' get expanded. For details of
2345 2394 the semantic rules, see PEP-215:
2346 2395 http://www.python.org/peps/pep-0215.html. This is the library used by
2347 2396 IPython for variable expansion. If you want to access a true shell
2348 2397 variable, an extra $ is necessary to prevent its expansion by IPython:
2349 2398
2350 2399 In [6]: alias show echo\\
2351 2400 In [7]: PATH='A Python string'\\
2352 2401 In [8]: show $PATH\\
2353 2402 A Python string\\
2354 2403 In [9]: show $$PATH\\
2355 2404 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2356 2405
2357 2406 You can use the alias facility to acess all of $PATH. See the %rehash
2358 2407 and %rehashx functions, which automatically create aliases for the
2359 2408 contents of your $PATH.
2360 2409
2361 2410 If called with no parameters, %alias prints the current alias table."""
2362 2411
2363 2412 par = parameter_s.strip()
2364 2413 if not par:
2365 2414 stored = self.db.get('stored_aliases', {} )
2366 2415 atab = self.shell.alias_table
2367 2416 aliases = atab.keys()
2368 2417 aliases.sort()
2369 2418 res = []
2370 2419 showlast = []
2371 2420 for alias in aliases:
2372 2421 tgt = atab[alias][1]
2373 2422 # 'interesting' aliases
2374 2423 if (alias in stored or
2375 2424 alias != os.path.splitext(tgt)[0] or
2376 2425 ' ' in tgt):
2377 2426 showlast.append((alias, tgt))
2378 2427 else:
2379 2428 res.append((alias, tgt ))
2380 2429
2381 2430 # show most interesting aliases last
2382 2431 res.extend(showlast)
2383 2432 print "Total number of aliases:",len(aliases)
2384 2433 return res
2385 2434 try:
2386 2435 alias,cmd = par.split(None,1)
2387 2436 except:
2388 2437 print OInspect.getdoc(self.magic_alias)
2389 2438 else:
2390 2439 nargs = cmd.count('%s')
2391 2440 if nargs>0 and cmd.find('%l')>=0:
2392 2441 error('The %s and %l specifiers are mutually exclusive '
2393 2442 'in alias definitions.')
2394 2443 else: # all looks OK
2395 2444 self.shell.alias_table[alias] = (nargs,cmd)
2396 2445 self.shell.alias_table_validate(verbose=0)
2397 2446 # end magic_alias
2398 2447
2399 2448 def magic_unalias(self, parameter_s = ''):
2400 2449 """Remove an alias"""
2401 2450
2402 2451 aname = parameter_s.strip()
2403 2452 if aname in self.shell.alias_table:
2404 2453 del self.shell.alias_table[aname]
2405 2454 stored = self.db.get('stored_aliases', {} )
2406 2455 if aname in stored:
2407 2456 print "Removing %stored alias",aname
2408 2457 del stored[aname]
2409 2458 self.db['stored_aliases'] = stored
2410 2459
2411 2460 def magic_rehash(self, parameter_s = ''):
2412 2461 """Update the alias table with all entries in $PATH.
2413 2462
2414 2463 This version does no checks on execute permissions or whether the
2415 2464 contents of $PATH are truly files (instead of directories or something
2416 2465 else). For such a safer (but slower) version, use %rehashx."""
2417 2466
2418 2467 # This function (and rehashx) manipulate the alias_table directly
2419 2468 # rather than calling magic_alias, for speed reasons. A rehash on a
2420 2469 # typical Linux box involves several thousand entries, so efficiency
2421 2470 # here is a top concern.
2422 2471
2423 2472 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2424 2473 alias_table = self.shell.alias_table
2425 2474 for pdir in path:
2426 2475 for ff in os.listdir(pdir):
2427 2476 # each entry in the alias table must be (N,name), where
2428 2477 # N is the number of positional arguments of the alias.
2429 2478 alias_table[ff] = (0,ff)
2430 2479 # Make sure the alias table doesn't contain keywords or builtins
2431 2480 self.shell.alias_table_validate()
2432 2481 # Call again init_auto_alias() so we get 'rm -i' and other modified
2433 2482 # aliases since %rehash will probably clobber them
2434 2483 self.shell.init_auto_alias()
2435 2484
2436 2485 def magic_rehashx(self, parameter_s = ''):
2437 2486 """Update the alias table with all executable files in $PATH.
2438 2487
2439 2488 This version explicitly checks that every entry in $PATH is a file
2440 2489 with execute access (os.X_OK), so it is much slower than %rehash.
2441 2490
2442 2491 Under Windows, it checks executability as a match agains a
2443 2492 '|'-separated string of extensions, stored in the IPython config
2444 2493 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2445 2494
2446 2495 path = [os.path.abspath(os.path.expanduser(p)) for p in
2447 2496 os.environ['PATH'].split(os.pathsep)]
2448 2497 path = filter(os.path.isdir,path)
2449 2498
2450 2499 alias_table = self.shell.alias_table
2451 2500 syscmdlist = []
2452 2501 if os.name == 'posix':
2453 2502 isexec = lambda fname:os.path.isfile(fname) and \
2454 2503 os.access(fname,os.X_OK)
2455 2504 else:
2456 2505
2457 2506 try:
2458 2507 winext = os.environ['pathext'].replace(';','|').replace('.','')
2459 2508 except KeyError:
2460 2509 winext = 'exe|com|bat|py'
2461 2510 if 'py' not in winext:
2462 2511 winext += '|py'
2463 2512 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2464 2513 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2465 2514 savedir = os.getcwd()
2466 2515 try:
2467 2516 # write the whole loop for posix/Windows so we don't have an if in
2468 2517 # the innermost part
2469 2518 if os.name == 'posix':
2470 2519 for pdir in path:
2471 2520 os.chdir(pdir)
2472 2521 for ff in os.listdir(pdir):
2473 2522 if isexec(ff) and ff not in self.shell.no_alias:
2474 2523 # each entry in the alias table must be (N,name),
2475 2524 # where N is the number of positional arguments of the
2476 2525 # alias.
2477 2526 alias_table[ff] = (0,ff)
2478 2527 syscmdlist.append(ff)
2479 2528 else:
2480 2529 for pdir in path:
2481 2530 os.chdir(pdir)
2482 2531 for ff in os.listdir(pdir):
2483 2532 if isexec(ff) and os.path.splitext(ff)[0] not in self.shell.no_alias:
2484 2533 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2485 2534 syscmdlist.append(ff)
2486 2535 # Make sure the alias table doesn't contain keywords or builtins
2487 2536 self.shell.alias_table_validate()
2488 2537 # Call again init_auto_alias() so we get 'rm -i' and other
2489 2538 # modified aliases since %rehashx will probably clobber them
2490 2539 self.shell.init_auto_alias()
2491 2540 db = self.getapi().db
2492 2541 db['syscmdlist'] = syscmdlist
2493 2542 finally:
2494 2543 os.chdir(savedir)
2495 2544
2496 2545 def magic_pwd(self, parameter_s = ''):
2497 2546 """Return the current working directory path."""
2498 2547 return os.getcwd()
2499 2548
2500 2549 def magic_cd(self, parameter_s=''):
2501 2550 """Change the current working directory.
2502 2551
2503 2552 This command automatically maintains an internal list of directories
2504 2553 you visit during your IPython session, in the variable _dh. The
2505 2554 command %dhist shows this history nicely formatted.
2506 2555
2507 2556 Usage:
2508 2557
2509 2558 cd 'dir': changes to directory 'dir'.
2510 2559
2511 2560 cd -: changes to the last visited directory.
2512 2561
2513 2562 cd -<n>: changes to the n-th directory in the directory history.
2514 2563
2515 2564 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2516 2565 (note: cd <bookmark_name> is enough if there is no
2517 2566 directory <bookmark_name>, but a bookmark with the name exists.)
2518 2567
2519 2568 Options:
2520 2569
2521 2570 -q: quiet. Do not print the working directory after the cd command is
2522 2571 executed. By default IPython's cd command does print this directory,
2523 2572 since the default prompts do not display path information.
2524 2573
2525 2574 Note that !cd doesn't work for this purpose because the shell where
2526 2575 !command runs is immediately discarded after executing 'command'."""
2527 2576
2528 2577 parameter_s = parameter_s.strip()
2529 2578 #bkms = self.shell.persist.get("bookmarks",{})
2530 2579
2531 2580 numcd = re.match(r'(-)(\d+)$',parameter_s)
2532 2581 # jump in directory history by number
2533 2582 if numcd:
2534 2583 nn = int(numcd.group(2))
2535 2584 try:
2536 2585 ps = self.shell.user_ns['_dh'][nn]
2537 2586 except IndexError:
2538 2587 print 'The requested directory does not exist in history.'
2539 2588 return
2540 2589 else:
2541 2590 opts = {}
2542 2591 else:
2543 2592 #turn all non-space-escaping backslashes to slashes,
2544 2593 # for c:\windows\directory\names\
2545 2594 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2546 2595 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2547 2596 # jump to previous
2548 2597 if ps == '-':
2549 2598 try:
2550 2599 ps = self.shell.user_ns['_dh'][-2]
2551 2600 except IndexError:
2552 2601 print 'No previous directory to change to.'
2553 2602 return
2554 2603 # jump to bookmark if needed
2555 2604 else:
2556 2605 if not os.path.isdir(ps) or opts.has_key('b'):
2557 2606 bkms = self.db.get('bookmarks', {})
2558 2607
2559 2608 if bkms.has_key(ps):
2560 2609 target = bkms[ps]
2561 2610 print '(bookmark:%s) -> %s' % (ps,target)
2562 2611 ps = target
2563 2612 else:
2564 2613 if opts.has_key('b'):
2565 2614 error("Bookmark '%s' not found. "
2566 2615 "Use '%%bookmark -l' to see your bookmarks." % ps)
2567 2616 return
2568 2617
2569 2618 # at this point ps should point to the target dir
2570 2619 if ps:
2571 2620 try:
2572 2621 os.chdir(os.path.expanduser(ps))
2573 2622 ttitle = ("IPy:" + (
2574 2623 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2575 2624 platutils.set_term_title(ttitle)
2576 2625 except OSError:
2577 2626 print sys.exc_info()[1]
2578 2627 else:
2579 2628 self.shell.user_ns['_dh'].append(os.getcwd())
2580 2629 else:
2581 2630 os.chdir(self.shell.home_dir)
2582 2631 platutils.set_term_title("IPy:~")
2583 2632 self.shell.user_ns['_dh'].append(os.getcwd())
2584 2633 if not 'q' in opts:
2585 2634 print self.shell.user_ns['_dh'][-1]
2586 2635
2587 2636 def magic_dhist(self, parameter_s=''):
2588 2637 """Print your history of visited directories.
2589 2638
2590 2639 %dhist -> print full history\\
2591 2640 %dhist n -> print last n entries only\\
2592 2641 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2593 2642
2594 2643 This history is automatically maintained by the %cd command, and
2595 2644 always available as the global list variable _dh. You can use %cd -<n>
2596 2645 to go to directory number <n>."""
2597 2646
2598 2647 dh = self.shell.user_ns['_dh']
2599 2648 if parameter_s:
2600 2649 try:
2601 2650 args = map(int,parameter_s.split())
2602 2651 except:
2603 2652 self.arg_err(Magic.magic_dhist)
2604 2653 return
2605 2654 if len(args) == 1:
2606 2655 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2607 2656 elif len(args) == 2:
2608 2657 ini,fin = args
2609 2658 else:
2610 2659 self.arg_err(Magic.magic_dhist)
2611 2660 return
2612 2661 else:
2613 2662 ini,fin = 0,len(dh)
2614 2663 nlprint(dh,
2615 2664 header = 'Directory history (kept in _dh)',
2616 2665 start=ini,stop=fin)
2617 2666
2618 2667 def magic_env(self, parameter_s=''):
2619 2668 """List environment variables."""
2620 2669
2621 2670 return os.environ.data
2622 2671
2623 2672 def magic_pushd(self, parameter_s=''):
2624 2673 """Place the current dir on stack and change directory.
2625 2674
2626 2675 Usage:\\
2627 2676 %pushd ['dirname']
2628 2677
2629 2678 %pushd with no arguments does a %pushd to your home directory.
2630 2679 """
2631 2680 if parameter_s == '': parameter_s = '~'
2632 2681 dir_s = self.shell.dir_stack
2633 2682 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2634 2683 os.path.expanduser(self.shell.dir_stack[0]):
2635 2684 try:
2636 2685 self.magic_cd(parameter_s)
2637 2686 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2638 2687 self.magic_dirs()
2639 2688 except:
2640 2689 print 'Invalid directory'
2641 2690 else:
2642 2691 print 'You are already there!'
2643 2692
2644 2693 def magic_popd(self, parameter_s=''):
2645 2694 """Change to directory popped off the top of the stack.
2646 2695 """
2647 2696 if len (self.shell.dir_stack) > 1:
2648 2697 self.shell.dir_stack.pop(0)
2649 2698 self.magic_cd(self.shell.dir_stack[0])
2650 2699 print self.shell.dir_stack[0]
2651 2700 else:
2652 2701 print "You can't remove the starting directory from the stack:",\
2653 2702 self.shell.dir_stack
2654 2703
2655 2704 def magic_dirs(self, parameter_s=''):
2656 2705 """Return the current directory stack."""
2657 2706
2658 2707 return self.shell.dir_stack[:]
2659 2708
2660 2709 def magic_sc(self, parameter_s=''):
2661 2710 """Shell capture - execute a shell command and capture its output.
2662 2711
2663 2712 DEPRECATED. Suboptimal, retained for backwards compatibility.
2664 2713
2665 2714 You should use the form 'var = !command' instead. Example:
2666 2715
2667 2716 "%sc -l myfiles = ls ~" should now be written as
2668 2717
2669 2718 "myfiles = !ls ~"
2670 2719
2671 2720 myfiles.s, myfiles.l and myfiles.n still apply as documented
2672 2721 below.
2673 2722
2674 2723 --
2675 2724 %sc [options] varname=command
2676 2725
2677 2726 IPython will run the given command using commands.getoutput(), and
2678 2727 will then update the user's interactive namespace with a variable
2679 2728 called varname, containing the value of the call. Your command can
2680 2729 contain shell wildcards, pipes, etc.
2681 2730
2682 2731 The '=' sign in the syntax is mandatory, and the variable name you
2683 2732 supply must follow Python's standard conventions for valid names.
2684 2733
2685 2734 (A special format without variable name exists for internal use)
2686 2735
2687 2736 Options:
2688 2737
2689 2738 -l: list output. Split the output on newlines into a list before
2690 2739 assigning it to the given variable. By default the output is stored
2691 2740 as a single string.
2692 2741
2693 2742 -v: verbose. Print the contents of the variable.
2694 2743
2695 2744 In most cases you should not need to split as a list, because the
2696 2745 returned value is a special type of string which can automatically
2697 2746 provide its contents either as a list (split on newlines) or as a
2698 2747 space-separated string. These are convenient, respectively, either
2699 2748 for sequential processing or to be passed to a shell command.
2700 2749
2701 2750 For example:
2702 2751
2703 2752 # Capture into variable a
2704 2753 In [9]: sc a=ls *py
2705 2754
2706 2755 # a is a string with embedded newlines
2707 2756 In [10]: a
2708 2757 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2709 2758
2710 2759 # which can be seen as a list:
2711 2760 In [11]: a.l
2712 2761 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2713 2762
2714 2763 # or as a whitespace-separated string:
2715 2764 In [12]: a.s
2716 2765 Out[12]: 'setup.py win32_manual_post_install.py'
2717 2766
2718 2767 # a.s is useful to pass as a single command line:
2719 2768 In [13]: !wc -l $a.s
2720 2769 146 setup.py
2721 2770 130 win32_manual_post_install.py
2722 2771 276 total
2723 2772
2724 2773 # while the list form is useful to loop over:
2725 2774 In [14]: for f in a.l:
2726 2775 ....: !wc -l $f
2727 2776 ....:
2728 2777 146 setup.py
2729 2778 130 win32_manual_post_install.py
2730 2779
2731 2780 Similiarly, the lists returned by the -l option are also special, in
2732 2781 the sense that you can equally invoke the .s attribute on them to
2733 2782 automatically get a whitespace-separated string from their contents:
2734 2783
2735 2784 In [1]: sc -l b=ls *py
2736 2785
2737 2786 In [2]: b
2738 2787 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2739 2788
2740 2789 In [3]: b.s
2741 2790 Out[3]: 'setup.py win32_manual_post_install.py'
2742 2791
2743 2792 In summary, both the lists and strings used for ouptut capture have
2744 2793 the following special attributes:
2745 2794
2746 2795 .l (or .list) : value as list.
2747 2796 .n (or .nlstr): value as newline-separated string.
2748 2797 .s (or .spstr): value as space-separated string.
2749 2798 """
2750 2799
2751 2800 opts,args = self.parse_options(parameter_s,'lv')
2752 2801 # Try to get a variable name and command to run
2753 2802 try:
2754 2803 # the variable name must be obtained from the parse_options
2755 2804 # output, which uses shlex.split to strip options out.
2756 2805 var,_ = args.split('=',1)
2757 2806 var = var.strip()
2758 2807 # But the the command has to be extracted from the original input
2759 2808 # parameter_s, not on what parse_options returns, to avoid the
2760 2809 # quote stripping which shlex.split performs on it.
2761 2810 _,cmd = parameter_s.split('=',1)
2762 2811 except ValueError:
2763 2812 var,cmd = '',''
2764 2813 # If all looks ok, proceed
2765 2814 out,err = self.shell.getoutputerror(cmd)
2766 2815 if err:
2767 2816 print >> Term.cerr,err
2768 2817 if opts.has_key('l'):
2769 2818 out = SList(out.split('\n'))
2770 2819 else:
2771 2820 out = LSString(out)
2772 2821 if opts.has_key('v'):
2773 2822 print '%s ==\n%s' % (var,pformat(out))
2774 2823 if var:
2775 2824 self.shell.user_ns.update({var:out})
2776 2825 else:
2777 2826 return out
2778 2827
2779 2828 def magic_sx(self, parameter_s=''):
2780 2829 """Shell execute - run a shell command and capture its output.
2781 2830
2782 2831 %sx command
2783 2832
2784 2833 IPython will run the given command using commands.getoutput(), and
2785 2834 return the result formatted as a list (split on '\\n'). Since the
2786 2835 output is _returned_, it will be stored in ipython's regular output
2787 2836 cache Out[N] and in the '_N' automatic variables.
2788 2837
2789 2838 Notes:
2790 2839
2791 2840 1) If an input line begins with '!!', then %sx is automatically
2792 2841 invoked. That is, while:
2793 2842 !ls
2794 2843 causes ipython to simply issue system('ls'), typing
2795 2844 !!ls
2796 2845 is a shorthand equivalent to:
2797 2846 %sx ls
2798 2847
2799 2848 2) %sx differs from %sc in that %sx automatically splits into a list,
2800 2849 like '%sc -l'. The reason for this is to make it as easy as possible
2801 2850 to process line-oriented shell output via further python commands.
2802 2851 %sc is meant to provide much finer control, but requires more
2803 2852 typing.
2804 2853
2805 2854 3) Just like %sc -l, this is a list with special attributes:
2806 2855
2807 2856 .l (or .list) : value as list.
2808 2857 .n (or .nlstr): value as newline-separated string.
2809 2858 .s (or .spstr): value as whitespace-separated string.
2810 2859
2811 2860 This is very useful when trying to use such lists as arguments to
2812 2861 system commands."""
2813 2862
2814 2863 if parameter_s:
2815 2864 out,err = self.shell.getoutputerror(parameter_s)
2816 2865 if err:
2817 2866 print >> Term.cerr,err
2818 2867 return SList(out.split('\n'))
2819 2868
2820 2869 def magic_bg(self, parameter_s=''):
2821 2870 """Run a job in the background, in a separate thread.
2822 2871
2823 2872 For example,
2824 2873
2825 2874 %bg myfunc(x,y,z=1)
2826 2875
2827 2876 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2828 2877 execution starts, a message will be printed indicating the job
2829 2878 number. If your job number is 5, you can use
2830 2879
2831 2880 myvar = jobs.result(5) or myvar = jobs[5].result
2832 2881
2833 2882 to assign this result to variable 'myvar'.
2834 2883
2835 2884 IPython has a job manager, accessible via the 'jobs' object. You can
2836 2885 type jobs? to get more information about it, and use jobs.<TAB> to see
2837 2886 its attributes. All attributes not starting with an underscore are
2838 2887 meant for public use.
2839 2888
2840 2889 In particular, look at the jobs.new() method, which is used to create
2841 2890 new jobs. This magic %bg function is just a convenience wrapper
2842 2891 around jobs.new(), for expression-based jobs. If you want to create a
2843 2892 new job with an explicit function object and arguments, you must call
2844 2893 jobs.new() directly.
2845 2894
2846 2895 The jobs.new docstring also describes in detail several important
2847 2896 caveats associated with a thread-based model for background job
2848 2897 execution. Type jobs.new? for details.
2849 2898
2850 2899 You can check the status of all jobs with jobs.status().
2851 2900
2852 2901 The jobs variable is set by IPython into the Python builtin namespace.
2853 2902 If you ever declare a variable named 'jobs', you will shadow this
2854 2903 name. You can either delete your global jobs variable to regain
2855 2904 access to the job manager, or make a new name and assign it manually
2856 2905 to the manager (stored in IPython's namespace). For example, to
2857 2906 assign the job manager to the Jobs name, use:
2858 2907
2859 2908 Jobs = __builtins__.jobs"""
2860 2909
2861 2910 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2862 2911
2863 2912
2864 2913 def magic_bookmark(self, parameter_s=''):
2865 2914 """Manage IPython's bookmark system.
2866 2915
2867 2916 %bookmark <name> - set bookmark to current dir
2868 2917 %bookmark <name> <dir> - set bookmark to <dir>
2869 2918 %bookmark -l - list all bookmarks
2870 2919 %bookmark -d <name> - remove bookmark
2871 2920 %bookmark -r - remove all bookmarks
2872 2921
2873 2922 You can later on access a bookmarked folder with:
2874 2923 %cd -b <name>
2875 2924 or simply '%cd <name>' if there is no directory called <name> AND
2876 2925 there is such a bookmark defined.
2877 2926
2878 2927 Your bookmarks persist through IPython sessions, but they are
2879 2928 associated with each profile."""
2880 2929
2881 2930 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2882 2931 if len(args) > 2:
2883 2932 error('You can only give at most two arguments')
2884 2933 return
2885 2934
2886 2935 bkms = self.db.get('bookmarks',{})
2887 2936
2888 2937 if opts.has_key('d'):
2889 2938 try:
2890 2939 todel = args[0]
2891 2940 except IndexError:
2892 2941 error('You must provide a bookmark to delete')
2893 2942 else:
2894 2943 try:
2895 2944 del bkms[todel]
2896 2945 except:
2897 2946 error("Can't delete bookmark '%s'" % todel)
2898 2947 elif opts.has_key('r'):
2899 2948 bkms = {}
2900 2949 elif opts.has_key('l'):
2901 2950 bks = bkms.keys()
2902 2951 bks.sort()
2903 2952 if bks:
2904 2953 size = max(map(len,bks))
2905 2954 else:
2906 2955 size = 0
2907 2956 fmt = '%-'+str(size)+'s -> %s'
2908 2957 print 'Current bookmarks:'
2909 2958 for bk in bks:
2910 2959 print fmt % (bk,bkms[bk])
2911 2960 else:
2912 2961 if not args:
2913 2962 error("You must specify the bookmark name")
2914 2963 elif len(args)==1:
2915 2964 bkms[args[0]] = os.getcwd()
2916 2965 elif len(args)==2:
2917 2966 bkms[args[0]] = args[1]
2918 2967 self.db['bookmarks'] = bkms
2919 2968
2920 2969 def magic_pycat(self, parameter_s=''):
2921 2970 """Show a syntax-highlighted file through a pager.
2922 2971
2923 2972 This magic is similar to the cat utility, but it will assume the file
2924 2973 to be Python source and will show it with syntax highlighting. """
2925 2974
2926 2975 try:
2927 2976 filename = get_py_filename(parameter_s)
2928 2977 cont = file_read(filename)
2929 2978 except IOError:
2930 2979 try:
2931 2980 cont = eval(parameter_s,self.user_ns)
2932 2981 except NameError:
2933 2982 cont = None
2934 2983 if cont is None:
2935 2984 print "Error: no such file or variable"
2936 2985 return
2937 2986
2938 2987 page(self.shell.pycolorize(cont),
2939 2988 screen_lines=self.shell.rc.screen_length)
2940 2989
2941 2990 def magic_cpaste(self, parameter_s=''):
2942 2991 """Allows you to paste & execute a pre-formatted code block from clipboard
2943 2992
2944 2993 You must terminate the block with '--' (two minus-signs) alone on the
2945 2994 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2946 2995 is the new sentinel for this operation)
2947 2996
2948 2997 The block is dedented prior to execution to enable execution of
2949 2998 method definitions. '>' characters at the beginning of a line is
2950 2999 ignored, to allow pasting directly from e-mails. The executed block
2951 3000 is also assigned to variable named 'pasted_block' for later editing
2952 3001 with '%edit pasted_block'.
2953 3002
2954 3003 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2955 3004 This assigns the pasted block to variable 'foo' as string, without
2956 3005 dedenting or executing it.
2957 3006
2958 3007 Do not be alarmed by garbled output on Windows (it's a readline bug).
2959 3008 Just press enter and type -- (and press enter again) and the block
2960 3009 will be what was just pasted.
2961 3010
2962 3011 IPython statements (magics, shell escapes) are not supported (yet).
2963 3012 """
2964 3013 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2965 3014 par = args.strip()
2966 3015 sentinel = opts.get('s','--')
2967 3016
2968 3017 from IPython import iplib
2969 3018 lines = []
2970 3019 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2971 3020 while 1:
2972 3021 l = iplib.raw_input_original(':')
2973 3022 if l ==sentinel:
2974 3023 break
2975 3024 lines.append(l.lstrip('>'))
2976 3025 block = "\n".join(lines) + '\n'
2977 3026 #print "block:\n",block
2978 3027 if not par:
2979 3028 b = textwrap.dedent(block)
2980 3029 exec b in self.user_ns
2981 3030 self.user_ns['pasted_block'] = b
2982 3031 else:
2983 3032 self.user_ns[par] = block
2984 3033 print "Block assigned to '%s'" % par
2985 3034
2986 3035 def magic_quickref(self,arg):
2987 3036 """ Show a quick reference sheet """
2988 3037 import IPython.usage
2989 3038 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
2990 3039
2991 3040 page(qr)
2992 3041
2993 3042 def magic_upgrade(self,arg):
2994 3043 """ Upgrade your IPython installation
2995 3044
2996 3045 This will copy the config files that don't yet exist in your
2997 3046 ipython dir from the system config dir. Use this after upgrading
2998 3047 IPython if you don't wish to delete your .ipython dir.
2999 3048
3000 3049 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3001 3050 new users)
3002 3051
3003 3052 """
3004 3053 ip = self.getapi()
3005 3054 ipinstallation = path(IPython.__file__).dirname()
3006 3055 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3007 3056 src_config = ipinstallation / 'UserConfig'
3008 3057 userdir = path(ip.options.ipythondir)
3009 3058 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3010 3059 print ">",cmd
3011 3060 shell(cmd)
3012 3061 if arg == '-nolegacy':
3013 3062 legacy = userdir.files('ipythonrc*')
3014 3063 print "Nuking legacy files:",legacy
3015 3064
3016 3065 [p.remove() for p in legacy]
3017 3066 suffix = (sys.platform == 'win32' and '.ini' or '')
3018 3067 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3019 3068
3020 3069
3021 3070 # end Magic
@@ -1,607 +1,616 b''
1 1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 1329 2006-05-26 07:52:45Z fperez $
2 # $Id: ipythonrc 1879 2006-11-04 00:34:34Z fptest $
3 3
4 4 #***************************************************************************
5 5 #
6 6 # Configuration file for IPython -- ipythonrc format
7 7 #
8 8 # The format of this file is simply one of 'key value' lines.
9 9 # Lines containing only whitespace at the beginning and then a # are ignored
10 10 # as comments. But comments can NOT be put on lines with data.
11 11
12 12 # The meaning and use of each key are explained below.
13 13
14 14 #---------------------------------------------------------------------------
15 15 # Section: included files
16 16
17 17 # Put one or more *config* files (with the syntax of this file) you want to
18 18 # include. For keys with a unique value the outermost file has precedence. For
19 19 # keys with multiple values, they all get assembled into a list which then
20 20 # gets loaded by IPython.
21 21
22 22 # In this file, all lists of things should simply be space-separated.
23 23
24 24 # This allows you to build hierarchies of files which recursively load
25 25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
26 26 # should only keep here basic things you always want available. Then you can
27 27 # include it in every other special-purpose config file you create.
28 28 include
29 29
30 30 #---------------------------------------------------------------------------
31 31 # Section: startup setup
32 32
33 33 # These are mostly things which parallel a command line option of the same
34 34 # name.
35 35
36 36 # Keys in this section should only appear once. If any key from this section
37 37 # is encountered more than once, the last value remains, all earlier ones get
38 38 # discarded.
39 39
40 40
41 41 # Automatic calling of callable objects. If set to 1 or 2, callable objects
42 42 # are automatically called when invoked at the command line, even if you don't
43 43 # type parentheses. IPython adds the parentheses for you. For example:
44 44
45 45 #In [1]: str 45
46 46 #------> str(45)
47 47 #Out[1]: '45'
48 48
49 49 # IPython reprints your line with '---->' indicating that it added
50 50 # parentheses. While this option is very convenient for interactive use, it
51 51 # may occasionally cause problems with objects which have side-effects if
52 52 # called unexpectedly.
53 53
54 54 # The valid values for autocall are:
55 55
56 56 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
57 57
58 58 # autocall 1 -> active, but do not apply if there are no arguments on the line.
59 59
60 60 # In this mode, you get:
61 61
62 62 #In [1]: callable
63 63 #Out[1]: <built-in function callable>
64 64
65 65 #In [2]: callable 'hello'
66 66 #------> callable('hello')
67 67 #Out[2]: False
68 68
69 69 # 2 -> Active always. Even if no arguments are present, the callable object
70 70 # is called:
71 71
72 72 #In [4]: callable
73 73 #------> callable()
74 74
75 75 # Note that even with autocall off, you can still use '/' at the start of a
76 76 # line to treat the first argument on the command line as a function and add
77 77 # parentheses to it:
78 78
79 79 #In [8]: /str 43
80 80 #------> str(43)
81 81 #Out[8]: '43'
82 82
83 83 autocall 1
84 84
85 85 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
86 86 # source code (see the 'editor' variable below), it is possible that you save
87 87 # a file with syntax errors in it. If this variable is true, IPython will ask
88 88 # you whether to re-open the editor immediately to correct such an error.
89 89
90 90 autoedit_syntax 0
91 91
92 92 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
93 93 # line, while also un-indenting automatically after 'raise' or 'return'.
94 94
95 95 # This feature uses the readline library, so it will honor your ~/.inputrc
96 96 # configuration (or whatever file your INPUTRC variable points to). Adding
97 97 # the following lines to your .inputrc file can make indent/unindenting more
98 98 # convenient (M-i indents, M-u unindents):
99 99
100 100 # $if Python
101 101 # "\M-i": " "
102 102 # "\M-u": "\d\d\d\d"
103 103 # $endif
104 104
105 105 # The feature is potentially a bit dangerous, because it can cause problems
106 106 # with pasting of indented code (the pasted code gets re-indented on each
107 107 # line). But it's a huge time-saver when working interactively. The magic
108 108 # function %autoindent allows you to toggle it on/off at runtime.
109 109
110 110 autoindent 1
111 111
112 112 # Auto-magic. This gives you access to all the magic functions without having
113 113 # to prepend them with an % sign. If you define a variable with the same name
114 114 # as a magic function (say who=1), you will need to access the magic function
115 115 # with % (%who in this example). However, if later you delete your variable
116 116 # (del who), you'll recover the automagic calling form.
117 117
118 118 # Considering that many magic functions provide a lot of shell-like
119 119 # functionality, automagic gives you something close to a full Python+system
120 120 # shell environment (and you can extend it further if you want).
121 121
122 122 automagic 1
123 123
124 124 # Size of the output cache. After this many entries are stored, the cache will
125 125 # get flushed. Depending on the size of your intermediate calculations, you
126 126 # may have memory problems if you make it too big, since keeping things in the
127 127 # cache prevents Python from reclaiming the memory for old results. Experiment
128 128 # with a value that works well for you.
129 129
130 130 # If you choose cache_size 0 IPython will revert to python's regular >>>
131 131 # unnumbered prompt. You will still have _, __ and ___ for your last three
132 132 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
133 133 # you are running on a slow machine or with very limited memory, this may
134 134 # help.
135 135
136 136 cache_size 1000
137 137
138 138 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
139 139 # but that's your choice! Classic 1 -> same as IPython -classic.
140 140 # Note that this is _not_ the normal python interpreter, it's simply
141 141 # IPython emulating most of the classic interpreter's behavior.
142 142 classic 0
143 143
144 144 # colors - Coloring option for prompts and traceback printouts.
145 145
146 146 # Currently available schemes: NoColor, Linux, LightBG.
147 147
148 148 # This option allows coloring the prompts and traceback printouts. This
149 149 # requires a terminal which can properly handle color escape sequences. If you
150 150 # are having problems with this, use the NoColor scheme (uses no color escapes
151 151 # at all).
152 152
153 153 # The Linux option works well in linux console type environments: dark
154 154 # background with light fonts.
155 155
156 156 # LightBG is similar to Linux but swaps dark/light colors to be more readable
157 157 # in light background terminals.
158 158
159 159 # keep uncommented only the one you want:
160 160 colors Linux
161 161 #colors LightBG
162 162 #colors NoColor
163 163
164 164 ########################
165 165 # Note to Windows users
166 166 #
167 167 # Color and readline support is avaialble to Windows users via Gary Bishop's
168 168 # readline library. You can find Gary's tools at
169 169 # http://sourceforge.net/projects/uncpythontools.
170 170 # Note that his readline module requires in turn the ctypes library, available
171 171 # at http://starship.python.net/crew/theller/ctypes.
172 172 ########################
173 173
174 174 # color_info: IPython can display information about objects via a set of
175 175 # functions, and optionally can use colors for this, syntax highlighting
176 176 # source code and various other elements. This information is passed through a
177 177 # pager (it defaults to 'less' if $PAGER is not set).
178 178
179 179 # If your pager has problems, try to setting it to properly handle escapes
180 180 # (see the less manpage for detail), or disable this option. The magic
181 181 # function %color_info allows you to toggle this interactively for testing.
182 182
183 183 color_info 1
184 184
185 185 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
186 186 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
187 187 # the magic functions %Exit or %Quit you can force a direct exit, bypassing
188 188 # any confirmation.
189 189
190 190 confirm_exit 1
191 191
192 192 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
193 193 # still available as dreload() and appears as a builtin.
194 194
195 195 deep_reload 0
196 196
197 197 # Which editor to use with the %edit command. If you leave this at 0, IPython
198 198 # will honor your EDITOR environment variable. Since this editor is invoked on
199 199 # the fly by ipython and is meant for editing small code snippets, you may
200 200 # want to use a small, lightweight editor here.
201 201
202 202 # For Emacs users, setting up your Emacs server properly as described in the
203 203 # manual is a good idea. An alternative is to use jed, a very light editor
204 204 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
205 205
206 206 editor 0
207 207
208 208 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
209 209 log 0
210 210
211 211 # Same as ipython -Logfile YourLogfileName.
212 212 # Don't use with log 1 (use one or the other)
213 213 logfile ''
214 214
215 215 # banner 0 -> same as ipython -nobanner
216 216 banner 1
217 217
218 218 # messages 0 -> same as ipython -nomessages
219 219 messages 1
220 220
221 221 # Automatically call the pdb debugger after every uncaught exception. If you
222 222 # are used to debugging using pdb, this puts you automatically inside of it
223 223 # after any call (either in IPython or in code called by it) which triggers an
224 224 # exception which goes uncaught.
225 225 pdb 0
226 226
227 227 # Enable the pprint module for printing. pprint tends to give a more readable
228 228 # display (than print) for complex nested data structures.
229 229 pprint 1
230 230
231 231 # Prompt strings
232 232
233 233 # Most bash-like escapes can be used to customize IPython's prompts, as well as
234 234 # a few additional ones which are IPython-specific. All valid prompt escapes
235 235 # are described in detail in the Customization section of the IPython HTML/PDF
236 236 # manual.
237 237
238 238 # Use \# to represent the current prompt number, and quote them to protect
239 239 # spaces.
240 240 prompt_in1 'In [\#]: '
241 241
242 242 # \D is replaced by as many dots as there are digits in the
243 243 # current value of \#.
244 244 prompt_in2 ' .\D.: '
245 245
246 246 prompt_out 'Out[\#]: '
247 247
248 248 # Select whether to left-pad the output prompts to match the length of the
249 249 # input ones. This allows you for example to use a simple '>' as an output
250 250 # prompt, and yet have the output line up with the input. If set to false,
251 251 # the output prompts will be unpadded (flush left).
252 252 prompts_pad_left 1
253 253
254 254 # quick 1 -> same as ipython -quick
255 255 quick 0
256 256
257 257 # Use the readline library (1) or not (0). Most users will want this on, but
258 258 # if you experience strange problems with line management (mainly when using
259 259 # IPython inside Emacs buffers) you may try disabling it. Not having it on
260 260 # prevents you from getting command history with the arrow keys, searching and
261 261 # name completion using TAB.
262 262
263 263 readline 1
264 264
265 265 # Screen Length: number of lines of your screen. This is used to control
266 266 # printing of very long strings. Strings longer than this number of lines will
267 267 # be paged with the less command instead of directly printed.
268 268
269 269 # The default value for this is 0, which means IPython will auto-detect your
270 270 # screen size every time it needs to print. If for some reason this isn't
271 271 # working well (it needs curses support), specify it yourself. Otherwise don't
272 272 # change the default.
273 273
274 274 screen_length 0
275 275
276 276 # Prompt separators for input and output.
277 277 # Use \n for newline explicitly, without quotes.
278 278 # Use 0 (like at the cmd line) to turn off a given separator.
279 279
280 280 # The structure of prompt printing is:
281 281 # (SeparateIn)Input....
282 282 # (SeparateOut)Output...
283 283 # (SeparateOut2), # that is, no newline is printed after Out2
284 284 # By choosing these you can organize your output any way you want.
285 285
286 286 separate_in \n
287 287 separate_out 0
288 288 separate_out2 0
289 289
290 290 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
291 291 # Simply removes all input/output separators, overriding the choices above.
292 292 nosep 0
293 293
294 294 # Wildcard searches - IPython has a system for searching names using
295 295 # shell-like wildcards; type %psearch? for details. This variables sets
296 296 # whether by default such searches should be case sensitive or not. You can
297 297 # always override the default at the system command line or the IPython
298 298 # prompt.
299 299
300 300 wildcards_case_sensitive 1
301 301
302 302 # Object information: at what level of detail to display the string form of an
303 303 # object. If set to 0, ipython will compute the string form of any object X,
304 304 # by calling str(X), when X? is typed. If set to 1, str(X) will only be
305 305 # computed when X?? is given, and if set to 2 or higher, it will never be
306 306 # computed (there is no X??? level of detail). This is mostly of use to
307 307 # people who frequently manipulate objects whose string representation is
308 308 # extremely expensive to compute.
309 309
310 310 object_info_string_level 0
311 311
312 312 # xmode - Exception reporting mode.
313 313
314 314 # Valid modes: Plain, Context and Verbose.
315 315
316 316 # Plain: similar to python's normal traceback printing.
317 317
318 318 # Context: prints 5 lines of context source code around each line in the
319 319 # traceback.
320 320
321 321 # Verbose: similar to Context, but additionally prints the variables currently
322 322 # visible where the exception happened (shortening their strings if too
323 323 # long). This can potentially be very slow, if you happen to have a huge data
324 324 # structure whose string representation is complex to compute. Your computer
325 325 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
326 326 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
327 327
328 328 #xmode Plain
329 329 xmode Context
330 330 #xmode Verbose
331 331
332 332 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
333 333 # !cmd) to be used in multi-line input (like for loops). For example, if you
334 334 # have this active, the following is valid in IPython:
335 335 #
336 336 #In [17]: for i in range(3):
337 337 # ....: mkdir $i
338 338 # ....: !touch $i/hello
339 339 # ....: ls -l $i
340 340
341 341 multi_line_specials 1
342 342
343
344 # System calls: When IPython makes system calls (e.g. via special syntax like
345 # !cmd or !!cmd, or magics like %sc or %sx), it can print the command it is
346 # executing to standard output, prefixed by a header string.
347
348 system_header "IPython system call: "
349
350 system_verbose 1
351
343 352 # wxversion: request a specific wxPython version (used for -wthread)
344 353
345 354 # Set this to the value of wxPython you want to use, but note that this
346 355 # feature requires you to have the wxversion Python module to work. If you
347 356 # don't have the wxversion module (try 'import wxversion' at the prompt to
348 357 # check) or simply want to leave the system to pick up the default, leave this
349 358 # variable at 0.
350 359
351 360 wxversion 0
352 361
353 362 #---------------------------------------------------------------------------
354 363 # Section: Readline configuration (readline is not available for MS-Windows)
355 364
356 365 # This is done via the following options:
357 366
358 367 # (i) readline_parse_and_bind: this option can appear as many times as you
359 368 # want, each time defining a string to be executed via a
360 369 # readline.parse_and_bind() command. The syntax for valid commands of this
361 370 # kind can be found by reading the documentation for the GNU readline library,
362 371 # as these commands are of the kind which readline accepts in its
363 372 # configuration file.
364 373
365 374 # The TAB key can be used to complete names at the command line in one of two
366 375 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
367 376 # completes as much as possible while 'menu-complete' cycles through all
368 377 # possible completions. Leave the one you prefer uncommented.
369 378
370 379 readline_parse_and_bind tab: complete
371 380 #readline_parse_and_bind tab: menu-complete
372 381
373 382 # This binds Control-l to printing the list of all possible completions when
374 383 # there is more than one (what 'complete' does when hitting TAB twice, or at
375 384 # the first TAB if show-all-if-ambiguous is on)
376 385 readline_parse_and_bind "\C-l": possible-completions
377 386
378 387 # This forces readline to automatically print the above list when tab
379 388 # completion is set to 'complete'. You can still get this list manually by
380 389 # using the key bound to 'possible-completions' (Control-l by default) or by
381 390 # hitting TAB twice. Turning this on makes the printing happen at the first
382 391 # TAB.
383 392 readline_parse_and_bind set show-all-if-ambiguous on
384 393
385 394 # If you have TAB set to complete names, you can rebind any key (Control-o by
386 395 # default) to insert a true TAB character.
387 396 readline_parse_and_bind "\C-o": tab-insert
388 397
389 398 # These commands allow you to indent/unindent easily, with the 4-space
390 399 # convention of the Python coding standards. Since IPython's internal
391 400 # auto-indent system also uses 4 spaces, you should not change the number of
392 401 # spaces in the code below.
393 402 readline_parse_and_bind "\M-i": " "
394 403 readline_parse_and_bind "\M-o": "\d\d\d\d"
395 404 readline_parse_and_bind "\M-I": "\d\d\d\d"
396 405
397 406 # Bindings for incremental searches in the history. These searches use the
398 407 # string typed so far on the command line and search anything in the previous
399 408 # input history containing them.
400 409 readline_parse_and_bind "\C-r": reverse-search-history
401 410 readline_parse_and_bind "\C-s": forward-search-history
402 411
403 412 # Bindings for completing the current line in the history of previous
404 413 # commands. This allows you to recall any previous command by typing its first
405 414 # few letters and hitting Control-p, bypassing all intermediate commands which
406 415 # may be in the history (much faster than hitting up-arrow 50 times!)
407 416 readline_parse_and_bind "\C-p": history-search-backward
408 417 readline_parse_and_bind "\C-n": history-search-forward
409 418
410 419 # I also like to have the same functionality on the plain arrow keys. If you'd
411 420 # rather have the arrows use all the history (and not just match what you've
412 421 # typed so far), comment out or delete the next two lines.
413 422 readline_parse_and_bind "\e[A": history-search-backward
414 423 readline_parse_and_bind "\e[B": history-search-forward
415 424
416 425 # These are typically on by default under *nix, but not win32.
417 426 readline_parse_and_bind "\C-k": kill-line
418 427 readline_parse_and_bind "\C-u": unix-line-discard
419 428
420 429 # (ii) readline_remove_delims: a string of characters to be removed from the
421 430 # default word-delimiters list used by readline, so that completions may be
422 431 # performed on strings which contain them.
423 432
424 433 readline_remove_delims -/~
425 434
426 435 # (iii) readline_merge_completions: whether to merge the result of all
427 436 # possible completions or not. If true, IPython will complete filenames,
428 437 # python names and aliases and return all possible completions. If you set it
429 438 # to false, each completer is used at a time, and only if it doesn't return
430 439 # any completions is the next one used.
431 440
432 441 # The default order is: [python_matches, file_matches, alias_matches]
433 442
434 443 readline_merge_completions 1
435 444
436 445 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
437 446 # will complete all attributes of an object, including all the special methods
438 447 # whose names start with single or double underscores (like __getitem__ or
439 448 # __class__).
440 449
441 450 # This variable allows you to control this completion behavior:
442 451
443 452 # readline_omit__names 1 -> completion will omit showing any names starting
444 453 # with two __, but it will still show names starting with one _.
445 454
446 455 # readline_omit__names 2 -> completion will omit all names beginning with one
447 456 # _ (which obviously means filtering out the double __ ones).
448 457
449 458 # Even when this option is set, you can still see those names by explicitly
450 459 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
451 460 # complete attribute names starting with '_'.
452 461
453 462 # This option is off by default so that new users see all attributes of any
454 463 # objects they are dealing with.
455 464
456 465 readline_omit__names 0
457 466
458 467 #---------------------------------------------------------------------------
459 468 # Section: modules to be loaded with 'import ...'
460 469
461 470 # List, separated by spaces, the names of the modules you want to import
462 471
463 472 # Example:
464 473 # import_mod sys os
465 474 # will produce internally the statements
466 475 # import sys
467 476 # import os
468 477
469 478 # Each import is executed in its own try/except block, so if one module
470 479 # fails to load the others will still be ok.
471 480
472 481 import_mod
473 482
474 483 #---------------------------------------------------------------------------
475 484 # Section: modules to import some functions from: 'from ... import ...'
476 485
477 486 # List, one per line, the modules for which you want only to import some
478 487 # functions. Give the module name first and then the name of functions to be
479 488 # imported from that module.
480 489
481 490 # Example:
482 491
483 492 # import_some IPython.genutils timing timings
484 493 # will produce internally the statement
485 494 # from IPython.genutils import timing, timings
486 495
487 496 # timing() and timings() are two IPython utilities for timing the execution of
488 497 # your own functions, which you may find useful. Just commment out the above
489 498 # line if you want to test them.
490 499
491 500 # If you have more than one modules_some line, each gets its own try/except
492 501 # block (like modules, see above).
493 502
494 503 import_some
495 504
496 505 #---------------------------------------------------------------------------
497 506 # Section: modules to import all from : 'from ... import *'
498 507
499 508 # List (same syntax as import_mod above) those modules for which you want to
500 509 # import all functions. Remember, this is a potentially dangerous thing to do,
501 510 # since it is very easy to overwrite names of things you need. Use with
502 511 # caution.
503 512
504 513 # Example:
505 514 # import_all sys os
506 515 # will produce internally the statements
507 516 # from sys import *
508 517 # from os import *
509 518
510 519 # As before, each will be called in a separate try/except block.
511 520
512 521 import_all
513 522
514 523 #---------------------------------------------------------------------------
515 524 # Section: Python code to execute.
516 525
517 526 # Put here code to be explicitly executed (keep it simple!)
518 527 # Put one line of python code per line. All whitespace is removed (this is a
519 528 # feature, not a bug), so don't get fancy building loops here.
520 529 # This is just for quick convenient creation of things you want available.
521 530
522 531 # Example:
523 532 # execute x = 1
524 533 # execute print 'hello world'; y = z = 'a'
525 534 # will produce internally
526 535 # x = 1
527 536 # print 'hello world'; y = z = 'a'
528 537 # and each *line* (not each statement, we don't do python syntax parsing) is
529 538 # executed in its own try/except block.
530 539
531 540 execute
532 541
533 542 # Note for the adventurous: you can use this to define your own names for the
534 543 # magic functions, by playing some namespace tricks:
535 544
536 545 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
537 546
538 547 # defines %pf as a new name for %profile.
539 548
540 549 #---------------------------------------------------------------------------
541 550 # Section: Pyhton files to load and execute.
542 551
543 552 # Put here the full names of files you want executed with execfile(file). If
544 553 # you want complicated initialization, just write whatever you want in a
545 554 # regular python file and load it from here.
546 555
547 556 # Filenames defined here (which *must* include the extension) are searched for
548 557 # through all of sys.path. Since IPython adds your .ipython directory to
549 558 # sys.path, they can also be placed in your .ipython dir and will be
550 559 # found. Otherwise (if you want to execute things not in .ipyton nor in
551 560 # sys.path) give a full path (you can use ~, it gets expanded)
552 561
553 562 # Example:
554 563 # execfile file1.py ~/file2.py
555 564 # will generate
556 565 # execfile('file1.py')
557 566 # execfile('_path_to_your_home/file2.py')
558 567
559 568 # As before, each file gets its own try/except block.
560 569
561 570 execfile
562 571
563 572 # If you are feeling adventurous, you can even add functionality to IPython
564 573 # through here. IPython works through a global variable called __ip which
565 574 # exists at the time when these files are read. If you know what you are doing
566 575 # (read the source) you can add functions to __ip in files loaded here.
567 576
568 577 # The file example-magic.py contains a simple but correct example. Try it:
569 578
570 579 # execfile example-magic.py
571 580
572 581 # Look at the examples in IPython/iplib.py for more details on how these magic
573 582 # functions need to process their arguments.
574 583
575 584 #---------------------------------------------------------------------------
576 585 # Section: aliases for system shell commands
577 586
578 587 # Here you can define your own names for system commands. The syntax is
579 588 # similar to that of the builtin %alias function:
580 589
581 590 # alias alias_name command_string
582 591
583 592 # The resulting aliases are auto-generated magic functions (hence usable as
584 593 # %alias_name)
585 594
586 595 # For example:
587 596
588 597 # alias myls ls -la
589 598
590 599 # will define 'myls' as an alias for executing the system command 'ls -la'.
591 600 # This allows you to customize IPython's environment to have the same aliases
592 601 # you are accustomed to from your own shell.
593 602
594 603 # You can also define aliases with parameters using %s specifiers (one per
595 604 # parameter):
596 605
597 606 # alias parts echo first %s second %s
598 607
599 608 # will give you in IPython:
600 609 # >>> %parts A B
601 610 # first A second B
602 611
603 612 # Use one 'alias' statement per alias you wish to define.
604 613
605 614 # alias
606 615
607 616 #************************* end of file <ipythonrc> ************************
@@ -1,2489 +1,2515 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.3 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 1878 2006-11-03 23:00:22Z fptest $
9 $Id: iplib.py 1879 2006-11-04 00:34:34Z fptest $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2006 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 IPython import Release
32 32 __author__ = '%s <%s>\n%s <%s>' % \
33 33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 34 __license__ = Release.license
35 35 __version__ = Release.version
36 36
37 37 # Python standard modules
38 38 import __main__
39 39 import __builtin__
40 40 import StringIO
41 41 import bdb
42 42 import cPickle as pickle
43 43 import codeop
44 44 import exceptions
45 45 import glob
46 46 import inspect
47 47 import keyword
48 48 import new
49 49 import os
50 50 import pydoc
51 51 import re
52 52 import shutil
53 53 import string
54 54 import sys
55 55 import tempfile
56 56 import traceback
57 57 import types
58 58 import pickleshare
59 59 from sets import Set
60 60 from pprint import pprint, pformat
61 61
62 62 # IPython's own modules
63 63 import IPython
64 64 from IPython import OInspect,PyColorize,ultraTB
65 65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 66 from IPython.FakeModule import FakeModule
67 67 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 68 from IPython.Logger import Logger
69 69 from IPython.Magic import Magic
70 70 from IPython.Prompts import CachedOutput
71 71 from IPython.ipstruct import Struct
72 72 from IPython.background_jobs import BackgroundJobManager
73 73 from IPython.usage import cmd_line_usage,interactive_usage
74 74 from IPython.genutils import *
75 75 from IPython.strdispatch import StrDispatch
76 76 import IPython.ipapi
77 77
78 78 # Globals
79 79
80 80 # store the builtin raw_input globally, and use this always, in case user code
81 81 # overwrites it (like wx.py.PyShell does)
82 82 raw_input_original = raw_input
83 83
84 84 # compiled regexps for autoindent management
85 85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86 86
87 87
88 88 #****************************************************************************
89 89 # Some utility function definitions
90 90
91 91 ini_spaces_re = re.compile(r'^(\s+)')
92 92
93 93 def num_ini_spaces(strng):
94 94 """Return the number of initial spaces in a string"""
95 95
96 96 ini_spaces = ini_spaces_re.match(strng)
97 97 if ini_spaces:
98 98 return ini_spaces.end()
99 99 else:
100 100 return 0
101 101
102 102 def softspace(file, newvalue):
103 103 """Copied from code.py, to remove the dependency"""
104 104
105 105 oldvalue = 0
106 106 try:
107 107 oldvalue = file.softspace
108 108 except AttributeError:
109 109 pass
110 110 try:
111 111 file.softspace = newvalue
112 112 except (AttributeError, TypeError):
113 113 # "attribute-less object" or "read-only attributes"
114 114 pass
115 115 return oldvalue
116 116
117 117
118 118 #****************************************************************************
119 119 # Local use exceptions
120 120 class SpaceInInput(exceptions.Exception): pass
121 121
122 122
123 123 #****************************************************************************
124 124 # Local use classes
125 125 class Bunch: pass
126 126
127 127 class Undefined: pass
128 128
129 129 class Quitter(object):
130 130 """Simple class to handle exit, similar to Python 2.5's.
131 131
132 132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
133 133 doesn't do (obviously, since it doesn't know about ipython)."""
134 134
135 135 def __init__(self,shell,name):
136 136 self.shell = shell
137 137 self.name = name
138 138
139 139 def __repr__(self):
140 140 return 'Type %s() to exit.' % self.name
141 141 __str__ = __repr__
142 142
143 143 def __call__(self):
144 144 self.shell.exit()
145 145
146 146 class InputList(list):
147 147 """Class to store user input.
148 148
149 149 It's basically a list, but slices return a string instead of a list, thus
150 150 allowing things like (assuming 'In' is an instance):
151 151
152 152 exec In[4:7]
153 153
154 154 or
155 155
156 156 exec In[5:9] + In[14] + In[21:25]"""
157 157
158 158 def __getslice__(self,i,j):
159 159 return ''.join(list.__getslice__(self,i,j))
160 160
161 161 class SyntaxTB(ultraTB.ListTB):
162 162 """Extension which holds some state: the last exception value"""
163 163
164 164 def __init__(self,color_scheme = 'NoColor'):
165 165 ultraTB.ListTB.__init__(self,color_scheme)
166 166 self.last_syntax_error = None
167 167
168 168 def __call__(self, etype, value, elist):
169 169 self.last_syntax_error = value
170 170 ultraTB.ListTB.__call__(self,etype,value,elist)
171 171
172 172 def clear_err_state(self):
173 173 """Return the current error state and clear it"""
174 174 e = self.last_syntax_error
175 175 self.last_syntax_error = None
176 176 return e
177 177
178 178 #****************************************************************************
179 179 # Main IPython class
180 180
181 181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
182 182 # until a full rewrite is made. I've cleaned all cross-class uses of
183 183 # attributes and methods, but too much user code out there relies on the
184 184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
185 185 #
186 186 # But at least now, all the pieces have been separated and we could, in
187 187 # principle, stop using the mixin. This will ease the transition to the
188 188 # chainsaw branch.
189 189
190 190 # For reference, the following is the list of 'self.foo' uses in the Magic
191 191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
192 192 # class, to prevent clashes.
193 193
194 194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
195 195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
196 196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
197 197 # 'self.value']
198 198
199 199 class InteractiveShell(object,Magic):
200 200 """An enhanced console for Python."""
201 201
202 202 # class attribute to indicate whether the class supports threads or not.
203 203 # Subclasses with thread support should override this as needed.
204 204 isthreaded = False
205 205
206 206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
207 207 user_ns = None,user_global_ns=None,banner2='',
208 208 custom_exceptions=((),None),embedded=False):
209 209
210 210 # log system
211 211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
212 212
213 213 # some minimal strict typechecks. For some core data structures, I
214 214 # want actual basic python types, not just anything that looks like
215 215 # one. This is especially true for namespaces.
216 216 for ns in (user_ns,user_global_ns):
217 217 if ns is not None and type(ns) != types.DictType:
218 218 raise TypeError,'namespace must be a dictionary'
219 219
220 220 # Job manager (for jobs run as background threads)
221 221 self.jobs = BackgroundJobManager()
222 222
223 223 # Store the actual shell's name
224 224 self.name = name
225 225
226 226 # We need to know whether the instance is meant for embedding, since
227 227 # global/local namespaces need to be handled differently in that case
228 228 self.embedded = embedded
229 229
230 230 # command compiler
231 231 self.compile = codeop.CommandCompiler()
232 232
233 233 # User input buffer
234 234 self.buffer = []
235 235
236 236 # Default name given in compilation of code
237 237 self.filename = '<ipython console>'
238 238
239 239 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 240 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 241 __builtin__.exit = Quitter(self,'exit')
242 242 __builtin__.quit = Quitter(self,'quit')
243 243
244 244 # Make an empty namespace, which extension writers can rely on both
245 245 # existing and NEVER being used by ipython itself. This gives them a
246 246 # convenient location for storing additional information and state
247 247 # their extensions may require, without fear of collisions with other
248 248 # ipython names that may develop later.
249 249 self.meta = Struct()
250 250
251 251 # Create the namespace where the user will operate. user_ns is
252 252 # normally the only one used, and it is passed to the exec calls as
253 253 # the locals argument. But we do carry a user_global_ns namespace
254 254 # given as the exec 'globals' argument, This is useful in embedding
255 255 # situations where the ipython shell opens in a context where the
256 256 # distinction between locals and globals is meaningful.
257 257
258 258 # FIXME. For some strange reason, __builtins__ is showing up at user
259 259 # level as a dict instead of a module. This is a manual fix, but I
260 260 # should really track down where the problem is coming from. Alex
261 261 # Schmolck reported this problem first.
262 262
263 263 # A useful post by Alex Martelli on this topic:
264 264 # Re: inconsistent value from __builtins__
265 265 # Von: Alex Martelli <aleaxit@yahoo.com>
266 266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
267 267 # Gruppen: comp.lang.python
268 268
269 269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
270 270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
271 271 # > <type 'dict'>
272 272 # > >>> print type(__builtins__)
273 273 # > <type 'module'>
274 274 # > Is this difference in return value intentional?
275 275
276 276 # Well, it's documented that '__builtins__' can be either a dictionary
277 277 # or a module, and it's been that way for a long time. Whether it's
278 278 # intentional (or sensible), I don't know. In any case, the idea is
279 279 # that if you need to access the built-in namespace directly, you
280 280 # should start with "import __builtin__" (note, no 's') which will
281 281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
282 282
283 283 # These routines return properly built dicts as needed by the rest of
284 284 # the code, and can also be used by extension writers to generate
285 285 # properly initialized namespaces.
286 286 user_ns = IPython.ipapi.make_user_ns(user_ns)
287 287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
288 288
289 289 # Assign namespaces
290 290 # This is the namespace where all normal user variables live
291 291 self.user_ns = user_ns
292 292 # Embedded instances require a separate namespace for globals.
293 293 # Normally this one is unused by non-embedded instances.
294 294 self.user_global_ns = user_global_ns
295 295 # A namespace to keep track of internal data structures to prevent
296 296 # them from cluttering user-visible stuff. Will be updated later
297 297 self.internal_ns = {}
298 298
299 299 # Namespace of system aliases. Each entry in the alias
300 300 # table must be a 2-tuple of the form (N,name), where N is the number
301 301 # of positional arguments of the alias.
302 302 self.alias_table = {}
303 303
304 304 # A table holding all the namespaces IPython deals with, so that
305 305 # introspection facilities can search easily.
306 306 self.ns_table = {'user':user_ns,
307 307 'user_global':user_global_ns,
308 308 'alias':self.alias_table,
309 309 'internal':self.internal_ns,
310 310 'builtin':__builtin__.__dict__
311 311 }
312 312
313 313 # The user namespace MUST have a pointer to the shell itself.
314 314 self.user_ns[name] = self
315 315
316 316 # We need to insert into sys.modules something that looks like a
317 317 # module but which accesses the IPython namespace, for shelve and
318 318 # pickle to work interactively. Normally they rely on getting
319 319 # everything out of __main__, but for embedding purposes each IPython
320 320 # instance has its own private namespace, so we can't go shoving
321 321 # everything into __main__.
322 322
323 323 # note, however, that we should only do this for non-embedded
324 324 # ipythons, which really mimic the __main__.__dict__ with their own
325 325 # namespace. Embedded instances, on the other hand, should not do
326 326 # this because they need to manage the user local/global namespaces
327 327 # only, but they live within a 'normal' __main__ (meaning, they
328 328 # shouldn't overtake the execution environment of the script they're
329 329 # embedded in).
330 330
331 331 if not embedded:
332 332 try:
333 333 main_name = self.user_ns['__name__']
334 334 except KeyError:
335 335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 336 else:
337 337 #print "pickle hack in place" # dbg
338 338 #print 'main_name:',main_name # dbg
339 339 sys.modules[main_name] = FakeModule(self.user_ns)
340 340
341 341 # List of input with multi-line handling.
342 342 # Fill its zero entry, user counter starts at 1
343 343 self.input_hist = InputList(['\n'])
344 344 # This one will hold the 'raw' input history, without any
345 345 # pre-processing. This will allow users to retrieve the input just as
346 346 # it was exactly typed in by the user, with %hist -r.
347 347 self.input_hist_raw = InputList(['\n'])
348 348
349 349 # list of visited directories
350 350 try:
351 351 self.dir_hist = [os.getcwd()]
352 352 except IOError, e:
353 353 self.dir_hist = []
354 354
355 355 # dict of output history
356 356 self.output_hist = {}
357 357
358 358 # dict of things NOT to alias (keywords, builtins and some magics)
359 359 no_alias = {}
360 360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
361 361 for key in keyword.kwlist + no_alias_magics:
362 362 no_alias[key] = 1
363 363 no_alias.update(__builtin__.__dict__)
364 364 self.no_alias = no_alias
365 365
366 366 # make global variables for user access to these
367 367 self.user_ns['_ih'] = self.input_hist
368 368 self.user_ns['_oh'] = self.output_hist
369 369 self.user_ns['_dh'] = self.dir_hist
370 370
371 371 # user aliases to input and output histories
372 372 self.user_ns['In'] = self.input_hist
373 373 self.user_ns['Out'] = self.output_hist
374 374
375 375 # Object variable to store code object waiting execution. This is
376 376 # used mainly by the multithreaded shells, but it can come in handy in
377 377 # other situations. No need to use a Queue here, since it's a single
378 378 # item which gets cleared once run.
379 379 self.code_to_run = None
380 380
381 381 # escapes for automatic behavior on the command line
382 382 self.ESC_SHELL = '!'
383 383 self.ESC_HELP = '?'
384 384 self.ESC_MAGIC = '%'
385 385 self.ESC_QUOTE = ','
386 386 self.ESC_QUOTE2 = ';'
387 387 self.ESC_PAREN = '/'
388 388
389 389 # And their associated handlers
390 390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
391 391 self.ESC_QUOTE : self.handle_auto,
392 392 self.ESC_QUOTE2 : self.handle_auto,
393 393 self.ESC_MAGIC : self.handle_magic,
394 394 self.ESC_HELP : self.handle_help,
395 395 self.ESC_SHELL : self.handle_shell_escape,
396 396 }
397 397
398 398 # class initializations
399 399 Magic.__init__(self,self)
400 400
401 401 # Python source parser/formatter for syntax highlighting
402 402 pyformat = PyColorize.Parser().format
403 403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
404 404
405 405 # hooks holds pointers used for user-side customizations
406 406 self.hooks = Struct()
407 407
408 408 self.strdispatchers = {}
409 409
410 410 # Set all default hooks, defined in the IPython.hooks module.
411 411 hooks = IPython.hooks
412 412 for hook_name in hooks.__all__:
413 413 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
414 414 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
415 415 #print "bound hook",hook_name
416 416
417 417 # Flag to mark unconditional exit
418 418 self.exit_now = False
419 419
420 420 self.usage_min = """\
421 421 An enhanced console for Python.
422 422 Some of its features are:
423 423 - Readline support if the readline library is present.
424 424 - Tab completion in the local namespace.
425 425 - Logging of input, see command-line options.
426 426 - System shell escape via ! , eg !ls.
427 427 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
428 428 - Keeps track of locally defined variables via %who, %whos.
429 429 - Show object information with a ? eg ?x or x? (use ?? for more info).
430 430 """
431 431 if usage: self.usage = usage
432 432 else: self.usage = self.usage_min
433 433
434 434 # Storage
435 435 self.rc = rc # This will hold all configuration information
436 436 self.pager = 'less'
437 437 # temporary files used for various purposes. Deleted at exit.
438 438 self.tempfiles = []
439 439
440 440 # Keep track of readline usage (later set by init_readline)
441 441 self.has_readline = False
442 442
443 443 # template for logfile headers. It gets resolved at runtime by the
444 444 # logstart method.
445 445 self.loghead_tpl = \
446 446 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
447 447 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
448 448 #log# opts = %s
449 449 #log# args = %s
450 450 #log# It is safe to make manual edits below here.
451 451 #log#-----------------------------------------------------------------------
452 452 """
453 453 # for pushd/popd management
454 454 try:
455 455 self.home_dir = get_home_dir()
456 456 except HomeDirError,msg:
457 457 fatal(msg)
458 458
459 459 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
460 460
461 461 # Functions to call the underlying shell.
462 462
463 463 # The first is similar to os.system, but it doesn't return a value,
464 464 # and it allows interpolation of variables in the user's namespace.
465 465 self.system = lambda cmd: \
466 466 shell(self.var_expand(cmd,depth=2),
467 header='IPython system call: ',
467 header=self.rc.system_header,
468 468 verbose=self.rc.system_verbose)
469
469 470 # These are for getoutput and getoutputerror:
470 471 self.getoutput = lambda cmd: \
471 472 getoutput(self.var_expand(cmd,depth=2),
472 header='IPython system call: ',
473 header=self.rc.system_header,
473 474 verbose=self.rc.system_verbose)
475
474 476 self.getoutputerror = lambda cmd: \
475 477 getoutputerror(self.var_expand(cmd,depth=2),
476 header='IPython system call: ',
478 header=self.rc.system_header,
477 479 verbose=self.rc.system_verbose)
478 480
479 481 # RegExp for splitting line contents into pre-char//first
480 482 # word-method//rest. For clarity, each group in on one line.
481 483
482 484 # WARNING: update the regexp if the above escapes are changed, as they
483 485 # are hardwired in.
484 486
485 487 # Don't get carried away with trying to make the autocalling catch too
486 488 # much: it's better to be conservative rather than to trigger hidden
487 489 # evals() somewhere and end up causing side effects.
488 490
489 491 self.line_split = re.compile(r'^([\s*,;/])'
490 492 r'([\?\w\.]+\w*\s*)'
491 493 r'(\(?.*$)')
492 494
493 495 # Original re, keep around for a while in case changes break something
494 496 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
495 497 # r'(\s*[\?\w\.]+\w*\s*)'
496 498 # r'(\(?.*$)')
497 499
498 500 # RegExp to identify potential function names
499 501 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
500 502
501 503 # RegExp to exclude strings with this start from autocalling. In
502 504 # particular, all binary operators should be excluded, so that if foo
503 505 # is callable, foo OP bar doesn't become foo(OP bar), which is
504 506 # invalid. The characters '!=()' don't need to be checked for, as the
505 507 # _prefilter routine explicitely does so, to catch direct calls and
506 508 # rebindings of existing names.
507 509
508 510 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
509 511 # it affects the rest of the group in square brackets.
510 512 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
511 513 '|^is |^not |^in |^and |^or ')
512 514
513 515 # try to catch also methods for stuff in lists/tuples/dicts: off
514 516 # (experimental). For this to work, the line_split regexp would need
515 517 # to be modified so it wouldn't break things at '['. That line is
516 518 # nasty enough that I shouldn't change it until I can test it _well_.
517 519 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
518 520
519 521 # keep track of where we started running (mainly for crash post-mortem)
520 522 self.starting_dir = os.getcwd()
521 523
522 524 # Various switches which can be set
523 525 self.CACHELENGTH = 5000 # this is cheap, it's just text
524 526 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
525 527 self.banner2 = banner2
526 528
527 529 # TraceBack handlers:
528 530
529 531 # Syntax error handler.
530 532 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
531 533
532 534 # The interactive one is initialized with an offset, meaning we always
533 535 # want to remove the topmost item in the traceback, which is our own
534 536 # internal code. Valid modes: ['Plain','Context','Verbose']
535 537 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
536 538 color_scheme='NoColor',
537 539 tb_offset = 1)
538 540
539 541 # IPython itself shouldn't crash. This will produce a detailed
540 542 # post-mortem if it does. But we only install the crash handler for
541 543 # non-threaded shells, the threaded ones use a normal verbose reporter
542 544 # and lose the crash handler. This is because exceptions in the main
543 545 # thread (such as in GUI code) propagate directly to sys.excepthook,
544 546 # and there's no point in printing crash dumps for every user exception.
545 547 if self.isthreaded:
546 548 ipCrashHandler = ultraTB.FormattedTB()
547 549 else:
548 550 from IPython import CrashHandler
549 551 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
550 552 self.set_crash_handler(ipCrashHandler)
551 553
552 554 # and add any custom exception handlers the user may have specified
553 555 self.set_custom_exc(*custom_exceptions)
554 556
555 557 # indentation management
556 558 self.autoindent = False
557 559 self.indent_current_nsp = 0
558 560
559 561 # Make some aliases automatically
560 562 # Prepare list of shell aliases to auto-define
561 563 if os.name == 'posix':
562 564 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
563 565 'mv mv -i','rm rm -i','cp cp -i',
564 566 'cat cat','less less','clear clear',
565 567 # a better ls
566 568 'ls ls -F',
567 569 # long ls
568 570 'll ls -lF')
569 571 # Extra ls aliases with color, which need special treatment on BSD
570 572 # variants
571 573 ls_extra = ( # color ls
572 574 'lc ls -F -o --color',
573 575 # ls normal files only
574 576 'lf ls -F -o --color %l | grep ^-',
575 577 # ls symbolic links
576 578 'lk ls -F -o --color %l | grep ^l',
577 579 # directories or links to directories,
578 580 'ldir ls -F -o --color %l | grep /$',
579 581 # things which are executable
580 582 'lx ls -F -o --color %l | grep ^-..x',
581 583 )
582 584 # The BSDs don't ship GNU ls, so they don't understand the
583 585 # --color switch out of the box
584 586 if 'bsd' in sys.platform:
585 587 ls_extra = ( # ls normal files only
586 588 'lf ls -lF | grep ^-',
587 589 # ls symbolic links
588 590 'lk ls -lF | grep ^l',
589 591 # directories or links to directories,
590 592 'ldir ls -lF | grep /$',
591 593 # things which are executable
592 594 'lx ls -lF | grep ^-..x',
593 595 )
594 596 auto_alias = auto_alias + ls_extra
595 597 elif os.name in ['nt','dos']:
596 598 auto_alias = ('dir dir /on', 'ls dir /on',
597 599 'ddir dir /ad /on', 'ldir dir /ad /on',
598 600 'mkdir mkdir','rmdir rmdir','echo echo',
599 601 'ren ren','cls cls','copy copy')
600 602 else:
601 603 auto_alias = ()
602 604 self.auto_alias = [s.split(None,1) for s in auto_alias]
603 605 # Call the actual (public) initializer
604 606 self.init_auto_alias()
605 607
606 608 # Produce a public API instance
607 609 self.api = IPython.ipapi.IPApi(self)
608 610
609 611 # track which builtins we add, so we can clean up later
610 612 self.builtins_added = {}
611 613 # This method will add the necessary builtins for operation, but
612 614 # tracking what it did via the builtins_added dict.
613 615 self.add_builtins()
614 616
615 617 # end __init__
616 618
617 619 def var_expand(self,cmd,depth=0):
618 620 """Expand python variables in a string.
619 621
620 622 The depth argument indicates how many frames above the caller should
621 623 be walked to look for the local namespace where to expand variables.
622 624
623 625 The global namespace for expansion is always the user's interactive
624 626 namespace.
625 627 """
626 628
627 629 return str(ItplNS(cmd.replace('#','\#'),
628 630 self.user_ns, # globals
629 631 # Skip our own frame in searching for locals:
630 632 sys._getframe(depth+1).f_locals # locals
631 633 ))
632 634
633 635 def pre_config_initialization(self):
634 636 """Pre-configuration init method
635 637
636 638 This is called before the configuration files are processed to
637 639 prepare the services the config files might need.
638 640
639 641 self.rc already has reasonable default values at this point.
640 642 """
641 643 rc = self.rc
642 644
643 645 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
644 646
645 647 def post_config_initialization(self):
646 648 """Post configuration init method
647 649
648 650 This is called after the configuration files have been processed to
649 651 'finalize' the initialization."""
650 652
651 653 rc = self.rc
652 654
653 655 # Object inspector
654 656 self.inspector = OInspect.Inspector(OInspect.InspectColors,
655 657 PyColorize.ANSICodeColors,
656 658 'NoColor',
657 659 rc.object_info_string_level)
658 660
659 661 # Load readline proper
660 662 if rc.readline:
661 663 self.init_readline()
662 664
663 665 # local shortcut, this is used a LOT
664 666 self.log = self.logger.log
665 667
666 668 # Initialize cache, set in/out prompts and printing system
667 669 self.outputcache = CachedOutput(self,
668 670 rc.cache_size,
669 671 rc.pprint,
670 672 input_sep = rc.separate_in,
671 673 output_sep = rc.separate_out,
672 674 output_sep2 = rc.separate_out2,
673 675 ps1 = rc.prompt_in1,
674 676 ps2 = rc.prompt_in2,
675 677 ps_out = rc.prompt_out,
676 678 pad_left = rc.prompts_pad_left)
677 679
678 680 # user may have over-ridden the default print hook:
679 681 try:
680 682 self.outputcache.__class__.display = self.hooks.display
681 683 except AttributeError:
682 684 pass
683 685
684 686 # I don't like assigning globally to sys, because it means when
685 687 # embedding instances, each embedded instance overrides the previous
686 688 # choice. But sys.displayhook seems to be called internally by exec,
687 689 # so I don't see a way around it. We first save the original and then
688 690 # overwrite it.
689 691 self.sys_displayhook = sys.displayhook
690 692 sys.displayhook = self.outputcache
691 693
692 694 # Set user colors (don't do it in the constructor above so that it
693 695 # doesn't crash if colors option is invalid)
694 696 self.magic_colors(rc.colors)
695 697
696 698 # Set calling of pdb on exceptions
697 699 self.call_pdb = rc.pdb
698 700
699 701 # Load user aliases
700 702 for alias in rc.alias:
701 703 self.magic_alias(alias)
702 704 self.hooks.late_startup_hook()
703 705
704 706 batchrun = False
705 707 for batchfile in [path(arg) for arg in self.rc.args
706 708 if arg.lower().endswith('.ipy')]:
707 709 if not batchfile.isfile():
708 710 print "No such batch file:", batchfile
709 711 continue
710 712 self.api.runlines(batchfile.text())
711 713 batchrun = True
712 714 if batchrun:
713 715 self.exit_now = True
714 716
715 717 def add_builtins(self):
716 718 """Store ipython references into the builtin namespace.
717 719
718 720 Some parts of ipython operate via builtins injected here, which hold a
719 721 reference to IPython itself."""
720 722
721 723 # TODO: deprecate all except _ip; 'jobs' should be installed
722 724 # by an extension and the rest are under _ip, ipalias is redundant
723 725 builtins_new = dict(__IPYTHON__ = self,
724 726 ip_set_hook = self.set_hook,
725 727 jobs = self.jobs,
726 728 ipmagic = self.ipmagic,
727 729 ipalias = self.ipalias,
728 730 ipsystem = self.ipsystem,
731 ipconfig = self.ipconfig,
729 732 _ip = self.api
730 733 )
731 734 for biname,bival in builtins_new.items():
732 735 try:
733 736 # store the orignal value so we can restore it
734 737 self.builtins_added[biname] = __builtin__.__dict__[biname]
735 738 except KeyError:
736 739 # or mark that it wasn't defined, and we'll just delete it at
737 740 # cleanup
738 741 self.builtins_added[biname] = Undefined
739 742 __builtin__.__dict__[biname] = bival
740 743
741 744 # Keep in the builtins a flag for when IPython is active. We set it
742 745 # with setdefault so that multiple nested IPythons don't clobber one
743 746 # another. Each will increase its value by one upon being activated,
744 747 # which also gives us a way to determine the nesting level.
745 748 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
746 749
747 750 def clean_builtins(self):
748 751 """Remove any builtins which might have been added by add_builtins, or
749 752 restore overwritten ones to their previous values."""
750 753 for biname,bival in self.builtins_added.items():
751 754 if bival is Undefined:
752 755 del __builtin__.__dict__[biname]
753 756 else:
754 757 __builtin__.__dict__[biname] = bival
755 758 self.builtins_added.clear()
756 759
757 760 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
758 761 """set_hook(name,hook) -> sets an internal IPython hook.
759 762
760 763 IPython exposes some of its internal API as user-modifiable hooks. By
761 764 adding your function to one of these hooks, you can modify IPython's
762 765 behavior to call at runtime your own routines."""
763 766
764 767 # At some point in the future, this should validate the hook before it
765 768 # accepts it. Probably at least check that the hook takes the number
766 769 # of args it's supposed to.
767 770
768 771 f = new.instancemethod(hook,self,self.__class__)
769 772
770 773 # check if the hook is for strdispatcher first
771 774 if str_key is not None:
772 775 sdp = self.strdispatchers.get(name, StrDispatch())
773 776 sdp.add_s(str_key, f, priority )
774 777 self.strdispatchers[name] = sdp
775 778 return
776 779 if re_key is not None:
777 780 sdp = self.strdispatchers.get(name, StrDispatch())
778 781 sdp.add_re(re.compile(re_key), f, priority )
779 782 self.strdispatchers[name] = sdp
780 783 return
781 784
782 785 dp = getattr(self.hooks, name, None)
783 786 if name not in IPython.hooks.__all__:
784 787 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
785 788 if not dp:
786 789 dp = IPython.hooks.CommandChainDispatcher()
787 790
788 791 try:
789 792 dp.add(f,priority)
790 793 except AttributeError:
791 794 # it was not commandchain, plain old func - replace
792 795 dp = f
793 796
794 797 setattr(self.hooks,name, dp)
795 798
796 799
797 800 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
798 801
799 802 def set_crash_handler(self,crashHandler):
800 803 """Set the IPython crash handler.
801 804
802 805 This must be a callable with a signature suitable for use as
803 806 sys.excepthook."""
804 807
805 808 # Install the given crash handler as the Python exception hook
806 809 sys.excepthook = crashHandler
807 810
808 811 # The instance will store a pointer to this, so that runtime code
809 812 # (such as magics) can access it. This is because during the
810 813 # read-eval loop, it gets temporarily overwritten (to deal with GUI
811 814 # frameworks).
812 815 self.sys_excepthook = sys.excepthook
813 816
814 817
815 818 def set_custom_exc(self,exc_tuple,handler):
816 819 """set_custom_exc(exc_tuple,handler)
817 820
818 821 Set a custom exception handler, which will be called if any of the
819 822 exceptions in exc_tuple occur in the mainloop (specifically, in the
820 823 runcode() method.
821 824
822 825 Inputs:
823 826
824 827 - exc_tuple: a *tuple* of valid exceptions to call the defined
825 828 handler for. It is very important that you use a tuple, and NOT A
826 829 LIST here, because of the way Python's except statement works. If
827 830 you only want to trap a single exception, use a singleton tuple:
828 831
829 832 exc_tuple == (MyCustomException,)
830 833
831 834 - handler: this must be defined as a function with the following
832 835 basic interface: def my_handler(self,etype,value,tb).
833 836
834 837 This will be made into an instance method (via new.instancemethod)
835 838 of IPython itself, and it will be called if any of the exceptions
836 839 listed in the exc_tuple are caught. If the handler is None, an
837 840 internal basic one is used, which just prints basic info.
838 841
839 842 WARNING: by putting in your own exception handler into IPython's main
840 843 execution loop, you run a very good chance of nasty crashes. This
841 844 facility should only be used if you really know what you are doing."""
842 845
843 846 assert type(exc_tuple)==type(()) , \
844 847 "The custom exceptions must be given AS A TUPLE."
845 848
846 849 def dummy_handler(self,etype,value,tb):
847 850 print '*** Simple custom exception handler ***'
848 851 print 'Exception type :',etype
849 852 print 'Exception value:',value
850 853 print 'Traceback :',tb
851 854 print 'Source code :','\n'.join(self.buffer)
852 855
853 856 if handler is None: handler = dummy_handler
854 857
855 858 self.CustomTB = new.instancemethod(handler,self,self.__class__)
856 859 self.custom_exceptions = exc_tuple
857 860
858 861 def set_custom_completer(self,completer,pos=0):
859 862 """set_custom_completer(completer,pos=0)
860 863
861 864 Adds a new custom completer function.
862 865
863 866 The position argument (defaults to 0) is the index in the completers
864 867 list where you want the completer to be inserted."""
865 868
866 869 newcomp = new.instancemethod(completer,self.Completer,
867 870 self.Completer.__class__)
868 871 self.Completer.matchers.insert(pos,newcomp)
869 872
870 873 def _get_call_pdb(self):
871 874 return self._call_pdb
872 875
873 876 def _set_call_pdb(self,val):
874 877
875 878 if val not in (0,1,False,True):
876 879 raise ValueError,'new call_pdb value must be boolean'
877 880
878 881 # store value in instance
879 882 self._call_pdb = val
880 883
881 884 # notify the actual exception handlers
882 885 self.InteractiveTB.call_pdb = val
883 886 if self.isthreaded:
884 887 try:
885 888 self.sys_excepthook.call_pdb = val
886 889 except:
887 890 warn('Failed to activate pdb for threaded exception handler')
888 891
889 892 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
890 893 'Control auto-activation of pdb at exceptions')
891 894
892 895
893 896 # These special functions get installed in the builtin namespace, to
894 897 # provide programmatic (pure python) access to magics, aliases and system
895 898 # calls. This is important for logging, user scripting, and more.
896 899
897 900 # We are basically exposing, via normal python functions, the three
898 901 # mechanisms in which ipython offers special call modes (magics for
899 902 # internal control, aliases for direct system access via pre-selected
900 903 # names, and !cmd for calling arbitrary system commands).
901 904
902 905 def ipmagic(self,arg_s):
903 906 """Call a magic function by name.
904 907
905 908 Input: a string containing the name of the magic function to call and any
906 909 additional arguments to be passed to the magic.
907 910
908 911 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
909 912 prompt:
910 913
911 914 In[1]: %name -opt foo bar
912 915
913 916 To call a magic without arguments, simply use ipmagic('name').
914 917
915 918 This provides a proper Python function to call IPython's magics in any
916 919 valid Python code you can type at the interpreter, including loops and
917 920 compound statements. It is added by IPython to the Python builtin
918 921 namespace upon initialization."""
919 922
920 923 args = arg_s.split(' ',1)
921 924 magic_name = args[0]
922 925 magic_name = magic_name.lstrip(self.ESC_MAGIC)
923 926
924 927 try:
925 928 magic_args = args[1]
926 929 except IndexError:
927 930 magic_args = ''
928 931 fn = getattr(self,'magic_'+magic_name,None)
929 932 if fn is None:
930 933 error("Magic function `%s` not found." % magic_name)
931 934 else:
932 935 magic_args = self.var_expand(magic_args,1)
933 936 return fn(magic_args)
934 937
935 938 def ipalias(self,arg_s):
936 939 """Call an alias by name.
937 940
938 941 Input: a string containing the name of the alias to call and any
939 942 additional arguments to be passed to the magic.
940 943
941 944 ipalias('name -opt foo bar') is equivalent to typing at the ipython
942 945 prompt:
943 946
944 947 In[1]: name -opt foo bar
945 948
946 949 To call an alias without arguments, simply use ipalias('name').
947 950
948 951 This provides a proper Python function to call IPython's aliases in any
949 952 valid Python code you can type at the interpreter, including loops and
950 953 compound statements. It is added by IPython to the Python builtin
951 954 namespace upon initialization."""
952 955
953 956 args = arg_s.split(' ',1)
954 957 alias_name = args[0]
955 958 try:
956 959 alias_args = args[1]
957 960 except IndexError:
958 961 alias_args = ''
959 962 if alias_name in self.alias_table:
960 963 self.call_alias(alias_name,alias_args)
961 964 else:
962 965 error("Alias `%s` not found." % alias_name)
963 966
967 def ipconfig(self,key=None,value=None):
968 """Manipulate the IPython config.
969
970 This provides a python interface to
971 If called with no arguments, it prints the internal IPython config
972
973 Optional arguments:
974
975 - key(None): if given, what key of the rc structure to return.
976
977 - value(None): if given, set the key to this value."""
978
979 if key is None:
980 page('Current configuration structure:\n'+
981 pformat(self.rc.dict()))
982 else:
983 if value is None:
984 print '%s -> %s' % (key,self.rc[key])
985 else:
986 if key not in self.rc:
987 raise KeyError(str(key))
988 self.rc[key] = value
989
964 990 def ipsystem(self,arg_s):
965 991 """Make a system call, using IPython."""
966 992
967 993 self.system(arg_s)
968 994
969 995 def complete(self,text):
970 996 """Return a sorted list of all possible completions on text.
971 997
972 998 Inputs:
973 999
974 1000 - text: a string of text to be completed on.
975 1001
976 1002 This is a wrapper around the completion mechanism, similar to what
977 1003 readline does at the command line when the TAB key is hit. By
978 1004 exposing it as a method, it can be used by other non-readline
979 1005 environments (such as GUIs) for text completion.
980 1006
981 1007 Simple usage example:
982 1008
983 1009 In [1]: x = 'hello'
984 1010
985 1011 In [2]: __IP.complete('x.l')
986 1012 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
987 1013
988 1014 complete = self.Completer.complete
989 1015 state = 0
990 1016 # use a dict so we get unique keys, since ipyhton's multiple
991 1017 # completers can return duplicates.
992 1018 comps = {}
993 1019 while True:
994 1020 newcomp = complete(text,state)
995 1021 if newcomp is None:
996 1022 break
997 1023 comps[newcomp] = 1
998 1024 state += 1
999 1025 outcomps = comps.keys()
1000 1026 outcomps.sort()
1001 1027 return outcomps
1002 1028
1003 1029 def set_completer_frame(self, frame=None):
1004 1030 if frame:
1005 1031 self.Completer.namespace = frame.f_locals
1006 1032 self.Completer.global_namespace = frame.f_globals
1007 1033 else:
1008 1034 self.Completer.namespace = self.user_ns
1009 1035 self.Completer.global_namespace = self.user_global_ns
1010 1036
1011 1037 def init_auto_alias(self):
1012 1038 """Define some aliases automatically.
1013 1039
1014 1040 These are ALL parameter-less aliases"""
1015 1041
1016 1042 for alias,cmd in self.auto_alias:
1017 1043 self.alias_table[alias] = (0,cmd)
1018 1044
1019 1045 def alias_table_validate(self,verbose=0):
1020 1046 """Update information about the alias table.
1021 1047
1022 1048 In particular, make sure no Python keywords/builtins are in it."""
1023 1049
1024 1050 no_alias = self.no_alias
1025 1051 for k in self.alias_table.keys():
1026 1052 if k in no_alias:
1027 1053 del self.alias_table[k]
1028 1054 if verbose:
1029 1055 print ("Deleting alias <%s>, it's a Python "
1030 1056 "keyword or builtin." % k)
1031 1057
1032 1058 def set_autoindent(self,value=None):
1033 1059 """Set the autoindent flag, checking for readline support.
1034 1060
1035 1061 If called with no arguments, it acts as a toggle."""
1036 1062
1037 1063 if not self.has_readline:
1038 1064 if os.name == 'posix':
1039 1065 warn("The auto-indent feature requires the readline library")
1040 1066 self.autoindent = 0
1041 1067 return
1042 1068 if value is None:
1043 1069 self.autoindent = not self.autoindent
1044 1070 else:
1045 1071 self.autoindent = value
1046 1072
1047 1073 def rc_set_toggle(self,rc_field,value=None):
1048 1074 """Set or toggle a field in IPython's rc config. structure.
1049 1075
1050 1076 If called with no arguments, it acts as a toggle.
1051 1077
1052 1078 If called with a non-existent field, the resulting AttributeError
1053 1079 exception will propagate out."""
1054 1080
1055 1081 rc_val = getattr(self.rc,rc_field)
1056 1082 if value is None:
1057 1083 value = not rc_val
1058 1084 setattr(self.rc,rc_field,value)
1059 1085
1060 1086 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1061 1087 """Install the user configuration directory.
1062 1088
1063 1089 Can be called when running for the first time or to upgrade the user's
1064 1090 .ipython/ directory with the mode parameter. Valid modes are 'install'
1065 1091 and 'upgrade'."""
1066 1092
1067 1093 def wait():
1068 1094 try:
1069 1095 raw_input("Please press <RETURN> to start IPython.")
1070 1096 except EOFError:
1071 1097 print >> Term.cout
1072 1098 print '*'*70
1073 1099
1074 1100 cwd = os.getcwd() # remember where we started
1075 1101 glb = glob.glob
1076 1102 print '*'*70
1077 1103 if mode == 'install':
1078 1104 print \
1079 1105 """Welcome to IPython. I will try to create a personal configuration directory
1080 1106 where you can customize many aspects of IPython's functionality in:\n"""
1081 1107 else:
1082 1108 print 'I am going to upgrade your configuration in:'
1083 1109
1084 1110 print ipythondir
1085 1111
1086 1112 rcdirend = os.path.join('IPython','UserConfig')
1087 1113 cfg = lambda d: os.path.join(d,rcdirend)
1088 1114 try:
1089 1115 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1090 1116 except IOError:
1091 1117 warning = """
1092 1118 Installation error. IPython's directory was not found.
1093 1119
1094 1120 Check the following:
1095 1121
1096 1122 The ipython/IPython directory should be in a directory belonging to your
1097 1123 PYTHONPATH environment variable (that is, it should be in a directory
1098 1124 belonging to sys.path). You can copy it explicitly there or just link to it.
1099 1125
1100 1126 IPython will proceed with builtin defaults.
1101 1127 """
1102 1128 warn(warning)
1103 1129 wait()
1104 1130 return
1105 1131
1106 1132 if mode == 'install':
1107 1133 try:
1108 1134 shutil.copytree(rcdir,ipythondir)
1109 1135 os.chdir(ipythondir)
1110 1136 rc_files = glb("ipythonrc*")
1111 1137 for rc_file in rc_files:
1112 1138 os.rename(rc_file,rc_file+rc_suffix)
1113 1139 except:
1114 1140 warning = """
1115 1141
1116 1142 There was a problem with the installation:
1117 1143 %s
1118 1144 Try to correct it or contact the developers if you think it's a bug.
1119 1145 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1120 1146 warn(warning)
1121 1147 wait()
1122 1148 return
1123 1149
1124 1150 elif mode == 'upgrade':
1125 1151 try:
1126 1152 os.chdir(ipythondir)
1127 1153 except:
1128 1154 print """
1129 1155 Can not upgrade: changing to directory %s failed. Details:
1130 1156 %s
1131 1157 """ % (ipythondir,sys.exc_info()[1])
1132 1158 wait()
1133 1159 return
1134 1160 else:
1135 1161 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1136 1162 for new_full_path in sources:
1137 1163 new_filename = os.path.basename(new_full_path)
1138 1164 if new_filename.startswith('ipythonrc'):
1139 1165 new_filename = new_filename + rc_suffix
1140 1166 # The config directory should only contain files, skip any
1141 1167 # directories which may be there (like CVS)
1142 1168 if os.path.isdir(new_full_path):
1143 1169 continue
1144 1170 if os.path.exists(new_filename):
1145 1171 old_file = new_filename+'.old'
1146 1172 if os.path.exists(old_file):
1147 1173 os.remove(old_file)
1148 1174 os.rename(new_filename,old_file)
1149 1175 shutil.copy(new_full_path,new_filename)
1150 1176 else:
1151 1177 raise ValueError,'unrecognized mode for install:',`mode`
1152 1178
1153 1179 # Fix line-endings to those native to each platform in the config
1154 1180 # directory.
1155 1181 try:
1156 1182 os.chdir(ipythondir)
1157 1183 except:
1158 1184 print """
1159 1185 Problem: changing to directory %s failed.
1160 1186 Details:
1161 1187 %s
1162 1188
1163 1189 Some configuration files may have incorrect line endings. This should not
1164 1190 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1165 1191 wait()
1166 1192 else:
1167 1193 for fname in glb('ipythonrc*'):
1168 1194 try:
1169 1195 native_line_ends(fname,backup=0)
1170 1196 except IOError:
1171 1197 pass
1172 1198
1173 1199 if mode == 'install':
1174 1200 print """
1175 1201 Successful installation!
1176 1202
1177 1203 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1178 1204 IPython manual (there are both HTML and PDF versions supplied with the
1179 1205 distribution) to make sure that your system environment is properly configured
1180 1206 to take advantage of IPython's features.
1181 1207
1182 1208 Important note: the configuration system has changed! The old system is
1183 1209 still in place, but its setting may be partly overridden by the settings in
1184 1210 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1185 1211 if some of the new settings bother you.
1186 1212
1187 1213 """
1188 1214 else:
1189 1215 print """
1190 1216 Successful upgrade!
1191 1217
1192 1218 All files in your directory:
1193 1219 %(ipythondir)s
1194 1220 which would have been overwritten by the upgrade were backed up with a .old
1195 1221 extension. If you had made particular customizations in those files you may
1196 1222 want to merge them back into the new files.""" % locals()
1197 1223 wait()
1198 1224 os.chdir(cwd)
1199 1225 # end user_setup()
1200 1226
1201 1227 def atexit_operations(self):
1202 1228 """This will be executed at the time of exit.
1203 1229
1204 1230 Saving of persistent data should be performed here. """
1205 1231
1206 1232 #print '*** IPython exit cleanup ***' # dbg
1207 1233 # input history
1208 1234 self.savehist()
1209 1235
1210 1236 # Cleanup all tempfiles left around
1211 1237 for tfile in self.tempfiles:
1212 1238 try:
1213 1239 os.unlink(tfile)
1214 1240 except OSError:
1215 1241 pass
1216 1242
1217 1243 # save the "persistent data" catch-all dictionary
1218 1244 self.hooks.shutdown_hook()
1219 1245
1220 1246 def savehist(self):
1221 1247 """Save input history to a file (via readline library)."""
1222 1248 try:
1223 1249 self.readline.write_history_file(self.histfile)
1224 1250 except:
1225 1251 print 'Unable to save IPython command history to file: ' + \
1226 1252 `self.histfile`
1227 1253
1228 1254 def history_saving_wrapper(self, func):
1229 1255 """ Wrap func for readline history saving
1230 1256
1231 1257 Convert func into callable that saves & restores
1232 1258 history around the call """
1233 1259
1234 1260 if not self.has_readline:
1235 1261 return func
1236 1262
1237 1263 def wrapper():
1238 1264 self.savehist()
1239 1265 try:
1240 1266 func()
1241 1267 finally:
1242 1268 readline.read_history_file(self.histfile)
1243 1269 return wrapper
1244 1270
1245 1271
1246 1272 def pre_readline(self):
1247 1273 """readline hook to be used at the start of each line.
1248 1274
1249 1275 Currently it handles auto-indent only."""
1250 1276
1251 1277 #debugx('self.indent_current_nsp','pre_readline:')
1252 1278 self.readline.insert_text(self.indent_current_str())
1253 1279
1254 1280 def init_readline(self):
1255 1281 """Command history completion/saving/reloading."""
1256 1282
1257 1283 import IPython.rlineimpl as readline
1258 1284 if not readline.have_readline:
1259 1285 self.has_readline = 0
1260 1286 self.readline = None
1261 1287 # no point in bugging windows users with this every time:
1262 1288 warn('Readline services not available on this platform.')
1263 1289 else:
1264 1290 sys.modules['readline'] = readline
1265 1291 import atexit
1266 1292 from IPython.completer import IPCompleter
1267 1293 self.Completer = IPCompleter(self,
1268 1294 self.user_ns,
1269 1295 self.user_global_ns,
1270 1296 self.rc.readline_omit__names,
1271 1297 self.alias_table)
1272 1298 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1273 1299 self.strdispatchers['complete_command'] = sdisp
1274 1300 self.Completer.custom_completers = sdisp
1275 1301 # Platform-specific configuration
1276 1302 if os.name == 'nt':
1277 1303 self.readline_startup_hook = readline.set_pre_input_hook
1278 1304 else:
1279 1305 self.readline_startup_hook = readline.set_startup_hook
1280 1306
1281 1307 # Load user's initrc file (readline config)
1282 1308 inputrc_name = os.environ.get('INPUTRC')
1283 1309 if inputrc_name is None:
1284 1310 home_dir = get_home_dir()
1285 1311 if home_dir is not None:
1286 1312 inputrc_name = os.path.join(home_dir,'.inputrc')
1287 1313 if os.path.isfile(inputrc_name):
1288 1314 try:
1289 1315 readline.read_init_file(inputrc_name)
1290 1316 except:
1291 1317 warn('Problems reading readline initialization file <%s>'
1292 1318 % inputrc_name)
1293 1319
1294 1320 self.has_readline = 1
1295 1321 self.readline = readline
1296 1322 # save this in sys so embedded copies can restore it properly
1297 1323 sys.ipcompleter = self.Completer.complete
1298 1324 readline.set_completer(self.Completer.complete)
1299 1325
1300 1326 # Configure readline according to user's prefs
1301 1327 for rlcommand in self.rc.readline_parse_and_bind:
1302 1328 readline.parse_and_bind(rlcommand)
1303 1329
1304 1330 # remove some chars from the delimiters list
1305 1331 delims = readline.get_completer_delims()
1306 1332 delims = delims.translate(string._idmap,
1307 1333 self.rc.readline_remove_delims)
1308 1334 readline.set_completer_delims(delims)
1309 1335 # otherwise we end up with a monster history after a while:
1310 1336 readline.set_history_length(1000)
1311 1337 try:
1312 1338 #print '*** Reading readline history' # dbg
1313 1339 readline.read_history_file(self.histfile)
1314 1340 except IOError:
1315 1341 pass # It doesn't exist yet.
1316 1342
1317 1343 atexit.register(self.atexit_operations)
1318 1344 del atexit
1319 1345
1320 1346 # Configure auto-indent for all platforms
1321 1347 self.set_autoindent(self.rc.autoindent)
1322 1348
1323 1349 def ask_yes_no(self,prompt,default=True):
1324 1350 if self.rc.quiet:
1325 1351 return True
1326 1352 return ask_yes_no(prompt,default)
1327 1353
1328 1354 def _should_recompile(self,e):
1329 1355 """Utility routine for edit_syntax_error"""
1330 1356
1331 1357 if e.filename in ('<ipython console>','<input>','<string>',
1332 1358 '<console>','<BackgroundJob compilation>',
1333 1359 None):
1334 1360
1335 1361 return False
1336 1362 try:
1337 1363 if (self.rc.autoedit_syntax and
1338 1364 not self.ask_yes_no('Return to editor to correct syntax error? '
1339 1365 '[Y/n] ','y')):
1340 1366 return False
1341 1367 except EOFError:
1342 1368 return False
1343 1369
1344 1370 def int0(x):
1345 1371 try:
1346 1372 return int(x)
1347 1373 except TypeError:
1348 1374 return 0
1349 1375 # always pass integer line and offset values to editor hook
1350 1376 self.hooks.fix_error_editor(e.filename,
1351 1377 int0(e.lineno),int0(e.offset),e.msg)
1352 1378 return True
1353 1379
1354 1380 def edit_syntax_error(self):
1355 1381 """The bottom half of the syntax error handler called in the main loop.
1356 1382
1357 1383 Loop until syntax error is fixed or user cancels.
1358 1384 """
1359 1385
1360 1386 while self.SyntaxTB.last_syntax_error:
1361 1387 # copy and clear last_syntax_error
1362 1388 err = self.SyntaxTB.clear_err_state()
1363 1389 if not self._should_recompile(err):
1364 1390 return
1365 1391 try:
1366 1392 # may set last_syntax_error again if a SyntaxError is raised
1367 1393 self.safe_execfile(err.filename,self.user_ns)
1368 1394 except:
1369 1395 self.showtraceback()
1370 1396 else:
1371 1397 try:
1372 1398 f = file(err.filename)
1373 1399 try:
1374 1400 sys.displayhook(f.read())
1375 1401 finally:
1376 1402 f.close()
1377 1403 except:
1378 1404 self.showtraceback()
1379 1405
1380 1406 def showsyntaxerror(self, filename=None):
1381 1407 """Display the syntax error that just occurred.
1382 1408
1383 1409 This doesn't display a stack trace because there isn't one.
1384 1410
1385 1411 If a filename is given, it is stuffed in the exception instead
1386 1412 of what was there before (because Python's parser always uses
1387 1413 "<string>" when reading from a string).
1388 1414 """
1389 1415 etype, value, last_traceback = sys.exc_info()
1390 1416
1391 1417 # See note about these variables in showtraceback() below
1392 1418 sys.last_type = etype
1393 1419 sys.last_value = value
1394 1420 sys.last_traceback = last_traceback
1395 1421
1396 1422 if filename and etype is SyntaxError:
1397 1423 # Work hard to stuff the correct filename in the exception
1398 1424 try:
1399 1425 msg, (dummy_filename, lineno, offset, line) = value
1400 1426 except:
1401 1427 # Not the format we expect; leave it alone
1402 1428 pass
1403 1429 else:
1404 1430 # Stuff in the right filename
1405 1431 try:
1406 1432 # Assume SyntaxError is a class exception
1407 1433 value = SyntaxError(msg, (filename, lineno, offset, line))
1408 1434 except:
1409 1435 # If that failed, assume SyntaxError is a string
1410 1436 value = msg, (filename, lineno, offset, line)
1411 1437 self.SyntaxTB(etype,value,[])
1412 1438
1413 1439 def debugger(self):
1414 1440 """Call the pydb/pdb debugger."""
1415 1441
1416 1442 if not self.rc.pdb:
1417 1443 return
1418 1444 have_pydb = False
1419 1445 if sys.version[:3] >= '2.5':
1420 1446 try:
1421 1447 from pydb import pm
1422 1448 have_pydb = True
1423 1449 except ImportError:
1424 1450 pass
1425 1451 if not have_pydb:
1426 1452 from pdb import pm
1427 1453 self.history_saving_wrapper(pm)()
1428 1454
1429 1455 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1430 1456 """Display the exception that just occurred.
1431 1457
1432 1458 If nothing is known about the exception, this is the method which
1433 1459 should be used throughout the code for presenting user tracebacks,
1434 1460 rather than directly invoking the InteractiveTB object.
1435 1461
1436 1462 A specific showsyntaxerror() also exists, but this method can take
1437 1463 care of calling it if needed, so unless you are explicitly catching a
1438 1464 SyntaxError exception, don't try to analyze the stack manually and
1439 1465 simply call this method."""
1440 1466
1441 1467 # Though this won't be called by syntax errors in the input line,
1442 1468 # there may be SyntaxError cases whith imported code.
1443 1469 if exc_tuple is None:
1444 1470 etype, value, tb = sys.exc_info()
1445 1471 else:
1446 1472 etype, value, tb = exc_tuple
1447 1473 if etype is SyntaxError:
1448 1474 self.showsyntaxerror(filename)
1449 1475 else:
1450 1476 # WARNING: these variables are somewhat deprecated and not
1451 1477 # necessarily safe to use in a threaded environment, but tools
1452 1478 # like pdb depend on their existence, so let's set them. If we
1453 1479 # find problems in the field, we'll need to revisit their use.
1454 1480 sys.last_type = etype
1455 1481 sys.last_value = value
1456 1482 sys.last_traceback = tb
1457 1483
1458 1484 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1459 1485 if self.InteractiveTB.call_pdb and self.has_readline:
1460 1486 # pdb mucks up readline, fix it back
1461 1487 self.readline.set_completer(self.Completer.complete)
1462 1488
1463 1489 def mainloop(self,banner=None):
1464 1490 """Creates the local namespace and starts the mainloop.
1465 1491
1466 1492 If an optional banner argument is given, it will override the
1467 1493 internally created default banner."""
1468 1494
1469 1495 if self.rc.c: # Emulate Python's -c option
1470 1496 self.exec_init_cmd()
1471 1497 if banner is None:
1472 1498 if not self.rc.banner:
1473 1499 banner = ''
1474 1500 # banner is string? Use it directly!
1475 1501 elif isinstance(self.rc.banner,basestring):
1476 1502 banner = self.rc.banner
1477 1503 else:
1478 1504 banner = self.BANNER+self.banner2
1479 1505
1480 1506 self.interact(banner)
1481 1507
1482 1508 def exec_init_cmd(self):
1483 1509 """Execute a command given at the command line.
1484 1510
1485 1511 This emulates Python's -c option."""
1486 1512
1487 1513 #sys.argv = ['-c']
1488 1514 self.push(self.rc.c)
1489 1515
1490 1516 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1491 1517 """Embeds IPython into a running python program.
1492 1518
1493 1519 Input:
1494 1520
1495 1521 - header: An optional header message can be specified.
1496 1522
1497 1523 - local_ns, global_ns: working namespaces. If given as None, the
1498 1524 IPython-initialized one is updated with __main__.__dict__, so that
1499 1525 program variables become visible but user-specific configuration
1500 1526 remains possible.
1501 1527
1502 1528 - stack_depth: specifies how many levels in the stack to go to
1503 1529 looking for namespaces (when local_ns and global_ns are None). This
1504 1530 allows an intermediate caller to make sure that this function gets
1505 1531 the namespace from the intended level in the stack. By default (0)
1506 1532 it will get its locals and globals from the immediate caller.
1507 1533
1508 1534 Warning: it's possible to use this in a program which is being run by
1509 1535 IPython itself (via %run), but some funny things will happen (a few
1510 1536 globals get overwritten). In the future this will be cleaned up, as
1511 1537 there is no fundamental reason why it can't work perfectly."""
1512 1538
1513 1539 # Get locals and globals from caller
1514 1540 if local_ns is None or global_ns is None:
1515 1541 call_frame = sys._getframe(stack_depth).f_back
1516 1542
1517 1543 if local_ns is None:
1518 1544 local_ns = call_frame.f_locals
1519 1545 if global_ns is None:
1520 1546 global_ns = call_frame.f_globals
1521 1547
1522 1548 # Update namespaces and fire up interpreter
1523 1549
1524 1550 # The global one is easy, we can just throw it in
1525 1551 self.user_global_ns = global_ns
1526 1552
1527 1553 # but the user/local one is tricky: ipython needs it to store internal
1528 1554 # data, but we also need the locals. We'll copy locals in the user
1529 1555 # one, but will track what got copied so we can delete them at exit.
1530 1556 # This is so that a later embedded call doesn't see locals from a
1531 1557 # previous call (which most likely existed in a separate scope).
1532 1558 local_varnames = local_ns.keys()
1533 1559 self.user_ns.update(local_ns)
1534 1560
1535 1561 # Patch for global embedding to make sure that things don't overwrite
1536 1562 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1537 1563 # FIXME. Test this a bit more carefully (the if.. is new)
1538 1564 if local_ns is None and global_ns is None:
1539 1565 self.user_global_ns.update(__main__.__dict__)
1540 1566
1541 1567 # make sure the tab-completer has the correct frame information, so it
1542 1568 # actually completes using the frame's locals/globals
1543 1569 self.set_completer_frame()
1544 1570
1545 1571 # before activating the interactive mode, we need to make sure that
1546 1572 # all names in the builtin namespace needed by ipython point to
1547 1573 # ourselves, and not to other instances.
1548 1574 self.add_builtins()
1549 1575
1550 1576 self.interact(header)
1551 1577
1552 1578 # now, purge out the user namespace from anything we might have added
1553 1579 # from the caller's local namespace
1554 1580 delvar = self.user_ns.pop
1555 1581 for var in local_varnames:
1556 1582 delvar(var,None)
1557 1583 # and clean builtins we may have overridden
1558 1584 self.clean_builtins()
1559 1585
1560 1586 def interact(self, banner=None):
1561 1587 """Closely emulate the interactive Python console.
1562 1588
1563 1589 The optional banner argument specify the banner to print
1564 1590 before the first interaction; by default it prints a banner
1565 1591 similar to the one printed by the real Python interpreter,
1566 1592 followed by the current class name in parentheses (so as not
1567 1593 to confuse this with the real interpreter -- since it's so
1568 1594 close!).
1569 1595
1570 1596 """
1571 1597
1572 1598 if self.exit_now:
1573 1599 # batch run -> do not interact
1574 1600 return
1575 1601 cprt = 'Type "copyright", "credits" or "license" for more information.'
1576 1602 if banner is None:
1577 1603 self.write("Python %s on %s\n%s\n(%s)\n" %
1578 1604 (sys.version, sys.platform, cprt,
1579 1605 self.__class__.__name__))
1580 1606 else:
1581 1607 self.write(banner)
1582 1608
1583 1609 more = 0
1584 1610
1585 1611 # Mark activity in the builtins
1586 1612 __builtin__.__dict__['__IPYTHON__active'] += 1
1587 1613
1588 1614 # exit_now is set by a call to %Exit or %Quit
1589 1615 while not self.exit_now:
1590 1616 if more:
1591 1617 prompt = self.hooks.generate_prompt(True)
1592 1618 if self.autoindent:
1593 1619 self.readline_startup_hook(self.pre_readline)
1594 1620 else:
1595 1621 prompt = self.hooks.generate_prompt(False)
1596 1622 try:
1597 1623 line = self.raw_input(prompt,more)
1598 1624 if self.exit_now:
1599 1625 # quick exit on sys.std[in|out] close
1600 1626 break
1601 1627 if self.autoindent:
1602 1628 self.readline_startup_hook(None)
1603 1629 except KeyboardInterrupt:
1604 1630 self.write('\nKeyboardInterrupt\n')
1605 1631 self.resetbuffer()
1606 1632 # keep cache in sync with the prompt counter:
1607 1633 self.outputcache.prompt_count -= 1
1608 1634
1609 1635 if self.autoindent:
1610 1636 self.indent_current_nsp = 0
1611 1637 more = 0
1612 1638 except EOFError:
1613 1639 if self.autoindent:
1614 1640 self.readline_startup_hook(None)
1615 1641 self.write('\n')
1616 1642 self.exit()
1617 1643 except bdb.BdbQuit:
1618 1644 warn('The Python debugger has exited with a BdbQuit exception.\n'
1619 1645 'Because of how pdb handles the stack, it is impossible\n'
1620 1646 'for IPython to properly format this particular exception.\n'
1621 1647 'IPython will resume normal operation.')
1622 1648 except:
1623 1649 # exceptions here are VERY RARE, but they can be triggered
1624 1650 # asynchronously by signal handlers, for example.
1625 1651 self.showtraceback()
1626 1652 else:
1627 1653 more = self.push(line)
1628 1654 if (self.SyntaxTB.last_syntax_error and
1629 1655 self.rc.autoedit_syntax):
1630 1656 self.edit_syntax_error()
1631 1657
1632 1658 # We are off again...
1633 1659 __builtin__.__dict__['__IPYTHON__active'] -= 1
1634 1660
1635 1661 def excepthook(self, etype, value, tb):
1636 1662 """One more defense for GUI apps that call sys.excepthook.
1637 1663
1638 1664 GUI frameworks like wxPython trap exceptions and call
1639 1665 sys.excepthook themselves. I guess this is a feature that
1640 1666 enables them to keep running after exceptions that would
1641 1667 otherwise kill their mainloop. This is a bother for IPython
1642 1668 which excepts to catch all of the program exceptions with a try:
1643 1669 except: statement.
1644 1670
1645 1671 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1646 1672 any app directly invokes sys.excepthook, it will look to the user like
1647 1673 IPython crashed. In order to work around this, we can disable the
1648 1674 CrashHandler and replace it with this excepthook instead, which prints a
1649 1675 regular traceback using our InteractiveTB. In this fashion, apps which
1650 1676 call sys.excepthook will generate a regular-looking exception from
1651 1677 IPython, and the CrashHandler will only be triggered by real IPython
1652 1678 crashes.
1653 1679
1654 1680 This hook should be used sparingly, only in places which are not likely
1655 1681 to be true IPython errors.
1656 1682 """
1657 1683 self.showtraceback((etype,value,tb),tb_offset=0)
1658 1684
1659 1685 def expand_aliases(self,fn,rest):
1660 1686 """ Expand multiple levels of aliases:
1661 1687
1662 1688 if:
1663 1689
1664 1690 alias foo bar /tmp
1665 1691 alias baz foo
1666 1692
1667 1693 then:
1668 1694
1669 1695 baz huhhahhei -> bar /tmp huhhahhei
1670 1696
1671 1697 """
1672 1698 line = fn + " " + rest
1673 1699
1674 1700 done = Set()
1675 1701 while 1:
1676 1702 pre,fn,rest = self.split_user_input(line)
1677 1703 if fn in self.alias_table:
1678 1704 if fn in done:
1679 1705 warn("Cyclic alias definition, repeated '%s'" % fn)
1680 1706 return ""
1681 1707 done.add(fn)
1682 1708
1683 1709 l2 = self.transform_alias(fn,rest)
1684 1710 # dir -> dir
1685 1711 # print "alias",line, "->",l2 #dbg
1686 1712 if l2 == line:
1687 1713 break
1688 1714 # ls -> ls -F should not recurse forever
1689 1715 if l2.split(None,1)[0] == line.split(None,1)[0]:
1690 1716 line = l2
1691 1717 break
1692 1718
1693 1719 line=l2
1694 1720
1695 1721
1696 1722 # print "al expand to",line #dbg
1697 1723 else:
1698 1724 break
1699 1725
1700 1726 return line
1701 1727
1702 1728 def transform_alias(self, alias,rest=''):
1703 1729 """ Transform alias to system command string.
1704 1730 """
1705 1731 nargs,cmd = self.alias_table[alias]
1706 1732 if ' ' in cmd and os.path.isfile(cmd):
1707 1733 cmd = '"%s"' % cmd
1708 1734
1709 1735 # Expand the %l special to be the user's input line
1710 1736 if cmd.find('%l') >= 0:
1711 1737 cmd = cmd.replace('%l',rest)
1712 1738 rest = ''
1713 1739 if nargs==0:
1714 1740 # Simple, argument-less aliases
1715 1741 cmd = '%s %s' % (cmd,rest)
1716 1742 else:
1717 1743 # Handle aliases with positional arguments
1718 1744 args = rest.split(None,nargs)
1719 1745 if len(args)< nargs:
1720 1746 error('Alias <%s> requires %s arguments, %s given.' %
1721 1747 (alias,nargs,len(args)))
1722 1748 return None
1723 1749 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1724 1750 # Now call the macro, evaluating in the user's namespace
1725 1751 #print 'new command: <%r>' % cmd # dbg
1726 1752 return cmd
1727 1753
1728 1754 def call_alias(self,alias,rest=''):
1729 1755 """Call an alias given its name and the rest of the line.
1730 1756
1731 1757 This is only used to provide backwards compatibility for users of
1732 1758 ipalias(), use of which is not recommended for anymore."""
1733 1759
1734 1760 # Now call the macro, evaluating in the user's namespace
1735 1761 cmd = self.transform_alias(alias, rest)
1736 1762 try:
1737 1763 self.system(cmd)
1738 1764 except:
1739 1765 self.showtraceback()
1740 1766
1741 1767 def indent_current_str(self):
1742 1768 """return the current level of indentation as a string"""
1743 1769 return self.indent_current_nsp * ' '
1744 1770
1745 1771 def autoindent_update(self,line):
1746 1772 """Keep track of the indent level."""
1747 1773
1748 1774 #debugx('line')
1749 1775 #debugx('self.indent_current_nsp')
1750 1776 if self.autoindent:
1751 1777 if line:
1752 1778 inisp = num_ini_spaces(line)
1753 1779 if inisp < self.indent_current_nsp:
1754 1780 self.indent_current_nsp = inisp
1755 1781
1756 1782 if line[-1] == ':':
1757 1783 self.indent_current_nsp += 4
1758 1784 elif dedent_re.match(line):
1759 1785 self.indent_current_nsp -= 4
1760 1786 else:
1761 1787 self.indent_current_nsp = 0
1762 1788
1763 1789 def runlines(self,lines):
1764 1790 """Run a string of one or more lines of source.
1765 1791
1766 1792 This method is capable of running a string containing multiple source
1767 1793 lines, as if they had been entered at the IPython prompt. Since it
1768 1794 exposes IPython's processing machinery, the given strings can contain
1769 1795 magic calls (%magic), special shell access (!cmd), etc."""
1770 1796
1771 1797 # We must start with a clean buffer, in case this is run from an
1772 1798 # interactive IPython session (via a magic, for example).
1773 1799 self.resetbuffer()
1774 1800 lines = lines.split('\n')
1775 1801 more = 0
1776 1802 for line in lines:
1777 1803 # skip blank lines so we don't mess up the prompt counter, but do
1778 1804 # NOT skip even a blank line if we are in a code block (more is
1779 1805 # true)
1780 1806 if line or more:
1781 1807 more = self.push(self.prefilter(line,more))
1782 1808 # IPython's runsource returns None if there was an error
1783 1809 # compiling the code. This allows us to stop processing right
1784 1810 # away, so the user gets the error message at the right place.
1785 1811 if more is None:
1786 1812 break
1787 1813 # final newline in case the input didn't have it, so that the code
1788 1814 # actually does get executed
1789 1815 if more:
1790 1816 self.push('\n')
1791 1817
1792 1818 def runsource(self, source, filename='<input>', symbol='single'):
1793 1819 """Compile and run some source in the interpreter.
1794 1820
1795 1821 Arguments are as for compile_command().
1796 1822
1797 1823 One several things can happen:
1798 1824
1799 1825 1) The input is incorrect; compile_command() raised an
1800 1826 exception (SyntaxError or OverflowError). A syntax traceback
1801 1827 will be printed by calling the showsyntaxerror() method.
1802 1828
1803 1829 2) The input is incomplete, and more input is required;
1804 1830 compile_command() returned None. Nothing happens.
1805 1831
1806 1832 3) The input is complete; compile_command() returned a code
1807 1833 object. The code is executed by calling self.runcode() (which
1808 1834 also handles run-time exceptions, except for SystemExit).
1809 1835
1810 1836 The return value is:
1811 1837
1812 1838 - True in case 2
1813 1839
1814 1840 - False in the other cases, unless an exception is raised, where
1815 1841 None is returned instead. This can be used by external callers to
1816 1842 know whether to continue feeding input or not.
1817 1843
1818 1844 The return value can be used to decide whether to use sys.ps1 or
1819 1845 sys.ps2 to prompt the next line."""
1820 1846
1821 1847 try:
1822 1848 code = self.compile(source,filename,symbol)
1823 1849 except (OverflowError, SyntaxError, ValueError):
1824 1850 # Case 1
1825 1851 self.showsyntaxerror(filename)
1826 1852 return None
1827 1853
1828 1854 if code is None:
1829 1855 # Case 2
1830 1856 return True
1831 1857
1832 1858 # Case 3
1833 1859 # We store the code object so that threaded shells and
1834 1860 # custom exception handlers can access all this info if needed.
1835 1861 # The source corresponding to this can be obtained from the
1836 1862 # buffer attribute as '\n'.join(self.buffer).
1837 1863 self.code_to_run = code
1838 1864 # now actually execute the code object
1839 1865 if self.runcode(code) == 0:
1840 1866 return False
1841 1867 else:
1842 1868 return None
1843 1869
1844 1870 def runcode(self,code_obj):
1845 1871 """Execute a code object.
1846 1872
1847 1873 When an exception occurs, self.showtraceback() is called to display a
1848 1874 traceback.
1849 1875
1850 1876 Return value: a flag indicating whether the code to be run completed
1851 1877 successfully:
1852 1878
1853 1879 - 0: successful execution.
1854 1880 - 1: an error occurred.
1855 1881 """
1856 1882
1857 1883 # Set our own excepthook in case the user code tries to call it
1858 1884 # directly, so that the IPython crash handler doesn't get triggered
1859 1885 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1860 1886
1861 1887 # we save the original sys.excepthook in the instance, in case config
1862 1888 # code (such as magics) needs access to it.
1863 1889 self.sys_excepthook = old_excepthook
1864 1890 outflag = 1 # happens in more places, so it's easier as default
1865 1891 try:
1866 1892 try:
1867 1893 # Embedded instances require separate global/local namespaces
1868 1894 # so they can see both the surrounding (local) namespace and
1869 1895 # the module-level globals when called inside another function.
1870 1896 if self.embedded:
1871 1897 exec code_obj in self.user_global_ns, self.user_ns
1872 1898 # Normal (non-embedded) instances should only have a single
1873 1899 # namespace for user code execution, otherwise functions won't
1874 1900 # see interactive top-level globals.
1875 1901 else:
1876 1902 exec code_obj in self.user_ns
1877 1903 finally:
1878 1904 # Reset our crash handler in place
1879 1905 sys.excepthook = old_excepthook
1880 1906 except SystemExit:
1881 1907 self.resetbuffer()
1882 1908 self.showtraceback()
1883 1909 warn("Type %exit or %quit to exit IPython "
1884 1910 "(%Exit or %Quit do so unconditionally).",level=1)
1885 1911 except self.custom_exceptions:
1886 1912 etype,value,tb = sys.exc_info()
1887 1913 self.CustomTB(etype,value,tb)
1888 1914 except:
1889 1915 self.showtraceback()
1890 1916 else:
1891 1917 outflag = 0
1892 1918 if softspace(sys.stdout, 0):
1893 1919 print
1894 1920 # Flush out code object which has been run (and source)
1895 1921 self.code_to_run = None
1896 1922 return outflag
1897 1923
1898 1924 def push(self, line):
1899 1925 """Push a line to the interpreter.
1900 1926
1901 1927 The line should not have a trailing newline; it may have
1902 1928 internal newlines. The line is appended to a buffer and the
1903 1929 interpreter's runsource() method is called with the
1904 1930 concatenated contents of the buffer as source. If this
1905 1931 indicates that the command was executed or invalid, the buffer
1906 1932 is reset; otherwise, the command is incomplete, and the buffer
1907 1933 is left as it was after the line was appended. The return
1908 1934 value is 1 if more input is required, 0 if the line was dealt
1909 1935 with in some way (this is the same as runsource()).
1910 1936 """
1911 1937
1912 1938 # autoindent management should be done here, and not in the
1913 1939 # interactive loop, since that one is only seen by keyboard input. We
1914 1940 # need this done correctly even for code run via runlines (which uses
1915 1941 # push).
1916 1942
1917 1943 #print 'push line: <%s>' % line # dbg
1918 1944 for subline in line.splitlines():
1919 1945 self.autoindent_update(subline)
1920 1946 self.buffer.append(line)
1921 1947 more = self.runsource('\n'.join(self.buffer), self.filename)
1922 1948 if not more:
1923 1949 self.resetbuffer()
1924 1950 return more
1925 1951
1926 1952 def resetbuffer(self):
1927 1953 """Reset the input buffer."""
1928 1954 self.buffer[:] = []
1929 1955
1930 1956 def raw_input(self,prompt='',continue_prompt=False):
1931 1957 """Write a prompt and read a line.
1932 1958
1933 1959 The returned line does not include the trailing newline.
1934 1960 When the user enters the EOF key sequence, EOFError is raised.
1935 1961
1936 1962 Optional inputs:
1937 1963
1938 1964 - prompt(''): a string to be printed to prompt the user.
1939 1965
1940 1966 - continue_prompt(False): whether this line is the first one or a
1941 1967 continuation in a sequence of inputs.
1942 1968 """
1943 1969
1944 1970 try:
1945 1971 line = raw_input_original(prompt)
1946 1972 except ValueError:
1947 1973 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1948 1974 self.exit_now = True
1949 1975 return ""
1950 1976
1951 1977
1952 1978 # Try to be reasonably smart about not re-indenting pasted input more
1953 1979 # than necessary. We do this by trimming out the auto-indent initial
1954 1980 # spaces, if the user's actual input started itself with whitespace.
1955 1981 #debugx('self.buffer[-1]')
1956 1982
1957 1983 if self.autoindent:
1958 1984 if num_ini_spaces(line) > self.indent_current_nsp:
1959 1985 line = line[self.indent_current_nsp:]
1960 1986 self.indent_current_nsp = 0
1961 1987
1962 1988 # store the unfiltered input before the user has any chance to modify
1963 1989 # it.
1964 1990 if line.strip():
1965 1991 if continue_prompt:
1966 1992 self.input_hist_raw[-1] += '%s\n' % line
1967 1993 if self.has_readline: # and some config option is set?
1968 1994 try:
1969 1995 histlen = self.readline.get_current_history_length()
1970 1996 newhist = self.input_hist_raw[-1].rstrip()
1971 1997 self.readline.remove_history_item(histlen-1)
1972 1998 self.readline.replace_history_item(histlen-2,newhist)
1973 1999 except AttributeError:
1974 2000 pass # re{move,place}_history_item are new in 2.4.
1975 2001 else:
1976 2002 self.input_hist_raw.append('%s\n' % line)
1977 2003
1978 2004 try:
1979 2005 lineout = self.prefilter(line,continue_prompt)
1980 2006 except:
1981 2007 # blanket except, in case a user-defined prefilter crashes, so it
1982 2008 # can't take all of ipython with it.
1983 2009 self.showtraceback()
1984 2010 return ''
1985 2011 else:
1986 2012 return lineout
1987 2013
1988 2014 def split_user_input(self,line):
1989 2015 """Split user input into pre-char, function part and rest."""
1990 2016
1991 2017 lsplit = self.line_split.match(line)
1992 2018 if lsplit is None: # no regexp match returns None
1993 2019 try:
1994 2020 iFun,theRest = line.split(None,1)
1995 2021 except ValueError:
1996 2022 iFun,theRest = line,''
1997 2023 pre = re.match('^(\s*)(.*)',line).groups()[0]
1998 2024 else:
1999 2025 pre,iFun,theRest = lsplit.groups()
2000 2026
2001 2027 #print 'line:<%s>' % line # dbg
2002 2028 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
2003 2029 return pre,iFun.strip(),theRest
2004 2030
2005 2031 def _prefilter(self, line, continue_prompt):
2006 2032 """Calls different preprocessors, depending on the form of line."""
2007 2033
2008 2034 # All handlers *must* return a value, even if it's blank ('').
2009 2035
2010 2036 # Lines are NOT logged here. Handlers should process the line as
2011 2037 # needed, update the cache AND log it (so that the input cache array
2012 2038 # stays synced).
2013 2039
2014 2040 # This function is _very_ delicate, and since it's also the one which
2015 2041 # determines IPython's response to user input, it must be as efficient
2016 2042 # as possible. For this reason it has _many_ returns in it, trying
2017 2043 # always to exit as quickly as it can figure out what it needs to do.
2018 2044
2019 2045 # This function is the main responsible for maintaining IPython's
2020 2046 # behavior respectful of Python's semantics. So be _very_ careful if
2021 2047 # making changes to anything here.
2022 2048
2023 2049 #.....................................................................
2024 2050 # Code begins
2025 2051
2026 2052 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2027 2053
2028 2054 # save the line away in case we crash, so the post-mortem handler can
2029 2055 # record it
2030 2056 self._last_input_line = line
2031 2057
2032 2058 #print '***line: <%s>' % line # dbg
2033 2059
2034 2060 # the input history needs to track even empty lines
2035 2061 stripped = line.strip()
2036 2062
2037 2063 if not stripped:
2038 2064 if not continue_prompt:
2039 2065 self.outputcache.prompt_count -= 1
2040 2066 return self.handle_normal(line,continue_prompt)
2041 2067 #return self.handle_normal('',continue_prompt)
2042 2068
2043 2069 # print '***cont',continue_prompt # dbg
2044 2070 # special handlers are only allowed for single line statements
2045 2071 if continue_prompt and not self.rc.multi_line_specials:
2046 2072 return self.handle_normal(line,continue_prompt)
2047 2073
2048 2074
2049 2075 # For the rest, we need the structure of the input
2050 2076 pre,iFun,theRest = self.split_user_input(line)
2051 2077
2052 2078 # See whether any pre-existing handler can take care of it
2053 2079
2054 2080 rewritten = self.hooks.input_prefilter(stripped)
2055 2081 if rewritten != stripped: # ok, some prefilter did something
2056 2082 rewritten = pre + rewritten # add indentation
2057 2083 return self.handle_normal(rewritten)
2058 2084
2059 2085 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2060 2086
2061 2087 # First check for explicit escapes in the last/first character
2062 2088 handler = None
2063 2089 if line[-1] == self.ESC_HELP:
2064 2090 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
2065 2091 if handler is None:
2066 2092 # look at the first character of iFun, NOT of line, so we skip
2067 2093 # leading whitespace in multiline input
2068 2094 handler = self.esc_handlers.get(iFun[0:1])
2069 2095 if handler is not None:
2070 2096 return handler(line,continue_prompt,pre,iFun,theRest)
2071 2097 # Emacs ipython-mode tags certain input lines
2072 2098 if line.endswith('# PYTHON-MODE'):
2073 2099 return self.handle_emacs(line,continue_prompt)
2074 2100
2075 2101 # Next, check if we can automatically execute this thing
2076 2102
2077 2103 # Allow ! in multi-line statements if multi_line_specials is on:
2078 2104 if continue_prompt and self.rc.multi_line_specials and \
2079 2105 iFun.startswith(self.ESC_SHELL):
2080 2106 return self.handle_shell_escape(line,continue_prompt,
2081 2107 pre=pre,iFun=iFun,
2082 2108 theRest=theRest)
2083 2109
2084 2110 # Let's try to find if the input line is a magic fn
2085 2111 oinfo = None
2086 2112 if hasattr(self,'magic_'+iFun):
2087 2113 # WARNING: _ofind uses getattr(), so it can consume generators and
2088 2114 # cause other side effects.
2089 2115 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2090 2116 if oinfo['ismagic']:
2091 2117 # Be careful not to call magics when a variable assignment is
2092 2118 # being made (ls='hi', for example)
2093 2119 if self.rc.automagic and \
2094 2120 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2095 2121 (self.rc.multi_line_specials or not continue_prompt):
2096 2122 return self.handle_magic(line,continue_prompt,
2097 2123 pre,iFun,theRest)
2098 2124 else:
2099 2125 return self.handle_normal(line,continue_prompt)
2100 2126
2101 2127 # If the rest of the line begins with an (in)equality, assginment or
2102 2128 # function call, we should not call _ofind but simply execute it.
2103 2129 # This avoids spurious geattr() accesses on objects upon assignment.
2104 2130 #
2105 2131 # It also allows users to assign to either alias or magic names true
2106 2132 # python variables (the magic/alias systems always take second seat to
2107 2133 # true python code).
2108 2134 if theRest and theRest[0] in '!=()':
2109 2135 return self.handle_normal(line,continue_prompt)
2110 2136
2111 2137 if oinfo is None:
2112 2138 # let's try to ensure that _oinfo is ONLY called when autocall is
2113 2139 # on. Since it has inevitable potential side effects, at least
2114 2140 # having autocall off should be a guarantee to the user that no
2115 2141 # weird things will happen.
2116 2142
2117 2143 if self.rc.autocall:
2118 2144 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2119 2145 else:
2120 2146 # in this case, all that's left is either an alias or
2121 2147 # processing the line normally.
2122 2148 if iFun in self.alias_table:
2123 2149 # if autocall is off, by not running _ofind we won't know
2124 2150 # whether the given name may also exist in one of the
2125 2151 # user's namespace. At this point, it's best to do a
2126 2152 # quick check just to be sure that we don't let aliases
2127 2153 # shadow variables.
2128 2154 head = iFun.split('.',1)[0]
2129 2155 if head in self.user_ns or head in self.internal_ns \
2130 2156 or head in __builtin__.__dict__:
2131 2157 return self.handle_normal(line,continue_prompt)
2132 2158 else:
2133 2159 return self.handle_alias(line,continue_prompt,
2134 2160 pre,iFun,theRest)
2135 2161
2136 2162 else:
2137 2163 return self.handle_normal(line,continue_prompt)
2138 2164
2139 2165 if not oinfo['found']:
2140 2166 return self.handle_normal(line,continue_prompt)
2141 2167 else:
2142 2168 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2143 2169 if oinfo['isalias']:
2144 2170 return self.handle_alias(line,continue_prompt,
2145 2171 pre,iFun,theRest)
2146 2172
2147 2173 if (self.rc.autocall
2148 2174 and
2149 2175 (
2150 2176 #only consider exclusion re if not "," or ";" autoquoting
2151 2177 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2152 2178 or pre == self.ESC_PAREN) or
2153 2179 (not self.re_exclude_auto.match(theRest)))
2154 2180 and
2155 2181 self.re_fun_name.match(iFun) and
2156 2182 callable(oinfo['obj'])) :
2157 2183 #print 'going auto' # dbg
2158 2184 return self.handle_auto(line,continue_prompt,
2159 2185 pre,iFun,theRest,oinfo['obj'])
2160 2186 else:
2161 2187 #print 'was callable?', callable(oinfo['obj']) # dbg
2162 2188 return self.handle_normal(line,continue_prompt)
2163 2189
2164 2190 # If we get here, we have a normal Python line. Log and return.
2165 2191 return self.handle_normal(line,continue_prompt)
2166 2192
2167 2193 def _prefilter_dumb(self, line, continue_prompt):
2168 2194 """simple prefilter function, for debugging"""
2169 2195 return self.handle_normal(line,continue_prompt)
2170 2196
2171 2197
2172 2198 def multiline_prefilter(self, line, continue_prompt):
2173 2199 """ Run _prefilter for each line of input
2174 2200
2175 2201 Covers cases where there are multiple lines in the user entry,
2176 2202 which is the case when the user goes back to a multiline history
2177 2203 entry and presses enter.
2178 2204
2179 2205 """
2180 2206 out = []
2181 2207 for l in line.rstrip('\n').split('\n'):
2182 2208 out.append(self._prefilter(l, continue_prompt))
2183 2209 return '\n'.join(out)
2184 2210
2185 2211 # Set the default prefilter() function (this can be user-overridden)
2186 2212 prefilter = multiline_prefilter
2187 2213
2188 2214 def handle_normal(self,line,continue_prompt=None,
2189 2215 pre=None,iFun=None,theRest=None):
2190 2216 """Handle normal input lines. Use as a template for handlers."""
2191 2217
2192 2218 # With autoindent on, we need some way to exit the input loop, and I
2193 2219 # don't want to force the user to have to backspace all the way to
2194 2220 # clear the line. The rule will be in this case, that either two
2195 2221 # lines of pure whitespace in a row, or a line of pure whitespace but
2196 2222 # of a size different to the indent level, will exit the input loop.
2197 2223
2198 2224 if (continue_prompt and self.autoindent and line.isspace() and
2199 2225 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2200 2226 (self.buffer[-1]).isspace() )):
2201 2227 line = ''
2202 2228
2203 2229 self.log(line,line,continue_prompt)
2204 2230 return line
2205 2231
2206 2232 def handle_alias(self,line,continue_prompt=None,
2207 2233 pre=None,iFun=None,theRest=None):
2208 2234 """Handle alias input lines. """
2209 2235
2210 2236 # pre is needed, because it carries the leading whitespace. Otherwise
2211 2237 # aliases won't work in indented sections.
2212 2238 transformed = self.expand_aliases(iFun, theRest)
2213 2239 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2214 2240 self.log(line,line_out,continue_prompt)
2215 2241 #print 'line out:',line_out # dbg
2216 2242 return line_out
2217 2243
2218 2244 def handle_shell_escape(self, line, continue_prompt=None,
2219 2245 pre=None,iFun=None,theRest=None):
2220 2246 """Execute the line in a shell, empty return value"""
2221 2247
2222 2248 #print 'line in :', `line` # dbg
2223 2249 # Example of a special handler. Others follow a similar pattern.
2224 2250 if line.lstrip().startswith('!!'):
2225 2251 # rewrite iFun/theRest to properly hold the call to %sx and
2226 2252 # the actual command to be executed, so handle_magic can work
2227 2253 # correctly
2228 2254 theRest = '%s %s' % (iFun[2:],theRest)
2229 2255 iFun = 'sx'
2230 2256 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2231 2257 line.lstrip()[2:]),
2232 2258 continue_prompt,pre,iFun,theRest)
2233 2259 else:
2234 2260 cmd=line.lstrip().lstrip('!')
2235 2261 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2236 2262 # update cache/log and return
2237 2263 self.log(line,line_out,continue_prompt)
2238 2264 return line_out
2239 2265
2240 2266 def handle_magic(self, line, continue_prompt=None,
2241 2267 pre=None,iFun=None,theRest=None):
2242 2268 """Execute magic functions."""
2243 2269
2244 2270
2245 2271 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2246 2272 self.log(line,cmd,continue_prompt)
2247 2273 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2248 2274 return cmd
2249 2275
2250 2276 def handle_auto(self, line, continue_prompt=None,
2251 2277 pre=None,iFun=None,theRest=None,obj=None):
2252 2278 """Hande lines which can be auto-executed, quoting if requested."""
2253 2279
2254 2280 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2255 2281
2256 2282 # This should only be active for single-line input!
2257 2283 if continue_prompt:
2258 2284 self.log(line,line,continue_prompt)
2259 2285 return line
2260 2286
2261 2287 auto_rewrite = True
2262 2288
2263 2289 if pre == self.ESC_QUOTE:
2264 2290 # Auto-quote splitting on whitespace
2265 2291 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2266 2292 elif pre == self.ESC_QUOTE2:
2267 2293 # Auto-quote whole string
2268 2294 newcmd = '%s("%s")' % (iFun,theRest)
2269 2295 elif pre == self.ESC_PAREN:
2270 2296 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2271 2297 else:
2272 2298 # Auto-paren.
2273 2299 # We only apply it to argument-less calls if the autocall
2274 2300 # parameter is set to 2. We only need to check that autocall is <
2275 2301 # 2, since this function isn't called unless it's at least 1.
2276 2302 if not theRest and (self.rc.autocall < 2):
2277 2303 newcmd = '%s %s' % (iFun,theRest)
2278 2304 auto_rewrite = False
2279 2305 else:
2280 2306 if theRest.startswith('['):
2281 2307 if hasattr(obj,'__getitem__'):
2282 2308 # Don't autocall in this case: item access for an object
2283 2309 # which is BOTH callable and implements __getitem__.
2284 2310 newcmd = '%s %s' % (iFun,theRest)
2285 2311 auto_rewrite = False
2286 2312 else:
2287 2313 # if the object doesn't support [] access, go ahead and
2288 2314 # autocall
2289 2315 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2290 2316 elif theRest.endswith(';'):
2291 2317 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2292 2318 else:
2293 2319 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2294 2320
2295 2321 if auto_rewrite:
2296 2322 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2297 2323 # log what is now valid Python, not the actual user input (without the
2298 2324 # final newline)
2299 2325 self.log(line,newcmd,continue_prompt)
2300 2326 return newcmd
2301 2327
2302 2328 def handle_help(self, line, continue_prompt=None,
2303 2329 pre=None,iFun=None,theRest=None):
2304 2330 """Try to get some help for the object.
2305 2331
2306 2332 obj? or ?obj -> basic information.
2307 2333 obj?? or ??obj -> more details.
2308 2334 """
2309 2335
2310 2336 # We need to make sure that we don't process lines which would be
2311 2337 # otherwise valid python, such as "x=1 # what?"
2312 2338 try:
2313 2339 codeop.compile_command(line)
2314 2340 except SyntaxError:
2315 2341 # We should only handle as help stuff which is NOT valid syntax
2316 2342 if line[0]==self.ESC_HELP:
2317 2343 line = line[1:]
2318 2344 elif line[-1]==self.ESC_HELP:
2319 2345 line = line[:-1]
2320 2346 self.log(line,'#?'+line,continue_prompt)
2321 2347 if line:
2322 2348 self.magic_pinfo(line)
2323 2349 else:
2324 2350 page(self.usage,screen_lines=self.rc.screen_length)
2325 2351 return '' # Empty string is needed here!
2326 2352 except:
2327 2353 # Pass any other exceptions through to the normal handler
2328 2354 return self.handle_normal(line,continue_prompt)
2329 2355 else:
2330 2356 # If the code compiles ok, we should handle it normally
2331 2357 return self.handle_normal(line,continue_prompt)
2332 2358
2333 2359 def getapi(self):
2334 2360 """ Get an IPApi object for this shell instance
2335 2361
2336 2362 Getting an IPApi object is always preferable to accessing the shell
2337 2363 directly, but this holds true especially for extensions.
2338 2364
2339 2365 It should always be possible to implement an extension with IPApi
2340 2366 alone. If not, contact maintainer to request an addition.
2341 2367
2342 2368 """
2343 2369 return self.api
2344 2370
2345 2371 def handle_emacs(self,line,continue_prompt=None,
2346 2372 pre=None,iFun=None,theRest=None):
2347 2373 """Handle input lines marked by python-mode."""
2348 2374
2349 2375 # Currently, nothing is done. Later more functionality can be added
2350 2376 # here if needed.
2351 2377
2352 2378 # The input cache shouldn't be updated
2353 2379
2354 2380 return line
2355 2381
2356 2382 def mktempfile(self,data=None):
2357 2383 """Make a new tempfile and return its filename.
2358 2384
2359 2385 This makes a call to tempfile.mktemp, but it registers the created
2360 2386 filename internally so ipython cleans it up at exit time.
2361 2387
2362 2388 Optional inputs:
2363 2389
2364 2390 - data(None): if data is given, it gets written out to the temp file
2365 2391 immediately, and the file is closed again."""
2366 2392
2367 2393 filename = tempfile.mktemp('.py','ipython_edit_')
2368 2394 self.tempfiles.append(filename)
2369 2395
2370 2396 if data:
2371 2397 tmp_file = open(filename,'w')
2372 2398 tmp_file.write(data)
2373 2399 tmp_file.close()
2374 2400 return filename
2375 2401
2376 2402 def write(self,data):
2377 2403 """Write a string to the default output"""
2378 2404 Term.cout.write(data)
2379 2405
2380 2406 def write_err(self,data):
2381 2407 """Write a string to the default error output"""
2382 2408 Term.cerr.write(data)
2383 2409
2384 2410 def exit(self):
2385 2411 """Handle interactive exit.
2386 2412
2387 2413 This method sets the exit_now attribute."""
2388 2414
2389 2415 if self.rc.confirm_exit:
2390 2416 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2391 2417 self.exit_now = True
2392 2418 else:
2393 2419 self.exit_now = True
2394 2420
2395 2421 def safe_execfile(self,fname,*where,**kw):
2396 2422 fname = os.path.expanduser(fname)
2397 2423
2398 2424 try:
2399 2425 xfile = open(fname)
2400 2426 except:
2401 2427 print >> Term.cerr, \
2402 2428 'Could not open file <%s> for safe execution.' % fname
2403 2429 return None
2404 2430
2405 2431 kw.setdefault('islog',0)
2406 2432 kw.setdefault('quiet',1)
2407 2433 kw.setdefault('exit_ignore',0)
2408 2434 first = xfile.readline()
2409 2435 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2410 2436 xfile.close()
2411 2437 # line by line execution
2412 2438 if first.startswith(loghead) or kw['islog']:
2413 2439 print 'Loading log file <%s> one line at a time...' % fname
2414 2440 if kw['quiet']:
2415 2441 stdout_save = sys.stdout
2416 2442 sys.stdout = StringIO.StringIO()
2417 2443 try:
2418 2444 globs,locs = where[0:2]
2419 2445 except:
2420 2446 try:
2421 2447 globs = locs = where[0]
2422 2448 except:
2423 2449 globs = locs = globals()
2424 2450 badblocks = []
2425 2451
2426 2452 # we also need to identify indented blocks of code when replaying
2427 2453 # logs and put them together before passing them to an exec
2428 2454 # statement. This takes a bit of regexp and look-ahead work in the
2429 2455 # file. It's easiest if we swallow the whole thing in memory
2430 2456 # first, and manually walk through the lines list moving the
2431 2457 # counter ourselves.
2432 2458 indent_re = re.compile('\s+\S')
2433 2459 xfile = open(fname)
2434 2460 filelines = xfile.readlines()
2435 2461 xfile.close()
2436 2462 nlines = len(filelines)
2437 2463 lnum = 0
2438 2464 while lnum < nlines:
2439 2465 line = filelines[lnum]
2440 2466 lnum += 1
2441 2467 # don't re-insert logger status info into cache
2442 2468 if line.startswith('#log#'):
2443 2469 continue
2444 2470 else:
2445 2471 # build a block of code (maybe a single line) for execution
2446 2472 block = line
2447 2473 try:
2448 2474 next = filelines[lnum] # lnum has already incremented
2449 2475 except:
2450 2476 next = None
2451 2477 while next and indent_re.match(next):
2452 2478 block += next
2453 2479 lnum += 1
2454 2480 try:
2455 2481 next = filelines[lnum]
2456 2482 except:
2457 2483 next = None
2458 2484 # now execute the block of one or more lines
2459 2485 try:
2460 2486 exec block in globs,locs
2461 2487 except SystemExit:
2462 2488 pass
2463 2489 except:
2464 2490 badblocks.append(block.rstrip())
2465 2491 if kw['quiet']: # restore stdout
2466 2492 sys.stdout.close()
2467 2493 sys.stdout = stdout_save
2468 2494 print 'Finished replaying log file <%s>' % fname
2469 2495 if badblocks:
2470 2496 print >> sys.stderr, ('\nThe following lines/blocks in file '
2471 2497 '<%s> reported errors:' % fname)
2472 2498
2473 2499 for badline in badblocks:
2474 2500 print >> sys.stderr, badline
2475 2501 else: # regular file execution
2476 2502 try:
2477 2503 execfile(fname,*where)
2478 2504 except SyntaxError:
2479 2505 self.showsyntaxerror()
2480 2506 warn('Failure executing file: <%s>' % fname)
2481 2507 except SystemExit,status:
2482 2508 if not kw['exit_ignore']:
2483 2509 self.showtraceback()
2484 2510 warn('Failure executing file: <%s>' % fname)
2485 2511 except:
2486 2512 self.showtraceback()
2487 2513 warn('Failure executing file: <%s>' % fname)
2488 2514
2489 2515 #************************* end of file <iplib.py> *****************************
@@ -1,754 +1,755 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or better.
6 6
7 7 This file contains the main make_IPython() starter function.
8 8
9 $Id: ipmaker.py 1384 2006-06-29 20:04:37Z vivainio $"""
9 $Id: ipmaker.py 1879 2006-11-04 00:34:34Z fptest $"""
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #*****************************************************************************
17 17
18 18 from IPython import Release
19 19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 20 __license__ = Release.license
21 21 __version__ = Release.version
22 22
23 23 credits._Printer__data = """
24 24 Python: %s
25 25
26 26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 27 See http://ipython.scipy.org for more information.""" \
28 28 % credits._Printer__data
29 29
30 30 copyright._Printer__data += """
31 31
32 32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 33 All Rights Reserved."""
34 34
35 35 #****************************************************************************
36 36 # Required modules
37 37
38 38 # From the standard library
39 39 import __main__
40 40 import __builtin__
41 41 import os
42 42 import re
43 43 import sys
44 44 import types
45 45 from pprint import pprint,pformat
46 46
47 47 # Our own
48 48 from IPython import DPyGetOpt
49 49 from IPython.ipstruct import Struct
50 50 from IPython.OutputTrap import OutputTrap
51 51 from IPython.ConfigLoader import ConfigLoader
52 52 from IPython.iplib import InteractiveShell
53 53 from IPython.usage import cmd_line_usage,interactive_usage
54 54 from IPython.genutils import *
55 55
56 56 #-----------------------------------------------------------------------------
57 57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
58 58 rc_override=None,shell_class=InteractiveShell,
59 59 embedded=False,**kw):
60 60 """This is a dump of IPython into a single function.
61 61
62 62 Later it will have to be broken up in a sensible manner.
63 63
64 64 Arguments:
65 65
66 66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 67 script name, b/c DPyGetOpt strips the first argument only for the real
68 68 sys.argv.
69 69
70 70 - user_ns: a dict to be used as the user's namespace."""
71 71
72 72 #----------------------------------------------------------------------
73 73 # Defaults and initialization
74 74
75 75 # For developer debugging, deactivates crash handler and uses pdb.
76 76 DEVDEBUG = False
77 77
78 78 if argv is None:
79 79 argv = sys.argv
80 80
81 81 # __IP is the main global that lives throughout and represents the whole
82 82 # application. If the user redefines it, all bets are off as to what
83 83 # happens.
84 84
85 85 # __IP is the name of he global which the caller will have accessible as
86 86 # __IP.name. We set its name via the first parameter passed to
87 87 # InteractiveShell:
88 88
89 89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
90 90 embedded=embedded,**kw)
91 91
92 92 # Put 'help' in the user namespace
93 93 from site import _Helper
94 94 IP.user_ns['help'] = _Helper()
95 95
96 96
97 97 if DEVDEBUG:
98 98 # For developer debugging only (global flag)
99 99 from IPython import ultraTB
100 100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
101 101
102 102 IP.BANNER_PARTS = ['Python %s\n'
103 103 'Type "copyright", "credits" or "license" '
104 104 'for more information.\n'
105 105 % (sys.version.split('\n')[0],),
106 106 "IPython %s -- An enhanced Interactive Python."
107 107 % (__version__,),
108 108 """? -> Introduction to IPython's features.
109 109 %magic -> Information about IPython's 'magic' % functions.
110 110 help -> Python's own help system.
111 111 object? -> Details about 'object'. ?object also works, ?? prints more.
112 112 """ ]
113 113
114 114 IP.usage = interactive_usage
115 115
116 116 # Platform-dependent suffix and directory names. We use _ipython instead
117 117 # of .ipython under win32 b/c there's software that breaks with .named
118 118 # directories on that platform.
119 119 if os.name == 'posix':
120 120 rc_suffix = ''
121 121 ipdir_def = '.ipython'
122 122 else:
123 123 rc_suffix = '.ini'
124 124 ipdir_def = '_ipython'
125 125
126 126 # default directory for configuration
127 127 ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR',
128 128 os.path.join(IP.home_dir,ipdir_def)))
129 129
130 130 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
131 131
132 132 # we need the directory where IPython itself is installed
133 133 import IPython
134 134 IPython_dir = os.path.dirname(IPython.__file__)
135 135 del IPython
136 136
137 137 #-------------------------------------------------------------------------
138 138 # Command line handling
139 139
140 140 # Valid command line options (uses DPyGetOpt syntax, like Perl's
141 141 # GetOpt::Long)
142 142
143 143 # Any key not listed here gets deleted even if in the file (like session
144 144 # or profile). That's deliberate, to maintain the rc namespace clean.
145 145
146 146 # Each set of options appears twice: under _conv only the names are
147 147 # listed, indicating which type they must be converted to when reading the
148 148 # ipythonrc file. And under DPyGetOpt they are listed with the regular
149 149 # DPyGetOpt syntax (=s,=i,:f,etc).
150 150
151 151 # Make sure there's a space before each end of line (they get auto-joined!)
152 152 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
153 153 'c=s classic|cl color_info! colors=s confirm_exit! '
154 154 'debug! deep_reload! editor=s log|l messages! nosep '
155 155 'object_info_string_level=i pdb! '
156 156 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
157 157 'quick screen_length|sl=i prompts_pad_left=i '
158 158 'logfile|lf=s logplay|lp=s profile|p=s '
159 159 'readline! readline_merge_completions! '
160 160 'readline_omit__names! '
161 161 'rcfile=s separate_in|si=s separate_out|so=s '
162 162 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
163 163 'magic_docstrings system_verbose! '
164 164 'multi_line_specials! '
165 165 'wxversion=s '
166 166 'autoedit_syntax!')
167 167
168 168 # Options that can *only* appear at the cmd line (not in rcfiles).
169 169
170 170 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
171 171 # the 'C-c !' command in emacs automatically appends a -i option at the end.
172 172 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
173 173 'gthread! qthread! q4thread! wthread! pylab! tk!')
174 174
175 175 # Build the actual name list to be used by DPyGetOpt
176 176 opts_names = qw(cmdline_opts) + qw(cmdline_only)
177 177
178 178 # Set sensible command line defaults.
179 179 # This should have everything from cmdline_opts and cmdline_only
180 180 opts_def = Struct(autocall = 1,
181 181 autoedit_syntax = 0,
182 182 autoindent = 0,
183 183 automagic = 1,
184 184 banner = 1,
185 185 cache_size = 1000,
186 186 c = '',
187 187 classic = 0,
188 188 colors = 'NoColor',
189 189 color_info = 0,
190 190 confirm_exit = 1,
191 191 debug = 0,
192 192 deep_reload = 0,
193 193 editor = '0',
194 194 help = 0,
195 195 ignore = 0,
196 196 ipythondir = ipythondir_def,
197 197 log = 0,
198 198 logfile = '',
199 199 logplay = '',
200 200 multi_line_specials = 1,
201 201 messages = 1,
202 202 object_info_string_level = 0,
203 203 nosep = 0,
204 204 pdb = 0,
205 205 pprint = 0,
206 206 profile = '',
207 207 prompt_in1 = 'In [\\#]: ',
208 208 prompt_in2 = ' .\\D.: ',
209 209 prompt_out = 'Out[\\#]: ',
210 210 prompts_pad_left = 1,
211 211 quiet = 0,
212 212 quick = 0,
213 213 readline = 1,
214 214 readline_merge_completions = 1,
215 215 readline_omit__names = 0,
216 216 rcfile = 'ipythonrc' + rc_suffix,
217 217 screen_length = 0,
218 218 separate_in = '\n',
219 219 separate_out = '\n',
220 220 separate_out2 = '',
221 system_header = 'IPython system call: ',
221 222 system_verbose = 0,
222 223 gthread = 0,
223 224 qthread = 0,
224 225 q4thread = 0,
225 226 wthread = 0,
226 227 pylab = 0,
227 228 tk = 0,
228 229 upgrade = 0,
229 230 Version = 0,
230 231 xmode = 'Verbose',
231 232 wildcards_case_sensitive = 1,
232 233 wxversion = '0',
233 234 magic_docstrings = 0, # undocumented, for doc generation
234 235 )
235 236
236 237 # Things that will *only* appear in rcfiles (not at the command line).
237 238 # Make sure there's a space before each end of line (they get auto-joined!)
238 239 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
239 240 qw_lol: 'import_some ',
240 241 # for things with embedded whitespace:
241 242 list_strings:'execute alias readline_parse_and_bind ',
242 243 # Regular strings need no conversion:
243 244 None:'readline_remove_delims ',
244 245 }
245 246 # Default values for these
246 247 rc_def = Struct(include = [],
247 248 import_mod = [],
248 249 import_all = [],
249 250 import_some = [[]],
250 251 execute = [],
251 252 execfile = [],
252 253 alias = [],
253 254 readline_parse_and_bind = [],
254 255 readline_remove_delims = '',
255 256 )
256 257
257 258 # Build the type conversion dictionary from the above tables:
258 259 typeconv = rcfile_opts.copy()
259 260 typeconv.update(optstr2types(cmdline_opts))
260 261
261 262 # FIXME: the None key appears in both, put that back together by hand. Ugly!
262 263 typeconv[None] += ' ' + rcfile_opts[None]
263 264
264 265 # Remove quotes at ends of all strings (used to protect spaces)
265 266 typeconv[unquote_ends] = typeconv[None]
266 267 del typeconv[None]
267 268
268 269 # Build the list we'll use to make all config decisions with defaults:
269 270 opts_all = opts_def.copy()
270 271 opts_all.update(rc_def)
271 272
272 273 # Build conflict resolver for recursive loading of config files:
273 274 # - preserve means the outermost file maintains the value, it is not
274 275 # overwritten if an included file has the same key.
275 276 # - add_flip applies + to the two values, so it better make sense to add
276 277 # those types of keys. But it flips them first so that things loaded
277 278 # deeper in the inclusion chain have lower precedence.
278 279 conflict = {'preserve': ' '.join([ typeconv[int],
279 280 typeconv[unquote_ends] ]),
280 281 'add_flip': ' '.join([ typeconv[qwflat],
281 282 typeconv[qw_lol],
282 283 typeconv[list_strings] ])
283 284 }
284 285
285 286 # Now actually process the command line
286 287 getopt = DPyGetOpt.DPyGetOpt()
287 288 getopt.setIgnoreCase(0)
288 289
289 290 getopt.parseConfiguration(opts_names)
290 291
291 292 try:
292 293 getopt.processArguments(argv)
293 294 except:
294 295 print cmd_line_usage
295 296 warn('\nError in Arguments: ' + `sys.exc_value`)
296 297 sys.exit(1)
297 298
298 299 # convert the options dict to a struct for much lighter syntax later
299 300 opts = Struct(getopt.optionValues)
300 301 args = getopt.freeValues
301 302
302 303 # this is the struct (which has default values at this point) with which
303 304 # we make all decisions:
304 305 opts_all.update(opts)
305 306
306 307 # Options that force an immediate exit
307 308 if opts_all.help:
308 309 page(cmd_line_usage)
309 310 sys.exit()
310 311
311 312 if opts_all.Version:
312 313 print __version__
313 314 sys.exit()
314 315
315 316 if opts_all.magic_docstrings:
316 317 IP.magic_magic('-latex')
317 318 sys.exit()
318 319
319 320 # add personal ipythondir to sys.path so that users can put things in
320 321 # there for customization
321 322 sys.path.append(os.path.abspath(opts_all.ipythondir))
322 323
323 324 # Create user config directory if it doesn't exist. This must be done
324 325 # *after* getting the cmd line options.
325 326 if not os.path.isdir(opts_all.ipythondir):
326 327 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
327 328
328 329 # upgrade user config files while preserving a copy of the originals
329 330 if opts_all.upgrade:
330 331 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
331 332
332 333 # check mutually exclusive options in the *original* command line
333 334 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
334 335 qw('classic profile'),qw('classic rcfile')])
335 336
336 337 #---------------------------------------------------------------------------
337 338 # Log replay
338 339
339 340 # if -logplay, we need to 'become' the other session. That basically means
340 341 # replacing the current command line environment with that of the old
341 342 # session and moving on.
342 343
343 344 # this is needed so that later we know we're in session reload mode, as
344 345 # opts_all will get overwritten:
345 346 load_logplay = 0
346 347
347 348 if opts_all.logplay:
348 349 load_logplay = opts_all.logplay
349 350 opts_debug_save = opts_all.debug
350 351 try:
351 352 logplay = open(opts_all.logplay)
352 353 except IOError:
353 354 if opts_all.debug: IP.InteractiveTB()
354 355 warn('Could not open logplay file '+`opts_all.logplay`)
355 356 # restore state as if nothing had happened and move on, but make
356 357 # sure that later we don't try to actually load the session file
357 358 logplay = None
358 359 load_logplay = 0
359 360 del opts_all.logplay
360 361 else:
361 362 try:
362 363 logplay.readline()
363 364 logplay.readline();
364 365 # this reloads that session's command line
365 366 cmd = logplay.readline()[6:]
366 367 exec cmd
367 368 # restore the true debug flag given so that the process of
368 369 # session loading itself can be monitored.
369 370 opts.debug = opts_debug_save
370 371 # save the logplay flag so later we don't overwrite the log
371 372 opts.logplay = load_logplay
372 373 # now we must update our own structure with defaults
373 374 opts_all.update(opts)
374 375 # now load args
375 376 cmd = logplay.readline()[6:]
376 377 exec cmd
377 378 logplay.close()
378 379 except:
379 380 logplay.close()
380 381 if opts_all.debug: IP.InteractiveTB()
381 382 warn("Logplay file lacking full configuration information.\n"
382 383 "I'll try to read it, but some things may not work.")
383 384
384 385 #-------------------------------------------------------------------------
385 386 # set up output traps: catch all output from files, being run, modules
386 387 # loaded, etc. Then give it to the user in a clean form at the end.
387 388
388 389 msg_out = 'Output messages. '
389 390 msg_err = 'Error messages. '
390 391 msg_sep = '\n'
391 392 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
392 393 msg_err,msg_sep,debug,
393 394 quiet_out=1),
394 395 user_exec = OutputTrap('User File Execution',msg_out,
395 396 msg_err,msg_sep,debug),
396 397 logplay = OutputTrap('Log Loader',msg_out,
397 398 msg_err,msg_sep,debug),
398 399 summary = ''
399 400 )
400 401
401 402 #-------------------------------------------------------------------------
402 403 # Process user ipythonrc-type configuration files
403 404
404 405 # turn on output trapping and log to msg.config
405 406 # remember that with debug on, trapping is actually disabled
406 407 msg.config.trap_all()
407 408
408 409 # look for rcfile in current or default directory
409 410 try:
410 411 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
411 412 except IOError:
412 413 if opts_all.debug: IP.InteractiveTB()
413 414 warn('Configuration file %s not found. Ignoring request.'
414 415 % (opts_all.rcfile) )
415 416
416 417 # 'profiles' are a shorthand notation for config filenames
417 418 if opts_all.profile:
418 419
419 420 try:
420 421 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
421 422 + rc_suffix,
422 423 opts_all.ipythondir)
423 424 except IOError:
424 425 if opts_all.debug: IP.InteractiveTB()
425 426 opts.profile = '' # remove profile from options if invalid
426 427 # We won't warn anymore, primary method is ipy_profile_PROFNAME
427 428 # which does trigger a warning.
428 429
429 430 # load the config file
430 431 rcfiledata = None
431 432 if opts_all.quick:
432 433 print 'Launching IPython in quick mode. No config file read.'
433 434 elif opts_all.classic:
434 435 print 'Launching IPython in classic mode. No config file read.'
435 436 elif opts_all.rcfile:
436 437 try:
437 438 cfg_loader = ConfigLoader(conflict)
438 439 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
439 440 'include',opts_all.ipythondir,
440 441 purge = 1,
441 442 unique = conflict['preserve'])
442 443 except:
443 444 IP.InteractiveTB()
444 445 warn('Problems loading configuration file '+
445 446 `opts_all.rcfile`+
446 447 '\nStarting with default -bare bones- configuration.')
447 448 else:
448 449 warn('No valid configuration file found in either currrent directory\n'+
449 450 'or in the IPython config. directory: '+`opts_all.ipythondir`+
450 451 '\nProceeding with internal defaults.')
451 452
452 453 #------------------------------------------------------------------------
453 454 # Set exception handlers in mode requested by user.
454 455 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
455 456 IP.magic_xmode(opts_all.xmode)
456 457 otrap.release_out()
457 458
458 459 #------------------------------------------------------------------------
459 460 # Execute user config
460 461
461 462 # Create a valid config structure with the right precedence order:
462 463 # defaults < rcfile < command line. This needs to be in the instance, so
463 464 # that method calls below that rely on it find it.
464 465 IP.rc = rc_def.copy()
465 466
466 467 # Work with a local alias inside this routine to avoid unnecessary
467 468 # attribute lookups.
468 469 IP_rc = IP.rc
469 470
470 471 IP_rc.update(opts_def)
471 472 if rcfiledata:
472 473 # now we can update
473 474 IP_rc.update(rcfiledata)
474 475 IP_rc.update(opts)
475 476 IP_rc.update(rc_override)
476 477
477 478 # Store the original cmd line for reference:
478 479 IP_rc.opts = opts
479 480 IP_rc.args = args
480 481
481 482 # create a *runtime* Struct like rc for holding parameters which may be
482 483 # created and/or modified by runtime user extensions.
483 484 IP.runtime_rc = Struct()
484 485
485 486 # from this point on, all config should be handled through IP_rc,
486 487 # opts* shouldn't be used anymore.
487 488
488 489
489 490 # update IP_rc with some special things that need manual
490 491 # tweaks. Basically options which affect other options. I guess this
491 492 # should just be written so that options are fully orthogonal and we
492 493 # wouldn't worry about this stuff!
493 494
494 495 if IP_rc.classic:
495 496 IP_rc.quick = 1
496 497 IP_rc.cache_size = 0
497 498 IP_rc.pprint = 0
498 499 IP_rc.prompt_in1 = '>>> '
499 500 IP_rc.prompt_in2 = '... '
500 501 IP_rc.prompt_out = ''
501 502 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
502 503 IP_rc.colors = 'NoColor'
503 504 IP_rc.xmode = 'Plain'
504 505
505 506 IP.pre_config_initialization()
506 507 # configure readline
507 508 # Define the history file for saving commands in between sessions
508 509 if IP_rc.profile:
509 510 histfname = 'history-%s' % IP_rc.profile
510 511 else:
511 512 histfname = 'history'
512 513 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
513 514
514 515 # update exception handlers with rc file status
515 516 otrap.trap_out() # I don't want these messages ever.
516 517 IP.magic_xmode(IP_rc.xmode)
517 518 otrap.release_out()
518 519
519 520 # activate logging if requested and not reloading a log
520 521 if IP_rc.logplay:
521 522 IP.magic_logstart(IP_rc.logplay + ' append')
522 523 elif IP_rc.logfile:
523 524 IP.magic_logstart(IP_rc.logfile)
524 525 elif IP_rc.log:
525 526 IP.magic_logstart()
526 527
527 528 # find user editor so that it we don't have to look it up constantly
528 529 if IP_rc.editor.strip()=='0':
529 530 try:
530 531 ed = os.environ['EDITOR']
531 532 except KeyError:
532 533 if os.name == 'posix':
533 534 ed = 'vi' # the only one guaranteed to be there!
534 535 else:
535 536 ed = 'notepad' # same in Windows!
536 537 IP_rc.editor = ed
537 538
538 539 # Keep track of whether this is an embedded instance or not (useful for
539 540 # post-mortems).
540 541 IP_rc.embedded = IP.embedded
541 542
542 543 # Recursive reload
543 544 try:
544 545 from IPython import deep_reload
545 546 if IP_rc.deep_reload:
546 547 __builtin__.reload = deep_reload.reload
547 548 else:
548 549 __builtin__.dreload = deep_reload.reload
549 550 del deep_reload
550 551 except ImportError:
551 552 pass
552 553
553 554 # Save the current state of our namespace so that the interactive shell
554 555 # can later know which variables have been created by us from config files
555 556 # and loading. This way, loading a file (in any way) is treated just like
556 557 # defining things on the command line, and %who works as expected.
557 558
558 559 # DON'T do anything that affects the namespace beyond this point!
559 560 IP.internal_ns.update(__main__.__dict__)
560 561
561 562 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
562 563
563 564 # Now run through the different sections of the users's config
564 565 if IP_rc.debug:
565 566 print 'Trying to execute the following configuration structure:'
566 567 print '(Things listed first are deeper in the inclusion tree and get'
567 568 print 'loaded first).\n'
568 569 pprint(IP_rc.__dict__)
569 570
570 571 for mod in IP_rc.import_mod:
571 572 try:
572 573 exec 'import '+mod in IP.user_ns
573 574 except :
574 575 IP.InteractiveTB()
575 576 import_fail_info(mod)
576 577
577 578 for mod_fn in IP_rc.import_some:
578 579 if mod_fn == []: break
579 580 mod,fn = mod_fn[0],','.join(mod_fn[1:])
580 581 try:
581 582 exec 'from '+mod+' import '+fn in IP.user_ns
582 583 except :
583 584 IP.InteractiveTB()
584 585 import_fail_info(mod,fn)
585 586
586 587 for mod in IP_rc.import_all:
587 588 try:
588 589 exec 'from '+mod+' import *' in IP.user_ns
589 590 except :
590 591 IP.InteractiveTB()
591 592 import_fail_info(mod)
592 593
593 594 for code in IP_rc.execute:
594 595 try:
595 596 exec code in IP.user_ns
596 597 except:
597 598 IP.InteractiveTB()
598 599 warn('Failure executing code: ' + `code`)
599 600
600 601 # Execute the files the user wants in ipythonrc
601 602 for file in IP_rc.execfile:
602 603 try:
603 604 file = filefind(file,sys.path+[IPython_dir])
604 605 except IOError:
605 606 warn(itpl('File $file not found. Skipping it.'))
606 607 else:
607 608 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
608 609
609 610 # finally, try importing ipy_*_conf for final configuration
610 611 try:
611 612 import ipy_system_conf
612 613 except ImportError:
613 614 if opts_all.debug: IP.InteractiveTB()
614 615 warn("Could not import 'ipy_system_conf'")
615 616 except:
616 617 IP.InteractiveTB()
617 618 import_fail_info('ipy_system_conf')
618 619
619 620 if opts_all.profile:
620 621 profmodname = 'ipy_profile_' + opts_all.profile
621 622 try:
622 623 __import__(profmodname)
623 624 except ImportError:
624 625 # only warn if ipythonrc-PROFNAME didn't exist
625 626 if opts.profile =='':
626 627 warn("Could not start with profile '%s'!\n"
627 628 "('%s/%s.py' does not exist? run '%%upgrade')" %
628 629 (opts_all.profile, opts_all.ipythondir, profmodname) )
629 630 except:
630 631 print "Error importing",profmodname
631 632 IP.InteractiveTB()
632 633 import_fail_info(profmodname)
633 634
634 635 try:
635 636 import ipy_user_conf
636 637 except ImportError:
637 638 if opts_all.debug: IP.InteractiveTB()
638 639 warn("Could not import user config!\n "
639 640 "('%s/ipy_user_conf.py' does not exist? Please run '%%upgrade')\n"
640 641 % opts_all.ipythondir)
641 642 except:
642 643 print "Error importing ipy_user_conf"
643 644 IP.InteractiveTB()
644 645 import_fail_info("ipy_user_conf")
645 646
646 647 # release stdout and stderr and save config log into a global summary
647 648 msg.config.release_all()
648 649 if IP_rc.messages:
649 650 msg.summary += msg.config.summary_all()
650 651
651 652 #------------------------------------------------------------------------
652 653 # Setup interactive session
653 654
654 655 # Now we should be fully configured. We can then execute files or load
655 656 # things only needed for interactive use. Then we'll open the shell.
656 657
657 658 # Take a snapshot of the user namespace before opening the shell. That way
658 659 # we'll be able to identify which things were interactively defined and
659 660 # which were defined through config files.
660 661 IP.user_config_ns = IP.user_ns.copy()
661 662
662 663 # Force reading a file as if it were a session log. Slower but safer.
663 664 if load_logplay:
664 665 print 'Replaying log...'
665 666 try:
666 667 if IP_rc.debug:
667 668 logplay_quiet = 0
668 669 else:
669 670 logplay_quiet = 1
670 671
671 672 msg.logplay.trap_all()
672 673 IP.safe_execfile(load_logplay,IP.user_ns,
673 674 islog = 1, quiet = logplay_quiet)
674 675 msg.logplay.release_all()
675 676 if IP_rc.messages:
676 677 msg.summary += msg.logplay.summary_all()
677 678 except:
678 679 warn('Problems replaying logfile %s.' % load_logplay)
679 680 IP.InteractiveTB()
680 681
681 682 # Load remaining files in command line
682 683 msg.user_exec.trap_all()
683 684
684 685 # Do NOT execute files named in the command line as scripts to be loaded
685 686 # by embedded instances. Doing so has the potential for an infinite
686 687 # recursion if there are exceptions thrown in the process.
687 688
688 689 # XXX FIXME: the execution of user files should be moved out to after
689 690 # ipython is fully initialized, just as if they were run via %run at the
690 691 # ipython prompt. This would also give them the benefit of ipython's
691 692 # nice tracebacks.
692 693
693 694 if (not embedded and IP_rc.args and
694 695 not IP_rc.args[0].lower().endswith('.ipy')):
695 696 name_save = IP.user_ns['__name__']
696 697 IP.user_ns['__name__'] = '__main__'
697 698 # Set our own excepthook in case the user code tries to call it
698 699 # directly. This prevents triggering the IPython crash handler.
699 700 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
700 701
701 702 save_argv = sys.argv[1:] # save it for later restoring
702 703
703 704 sys.argv = args
704 705
705 706 try:
706 707 IP.safe_execfile(args[0], IP.user_ns)
707 708 finally:
708 709 # Reset our crash handler in place
709 710 sys.excepthook = old_excepthook
710 711 sys.argv[:] = save_argv
711 712 IP.user_ns['__name__'] = name_save
712 713
713 714 msg.user_exec.release_all()
714 715
715 716 if IP_rc.messages:
716 717 msg.summary += msg.user_exec.summary_all()
717 718
718 719 # since we can't specify a null string on the cmd line, 0 is the equivalent:
719 720 if IP_rc.nosep:
720 721 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
721 722 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
722 723 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
723 724 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
724 725 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
725 726 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
726 727 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
727 728
728 729 # Determine how many lines at the bottom of the screen are needed for
729 730 # showing prompts, so we can know wheter long strings are to be printed or
730 731 # paged:
731 732 num_lines_bot = IP_rc.separate_in.count('\n')+1
732 733 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
733 734
734 735 # configure startup banner
735 736 if IP_rc.c: # regular python doesn't print the banner with -c
736 737 IP_rc.banner = 0
737 738 if IP_rc.banner:
738 739 BANN_P = IP.BANNER_PARTS
739 740 else:
740 741 BANN_P = []
741 742
742 743 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
743 744
744 745 # add message log (possibly empty)
745 746 if msg.summary: BANN_P.append(msg.summary)
746 747 # Final banner is a string
747 748 IP.BANNER = '\n'.join(BANN_P)
748 749
749 750 # Finalize the IPython instance. This assumes the rc structure is fully
750 751 # in place.
751 752 IP.post_config_initialization()
752 753
753 754 return IP
754 755 #************************ end of file <ipmaker.py> **************************
@@ -1,305 +1,314 b''
1 1 #!/usr/bin/env python
2 2 """Module for interactively running scripts.
3 3
4 4 This module implements classes for interactively running scripts written for
5 5 any system with a prompt which can be matched by a regexp suitable for
6 6 pexpect. It can be used to run as if they had been typed up interactively, an
7 7 arbitrary series of commands for the target system.
8 8
9 9 The module includes classes ready for IPython (with the default prompts),
10 10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
11 11 simply run the module as a script:
12 12
13 13 ./irunner.py --help
14 14
15 15
16 16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
17 17 contributed on the ipython-user list:
18 18
19 19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
20 20
21 21
22 22 NOTES:
23 23
24 24 - This module requires pexpect, available in most linux distros, or which can
25 25 be downloaded from
26 26
27 27 http://pexpect.sourceforge.net
28 28
29 29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
30 30 limitations. This means that it will NOT work under native windows Python.
31 31 """
32 32
33 33 # Stdlib imports
34 34 import optparse
35 35 import os
36 36 import sys
37 37
38 38 # Third-party modules.
39 39 import pexpect
40 40
41 41 # Global usage strings, to avoid indentation issues when typing it below.
42 42 USAGE = """
43 43 Interactive script runner, type: %s
44 44
45 45 runner [opts] script_name
46 46 """
47 47
48 48 # The generic runner class
49 49 class InteractiveRunner(object):
50 50 """Class to run a sequence of commands through an interactive program."""
51 51
52 52 def __init__(self,program,prompts,args=None):
53 53 """Construct a runner.
54 54
55 55 Inputs:
56 56
57 57 - program: command to execute the given program.
58 58
59 59 - prompts: a list of patterns to match as valid prompts, in the
60 60 format used by pexpect. This basically means that it can be either
61 61 a string (to be compiled as a regular expression) or a list of such
62 62 (it must be a true list, as pexpect does type checks).
63 63
64 64 If more than one prompt is given, the first is treated as the main
65 65 program prompt and the others as 'continuation' prompts, like
66 66 python's. This means that blank lines in the input source are
67 67 ommitted when the first prompt is matched, but are NOT ommitted when
68 68 the continuation one matches, since this is how python signals the
69 69 end of multiline input interactively.
70 70
71 71 Optional inputs:
72 72
73 73 - args(None): optional list of strings to pass as arguments to the
74 74 child program.
75 75
76 76 Public members not parameterized in the constructor:
77 77
78 78 - delaybeforesend(0): Newer versions of pexpect have a delay before
79 79 sending each new input. For our purposes here, it's typically best
80 80 to just set this to zero, but if you encounter reliability problems
81 81 or want an interactive run to pause briefly at each prompt, just
82 82 increase this value (it is measured in seconds). Note that this
83 83 variable is not honored at all by older versions of pexpect.
84 84 """
85 85
86 86 self.program = program
87 87 self.prompts = prompts
88 88 if args is None: args = []
89 89 self.args = args
90 90 # Other public members which we don't make as parameters, but which
91 91 # users may occasionally want to tweak
92 92 self.delaybeforesend = 0
93 93
94 94 def run_file(self,fname,interact=False):
95 95 """Run the given file interactively.
96 96
97 97 Inputs:
98 98
99 99 -fname: name of the file to execute.
100 100
101 101 See the run_source docstring for the meaning of the optional
102 102 arguments."""
103 103
104 104 fobj = open(fname,'r')
105 105 try:
106 106 self.run_source(fobj,interact)
107 107 finally:
108 108 fobj.close()
109 109
110 110 def run_source(self,source,interact=False):
111 111 """Run the given source code interactively.
112 112
113 113 Inputs:
114 114
115 115 - source: a string of code to be executed, or an open file object we
116 116 can iterate over.
117 117
118 118 Optional inputs:
119 119
120 120 - interact(False): if true, start to interact with the running
121 121 program at the end of the script. Otherwise, just exit.
122 122 """
123 123
124 124 # if the source is a string, chop it up in lines so we can iterate
125 125 # over it just as if it were an open file.
126 126 if not isinstance(source,file):
127 127 source = source.splitlines(True)
128 128
129 129 # grab the true write method of stdout, in case anything later
130 130 # reassigns sys.stdout, so that we really are writing to the true
131 131 # stdout and not to something else. We also normalize all strings we
132 132 # write to use the native OS line separators.
133 133 linesep = os.linesep
134 134 stdwrite = sys.stdout.write
135 135 write = lambda s: stdwrite(s.replace('\r\n',linesep))
136 136
137 137 c = pexpect.spawn(self.program,self.args,timeout=None)
138 138 c.delaybeforesend = self.delaybeforesend
139 139
140 140 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
141 141 # This causes problems because any line longer than 80 characters gets
142 142 # completely overwrapped on the printed outptut (even though
143 143 # internally the code runs fine). We reset this to 99 rows X 200
144 144 # columns (arbitrarily chosen), which should avoid problems in all
145 145 # reasonable cases.
146 146 c.setwinsize(99,200)
147 147
148 148 prompts = c.compile_pattern_list(self.prompts)
149 149
150 150 prompt_idx = c.expect_list(prompts)
151 151 # Flag whether the script ends normally or not, to know whether we can
152 152 # do anything further with the underlying process.
153 153 end_normal = True
154 154 for cmd in source:
155 155 # skip blank lines for all matches to the 'main' prompt, while the
156 156 # secondary prompts do not
157 157 if prompt_idx==0 and \
158 158 (cmd.isspace() or cmd.lstrip().startswith('#')):
159 159 print cmd,
160 160 continue
161 161
162 162 write(c.after)
163 163 c.send(cmd)
164 164 try:
165 165 prompt_idx = c.expect_list(prompts)
166 166 except pexpect.EOF:
167 167 # this will happen if the child dies unexpectedly
168 168 write(c.before)
169 169 end_normal = False
170 170 break
171 171 write(c.before)
172 172
173 173 if end_normal:
174 174 if interact:
175 175 c.send('\n')
176 176 print '<< Starting interactive mode >>',
177 177 try:
178 178 c.interact()
179 179 except OSError:
180 180 # This is what fires when the child stops. Simply print a
181 181 # newline so the system prompt is aligned. The extra
182 182 # space is there to make sure it gets printed, otherwise
183 183 # OS buffering sometimes just suppresses it.
184 184 write(' \n')
185 185 sys.stdout.flush()
186 186 else:
187 187 c.close()
188 188 else:
189 189 if interact:
190 190 e="Further interaction is not possible: child process is dead."
191 191 print >> sys.stderr, e
192 192
193 193 def main(self,argv=None):
194 194 """Run as a command-line script."""
195 195
196 196 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
197 197 newopt = parser.add_option
198 198 newopt('-i','--interact',action='store_true',default=False,
199 199 help='Interact with the program after the script is run.')
200 200
201 201 opts,args = parser.parse_args(argv)
202 202
203 203 if len(args) != 1:
204 204 print >> sys.stderr,"You must supply exactly one file to run."
205 205 sys.exit(1)
206 206
207 207 self.run_file(args[0],opts.interact)
208 208
209 209
210 210 # Specific runners for particular programs
211 211 class IPythonRunner(InteractiveRunner):
212 212 """Interactive IPython runner.
213 213
214 214 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
215 215 avoid having to write a regexp that matches ANSI sequences, though pexpect
216 216 does support them. If anyone contributes patches for ANSI color support,
217 217 they will be welcome.
218 218
219 219 It also sets the prompts manually, since the prompt regexps for
220 220 pexpect need to be matched to the actual prompts, so user-customized
221 221 prompts would break this.
222 222 """
223 223
224 224 def __init__(self,program = 'ipython',args=None):
225 225 """New runner, optionally passing the ipython command to use."""
226 226
227 227 args0 = ['-colors','NoColor',
228 228 '-pi1','In [\\#]: ',
229 229 '-pi2',' .\\D.: ']
230 230 if args is None: args = args0
231 231 else: args = args0 + args
232 232 prompts = [r'In \[\d+\]: ',r' \.*: ']
233 233 InteractiveRunner.__init__(self,program,prompts,args)
234 234
235 235
236 236 class PythonRunner(InteractiveRunner):
237 237 """Interactive Python runner."""
238 238
239 239 def __init__(self,program='python',args=None):
240 240 """New runner, optionally passing the python command to use."""
241 241
242 242 prompts = [r'>>> ',r'\.\.\. ']
243 243 InteractiveRunner.__init__(self,program,prompts,args)
244 244
245 245
246 246 class SAGERunner(InteractiveRunner):
247 247 """Interactive SAGE runner.
248 248
249 249 WARNING: this runner only works if you manually configure your SAGE copy
250 250 to use 'colors NoColor' in the ipythonrc config file, since currently the
251 251 prompt matching regexp does not identify color sequences."""
252 252
253 253 def __init__(self,program='sage',args=None):
254 254 """New runner, optionally passing the sage command to use."""
255 255
256 256 prompts = ['sage: ',r'\s*\.\.\. ']
257 257 InteractiveRunner.__init__(self,program,prompts,args)
258 258
259 259 # Global usage string, to avoid indentation issues if typed in a function def.
260 260 MAIN_USAGE = """
261 261 %prog [options] file_to_run
262 262
263 263 This is an interface to the various interactive runners available in this
264 264 module. If you want to pass specific options to one of the runners, you need
265 265 to first terminate the main options with a '--', and then provide the runner's
266 266 options. For example:
267 267
268 268 irunner.py --python -- --help
269 269
270 270 will pass --help to the python runner. Similarly,
271 271
272 272 irunner.py --ipython -- --interact script.ipy
273 273
274 274 will run the script.ipy file under the IPython runner, and then will start to
275 275 interact with IPython at the end of the script (instead of exiting).
276 276
277 277 The already implemented runners are listed below; adding one for a new program
278 278 is a trivial task, see the source for examples.
279 279
280 280 WARNING: the SAGE runner only works if you manually configure your SAGE copy
281 281 to use 'colors NoColor' in the ipythonrc config file, since currently the
282 282 prompt matching regexp does not identify color sequences.
283 283 """
284 284
285 285 def main():
286 286 """Run as a command-line script."""
287 287
288 288 parser = optparse.OptionParser(usage=MAIN_USAGE)
289 289 newopt = parser.add_option
290 290 parser.set_defaults(mode='ipython')
291 291 newopt('--ipython',action='store_const',dest='mode',const='ipython',
292 292 help='IPython interactive runner (default).')
293 293 newopt('--python',action='store_const',dest='mode',const='python',
294 294 help='Python interactive runner.')
295 295 newopt('--sage',action='store_const',dest='mode',const='sage',
296 296 help='SAGE interactive runner.')
297 297
298 298 opts,args = parser.parse_args()
299 299 runners = dict(ipython=IPythonRunner,
300 300 python=PythonRunner,
301 301 sage=SAGERunner)
302 runners[opts.mode]().main(args)
302
303 try:
304 ext = os.path.splitext(args[0])
305 except IndexError:
306 ext = ''
307 modes = {'.ipy':'ipython',
308 '.py':'python',
309 '.sage':'sage'}
310 mode = modes.get(ext,opts.mode)
311 runners[mode]().main(args)
303 312
304 313 if __name__ == '__main__':
305 314 main()
@@ -1,5910 +1,5923 b''
1 2006-11-03 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * IPython/iplib.py (InteractiveShell.ipconfig): new builtin, also
4 visible in ipapi as ip.config(), to programatically control the
5 internal rc object. There's an accompanying %config magic for
6 interactive use, which has been enhanced to match the
7 funtionality in ipconfig.
8
9 * IPython/Magic.py (magic_system_verbose): Change %system_verbose
10 so it's not just a toggle, it now takes an argument. Add support
11 for a customizable header when making system calls, as the new
12 system_header variable in the ipythonrc file.
13
1 14 2006-11-03 Walter Doerwald <walter@livinglogic.de>
2 15
3 16 * IPython/Extensions/ipipe.py: xrepr(), xiter() and xattrs() are now
4 17 generic functions (using Philip J. Eby's simplegeneric package).
5 18 This makes it possible to customize the display of third-party classes
6 19 without having to monkeypatch them. xiter() no longer supports a mode
7 20 argument and the XMode class has been removed. The same functionality can
8 21 be implemented via IterAttributeDescriptor and IterMethodDescriptor.
9 22 One consequence of the switch to generic functions is that xrepr() and
10 23 xattrs() implementation must define the default value for the mode
11 24 argument themselves and xattrs() implementations must return real
12 25 descriptors.
13 26
14 27 * IPython/external: This new subpackage will contain all third-party
15 28 packages that are bundled with IPython. (The first one is simplegeneric).
16 29
17 30 * IPython/Extensions/ipipe.py (ifile/ils): Readd output of the parent
18 31 directory which as been dropped in r1703.
19 32
20 33 * IPython/Extensions/ipipe.py (iless): Fixed.
21 34
22 35 * IPython/Extensions/ibrowse: Fixed sorting under Python 2.3.
23 36
24 37 2006-11-03 Fernando Perez <Fernando.Perez@colorado.edu>
25 38
26 39 * IPython/iplib.py (InteractiveShell.var_expand): fix stack
27 40 handling in variable expansion so that shells and magics recognize
28 41 function local scopes correctly. Bug reported by Brian.
29 42
30 43 * scripts/ipython: remove the very first entry in sys.path which
31 44 Python auto-inserts for scripts, so that sys.path under IPython is
32 45 as similar as possible to that under plain Python.
33 46
34 47 * IPython/completer.py (IPCompleter.file_matches): Fix
35 48 tab-completion so that quotes are not closed unless the completion
36 49 is unambiguous. After a request by Stefan. Minor cleanups in
37 50 ipy_stock_completers.
38 51
39 52 2006-11-02 Ville Vainio <vivainio@gmail.com>
40 53
41 54 * ipy_stock_completers.py: Add %run and %cd completers.
42 55
43 56 * completer.py: Try running custom completer for both
44 57 "foo" and "%foo" if the command is just "foo". Ignore case
45 58 when filtering possible completions.
46 59
47 60 * UserConfig/ipy_user_conf.py: install stock completers as default
48 61
49 62 * iplib.py (history_saving_wrapper), debugger(), ipy_pydb.py:
50 63 simplified readline history save / restore through a wrapper
51 64 function
52 65
53 66
54 67 2006-10-31 Ville Vainio <vivainio@gmail.com>
55 68
56 69 * strdispatch.py, completer.py, ipy_stock_completers.py:
57 70 Allow str_key ("command") in completer hooks. Implement
58 71 trivial completer for 'import' (stdlib modules only). Rename
59 72 ipy_linux_package_managers.py to ipy_stock_completers.py.
60 73 SVN completer.
61 74
62 75 * Extensions/ledit.py: %magic line editor for easily and
63 76 incrementally manipulating lists of strings. The magic command
64 77 name is %led.
65 78
66 79 2006-10-30 Ville Vainio <vivainio@gmail.com>
67 80
68 81 * Debugger.py, iplib.py (debugger()): Add last set of Rocky
69 82 Bernsteins's patches for pydb integration.
70 83 http://bashdb.sourceforge.net/pydb/
71 84
72 85 * strdispatch.py, iplib.py, completer.py, IPython/__init__.py,
73 86 Extensions/ipy_linux_package_managers.py, hooks.py: Implement
74 87 custom completer hook to allow the users to implement their own
75 88 completers. See ipy_linux_package_managers.py for example. The
76 89 hook name is 'complete_command'.
77 90
78 91 2006-10-28 Fernando Perez <Fernando.Perez@colorado.edu>
79 92
80 93 * IPython/UserConfig/ipythonrc-scipy: minor cleanups to remove old
81 94 Numeric leftovers.
82 95
83 96 * ipython.el (py-execute-region): apply Stefan's patch to fix
84 97 garbled results if the python shell hasn't been previously started.
85 98
86 99 * IPython/genutils.py (arg_split): moved to genutils, since it's a
87 100 pretty generic function and useful for other things.
88 101
89 102 * IPython/OInspect.py (getsource): Add customizable source
90 103 extractor. After a request/patch form W. Stein (SAGE).
91 104
92 105 * IPython/irunner.py (InteractiveRunner.run_source): reset tty
93 106 window size to a more reasonable value from what pexpect does,
94 107 since their choice causes wrapping bugs with long input lines.
95 108
96 109 2006-10-28 Ville Vainio <vivainio@gmail.com>
97 110
98 111 * Magic.py (%run): Save and restore the readline history from
99 112 file around %run commands to prevent side effects from
100 113 %runned programs that might use readline (e.g. pydb).
101 114
102 115 * extensions/ipy_pydb.py: Adds %pydb magic when imported, for
103 116 invoking the pydb enhanced debugger.
104 117
105 118 2006-10-23 Walter Doerwald <walter@livinglogic.de>
106 119
107 120 * IPython/Extensions/ipipe.py (ifile): Remove all methods that
108 121 call the base class method and propagate the return value to
109 122 ifile. This is now done by path itself.
110 123
111 124 2006-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
112 125
113 126 * IPython/ipapi.py (IPApi.__init__): Added new entry to public
114 127 api: set_crash_handler(), to expose the ability to change the
115 128 internal crash handler.
116 129
117 130 * IPython/CrashHandler.py (CrashHandler.__init__): abstract out
118 131 the various parameters of the crash handler so that apps using
119 132 IPython as their engine can customize crash handling. Ipmlemented
120 133 at the request of SAGE.
121 134
122 135 2006-10-14 Ville Vainio <vivainio@gmail.com>
123 136
124 137 * Magic.py, ipython.el: applied first "safe" part of Rocky
125 138 Bernstein's patch set for pydb integration.
126 139
127 140 * Magic.py (%unalias, %alias): %store'd aliases can now be
128 141 removed with '%unalias'. %alias w/o args now shows most
129 142 interesting (stored / manually defined) aliases last
130 143 where they catch the eye w/o scrolling.
131 144
132 145 * Magic.py (%rehashx), ext_rehashdir.py: files with
133 146 'py' extension are always considered executable, even
134 147 when not in PATHEXT environment variable.
135 148
136 149 2006-10-12 Ville Vainio <vivainio@gmail.com>
137 150
138 151 * jobctrl.py: Add new "jobctrl" extension for spawning background
139 152 processes with "&find /". 'import jobctrl' to try it out. Requires
140 153 'subprocess' module, standard in python 2.4+.
141 154
142 155 * iplib.py (expand_aliases, handle_alias): Aliases expand transitively,
143 156 so if foo -> bar and bar -> baz, then foo -> baz.
144 157
145 158 2006-10-09 Fernando Perez <Fernando.Perez@colorado.edu>
146 159
147 160 * IPython/Magic.py (Magic.parse_options): add a new posix option
148 161 to allow parsing of input args in magics that doesn't strip quotes
149 162 (if posix=False). This also closes %timeit bug reported by
150 163 Stefan.
151 164
152 165 2006-10-03 Ville Vainio <vivainio@gmail.com>
153 166
154 167 * iplib.py (raw_input, interact): Return ValueError catching for
155 168 raw_input. Fixes infinite loop for sys.stdin.close() or
156 169 sys.stdout.close().
157 170
158 171 2006-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
159 172
160 173 * IPython/irunner.py (InteractiveRunner.run_source): small fixes
161 174 to help in handling doctests. irunner is now pretty useful for
162 175 running standalone scripts and simulate a full interactive session
163 176 in a format that can be then pasted as a doctest.
164 177
165 178 * IPython/iplib.py (InteractiveShell.__init__): Install exit/quit
166 179 on top of the default (useless) ones. This also fixes the nasty
167 180 way in which 2.5's Quitter() exits (reverted [1785]).
168 181
169 182 * IPython/Debugger.py (Pdb.__init__): Fix ipdb to work with python
170 183 2.5.
171 184
172 185 * IPython/ultraTB.py (TBTools.set_colors): Make sure that ipdb
173 186 color scheme is updated as well when color scheme is changed
174 187 interactively.
175 188
176 189 2006-09-27 Ville Vainio <vivainio@gmail.com>
177 190
178 191 * iplib.py (raw_input): python 2.5 closes stdin on quit -> avoid
179 192 infinite loop and just exit. It's a hack, but will do for a while.
180 193
181 194 2006-08-25 Walter Doerwald <walter@livinglogic.de>
182 195
183 196 * IPython/Extensions/ipipe.py (ils): Add arguments dirs and files to
184 197 the constructor, this makes it possible to get a list of only directories
185 198 or only files.
186 199
187 200 2006-08-12 Ville Vainio <vivainio@gmail.com>
188 201
189 202 * Fakemodule.py, OInspect.py: Reverted 2006-08-11 mods,
190 203 they broke unittest
191 204
192 205 2006-08-11 Ville Vainio <vivainio@gmail.com>
193 206
194 207 * Fakemodule.py, OInspect.py: remove 2006-08-09 monkepatch
195 208 by resolving issue properly, i.e. by inheriting FakeModule
196 209 from types.ModuleType. Pickling ipython interactive data
197 210 should still work as usual (testing appreciated).
198 211
199 212 2006-08-09 Fernando Perez <Fernando.Perez@colorado.edu>
200 213
201 214 * IPython/OInspect.py: monkeypatch inspect from the stdlib if
202 215 running under python 2.3 with code from 2.4 to fix a bug with
203 216 help(). Reported by the Debian maintainers, Norbert Tretkowski
204 217 <norbert-AT-tretkowski.de> and Alexandre Fayolle
205 218 <afayolle-AT-debian.org>.
206 219
207 220 2006-08-04 Walter Doerwald <walter@livinglogic.de>
208 221
209 222 * IPython/Extensions/ibrowse.py: Fixed the help message in the footer
210 223 (which was displaying "quit" twice).
211 224
212 225 2006-07-28 Walter Doerwald <walter@livinglogic.de>
213 226
214 227 * IPython/Extensions/ipipe.py: Fix isort.__iter__() (was still using
215 228 the mode argument).
216 229
217 230 2006-07-27 Walter Doerwald <walter@livinglogic.de>
218 231
219 232 * IPython/Extensions/ipipe.py: Fix getglobals() if we're
220 233 not running under IPython.
221 234
222 235 * IPython/Extensions/ipipe.py: Rename XAttr to AttributeDetail
223 236 and make it iterable (iterating over the attribute itself). Add two new
224 237 magic strings for __xattrs__(): If the string starts with "-", the attribute
225 238 will not be displayed in ibrowse's detail view (but it can still be
226 239 iterated over). This makes it possible to add attributes that are large
227 240 lists or generator methods to the detail view. Replace magic attribute names
228 241 and _attrname() and _getattr() with "descriptors": For each type of magic
229 242 attribute name there's a subclass of Descriptor: None -> SelfDescriptor();
230 243 "foo" -> AttributeDescriptor("foo"); "foo()" -> MethodDescriptor("foo");
231 244 "-foo" -> IterAttributeDescriptor("foo"); "-foo()" -> IterMethodDescriptor("foo");
232 245 foo() -> FunctionDescriptor(foo). Magic strings returned from __xattrs__()
233 246 are still supported.
234 247
235 248 * IPython/Extensions/ibrowse.py: If fetching the next row from the input
236 249 fails in ibrowse.fetch(), the exception object is added as the last item
237 250 and item fetching is canceled. This prevents ibrowse from aborting if e.g.
238 251 a generator throws an exception midway through execution.
239 252
240 253 * IPython/Extensions/ipipe.py: Turn ifile's properties mimetype and
241 254 encoding into methods.
242 255
243 256 2006-07-26 Ville Vainio <vivainio@gmail.com>
244 257
245 258 * iplib.py: history now stores multiline input as single
246 259 history entries. Patch by Jorgen Cederlof.
247 260
248 261 2006-07-18 Walter Doerwald <walter@livinglogic.de>
249 262
250 263 * IPython/Extensions/ibrowse.py: Make cursor visible over
251 264 non existing attributes.
252 265
253 266 2006-07-14 Walter Doerwald <walter@livinglogic.de>
254 267
255 268 * IPython/Extensions/ipipe.py (ix): Use os.popen4() so that the
256 269 error output of the running command doesn't mess up the screen.
257 270
258 271 2006-07-13 Walter Doerwald <walter@livinglogic.de>
259 272
260 273 * IPython/Extensions/ipipe.py (isort): Make isort usable without
261 274 argument. This sorts the items themselves.
262 275
263 276 2006-07-12 Walter Doerwald <walter@livinglogic.de>
264 277
265 278 * IPython/Extensions/ipipe.py (eval, ifilter, isort, ieval):
266 279 Compile expression strings into code objects. This should speed
267 280 up ifilter and friends somewhat.
268 281
269 282 2006-07-08 Ville Vainio <vivainio@gmail.com>
270 283
271 284 * Magic.py: %cpaste now strips > from the beginning of lines
272 285 to ease pasting quoted code from emails. Contributed by
273 286 Stefan van der Walt.
274 287
275 288 2006-06-29 Ville Vainio <vivainio@gmail.com>
276 289
277 290 * ipmaker.py, Shell.py: qt4agg matplotlib backend support for pylab
278 291 mode, patch contributed by Darren Dale. NEEDS TESTING!
279 292
280 293 2006-06-28 Walter Doerwald <walter@livinglogic.de>
281 294
282 295 * IPython/Extensions/ibrowse.py: Give the ibrowse cursor row
283 296 a blue background. Fix fetching new display rows when the browser
284 297 scrolls more than a screenful (e.g. by using the goto command).
285 298
286 299 2006-06-27 Ville Vainio <vivainio@gmail.com>
287 300
288 301 * Magic.py (_inspect, _ofind) Apply David Huard's
289 302 patch for displaying the correct docstring for 'property'
290 303 attributes.
291 304
292 305 2006-06-23 Walter Doerwald <walter@livinglogic.de>
293 306
294 307 * IPython/Extensions/ibrowse.py: Put the documentation of the keyboard
295 308 commands into the methods implementing them.
296 309
297 310 2006-06-22 Fernando Perez <Fernando.Perez@colorado.edu>
298 311
299 312 * ipython.el (ipython-indentation-hook): cleanup patch, submitted
300 313 by Kov Chai <tchaikov-AT-gmail.com>. He notes that the original
301 314 autoindent support was authored by Jin Liu.
302 315
303 316 2006-06-22 Walter Doerwald <walter@livinglogic.de>
304 317
305 318 * IPython/Extensions/ibrowse.py: Replace the plain dictionaries used
306 319 for keymaps with a custom class that simplifies handling.
307 320
308 321 2006-06-19 Walter Doerwald <walter@livinglogic.de>
309 322
310 323 * IPython/Extensions/ibrowse.py: ibrowse now properly handles terminal
311 324 resizing. This requires Python 2.5 to work.
312 325
313 326 2006-06-16 Walter Doerwald <walter@livinglogic.de>
314 327
315 328 * IPython/Extensions/ibrowse.py: Add two new commands to
316 329 ibrowse: "hideattr" (mapped to "h") hides the attribute under
317 330 the cursor. "unhiderattrs" (mapped to "H") reveals all hidden
318 331 attributes again. Remapped the help command to "?". Display
319 332 keycodes in the range 0x01-0x1F as CTRL-xx. Add CTRL-a and CTRL-e
320 333 as keys for the "home" and "end" commands. Add three new commands
321 334 to the input mode for "find" and friends: "delend" (CTRL-K)
322 335 deletes to the end of line. "incsearchup" searches upwards in the
323 336 command history for an input that starts with the text before the cursor.
324 337 "incsearchdown" does the same downwards. Removed a bogus mapping of
325 338 the x key to "delete".
326 339
327 340 2006-06-15 Ville Vainio <vivainio@gmail.com>
328 341
329 342 * iplib.py, hooks.py: Added new generate_prompt hook that can be
330 343 used to create prompts dynamically, instead of the "old" way of
331 344 assigning "magic" strings to prompt_in1 and prompt_in2. The old
332 345 way still works (it's invoked by the default hook), of course.
333 346
334 347 * Prompts.py: added generate_output_prompt hook for altering output
335 348 prompt
336 349
337 350 * Release.py: Changed version string to 0.7.3.svn.
338 351
339 352 2006-06-15 Walter Doerwald <walter@livinglogic.de>
340 353
341 354 * IPython/Extensions/ibrowse.py: Change _BrowserLevel.moveto() so that
342 355 the call to fetch() always tries to fetch enough data for at least one
343 356 full screen. This makes it possible to simply call moveto(0,0,True) in
344 357 the constructor. Fix typos and removed the obsolete goto attribute.
345 358
346 359 2006-06-12 Ville Vainio <vivainio@gmail.com>
347 360
348 361 * ipy_profile_sh.py: applied Krisha Mohan Gundu's patch for
349 362 allowing $variable interpolation within multiline statements,
350 363 though so far only with "sh" profile for a testing period.
351 364 The patch also enables splitting long commands with \ but it
352 365 doesn't work properly yet.
353 366
354 367 2006-06-12 Walter Doerwald <walter@livinglogic.de>
355 368
356 369 * IPython/Extensions/ibrowse.py (_dodisplay): Display the length of the
357 370 input history and the position of the cursor in the input history for
358 371 the find, findbackwards and goto command.
359 372
360 373 2006-06-10 Walter Doerwald <walter@livinglogic.de>
361 374
362 375 * IPython/Extensions/ibrowse.py: Add a class _CommandInput that
363 376 implements the basic functionality of browser commands that require
364 377 input. Reimplement the goto, find and findbackwards commands as
365 378 subclasses of _CommandInput. Add an input history and keymaps to those
366 379 commands. Add "\r" as a keyboard shortcut for the enterdefault and
367 380 execute commands.
368 381
369 382 2006-06-07 Ville Vainio <vivainio@gmail.com>
370 383
371 384 * iplib.py: ipython mybatch.ipy exits ipython immediately after
372 385 running the batch files instead of leaving the session open.
373 386
374 387 2006-06-07 Fernando Perez <Fernando.Perez@colorado.edu>
375 388
376 389 * IPython/iplib.py (InteractiveShell.__init__): update BSD fix, as
377 390 the original fix was incomplete. Patch submitted by W. Maier.
378 391
379 392 2006-06-07 Ville Vainio <vivainio@gmail.com>
380 393
381 394 * iplib.py,Magic.py, ipmaker.py (magic_rehashx):
382 395 Confirmation prompts can be supressed by 'quiet' option.
383 396 _ip.options.quiet = 1 means "assume yes for all yes/no queries".
384 397
385 398 2006-06-06 *** Released version 0.7.2
386 399
387 400 2006-06-06 Fernando Perez <Fernando.Perez@colorado.edu>
388 401
389 402 * IPython/Release.py (version): Made 0.7.2 final for release.
390 403 Repo tagged and release cut.
391 404
392 405 2006-06-05 Ville Vainio <vivainio@gmail.com>
393 406
394 407 * Magic.py (magic_rehashx): Honor no_alias list earlier in
395 408 %rehashx, to avoid clobbering builtins in ipy_profile_sh.py
396 409
397 410 * upgrade_dir.py: try import 'path' module a bit harder
398 411 (for %upgrade)
399 412
400 413 2006-06-03 Fernando Perez <Fernando.Perez@colorado.edu>
401 414
402 415 * IPython/genutils.py (ask_yes_no): treat EOF as a default answer
403 416 instead of looping 20 times.
404 417
405 418 * IPython/ipmaker.py (make_IPython): honor -ipythondir flag
406 419 correctly at initialization time. Bug reported by Krishna Mohan
407 420 Gundu <gkmohan-AT-gmail.com> on the user list.
408 421
409 422 * IPython/Release.py (version): Mark 0.7.2 version to start
410 423 testing for release on 06/06.
411 424
412 425 2006-05-31 Fernando Perez <Fernando.Perez@colorado.edu>
413 426
414 427 * scripts/irunner: thin script interface so users don't have to
415 428 find the module and call it as an executable, since modules rarely
416 429 live in people's PATH.
417 430
418 431 * IPython/irunner.py (InteractiveRunner.__init__): added
419 432 delaybeforesend attribute to control delays with newer versions of
420 433 pexpect. Thanks to detailed help from pexpect's author, Noah
421 434 Spurrier <noah-AT-noah.org>. Noted how to use the SAGE runner
422 435 correctly (it works in NoColor mode).
423 436
424 437 * IPython/iplib.py (handle_normal): fix nasty crash reported on
425 438 SAGE list, from improper log() calls.
426 439
427 440 2006-05-31 Ville Vainio <vivainio@gmail.com>
428 441
429 442 * upgrade_dir.py, Magic.py (magic_upgrade): call upgrade_dir
430 443 with args in parens to work correctly with dirs that have spaces.
431 444
432 445 2006-05-30 Fernando Perez <Fernando.Perez@colorado.edu>
433 446
434 447 * IPython/Logger.py (Logger.logstart): add option to log raw input
435 448 instead of the processed one. A -r flag was added to the
436 449 %logstart magic used for controlling logging.
437 450
438 451 2006-05-29 Fernando Perez <Fernando.Perez@colorado.edu>
439 452
440 453 * IPython/iplib.py (InteractiveShell.__init__): add check for the
441 454 *BSDs to omit --color from all 'ls' aliases, since *BSD ls doesn't
442 455 recognize the option. After a bug report by Will Maier. This
443 456 closes #64 (will do it after confirmation from W. Maier).
444 457
445 458 * IPython/irunner.py: New module to run scripts as if manually
446 459 typed into an interactive environment, based on pexpect. After a
447 460 submission by Ken Schutte <kschutte-AT-csail.mit.edu> on the
448 461 ipython-user list. Simple unittests in the tests/ directory.
449 462
450 463 * tools/release: add Will Maier, OpenBSD port maintainer, to
451 464 recepients list. We are now officially part of the OpenBSD ports:
452 465 http://www.openbsd.org/ports.html ! Many thanks to Will for the
453 466 work.
454 467
455 468 2006-05-26 Fernando Perez <Fernando.Perez@colorado.edu>
456 469
457 470 * IPython/ipmaker.py (make_IPython): modify sys.argv fix (below)
458 471 so that it doesn't break tkinter apps.
459 472
460 473 * IPython/iplib.py (_prefilter): fix bug where aliases would
461 474 shadow variables when autocall was fully off. Reported by SAGE
462 475 author William Stein.
463 476
464 477 * IPython/OInspect.py (Inspector.__init__): add a flag to control
465 478 at what detail level strings are computed when foo? is requested.
466 479 This allows users to ask for example that the string form of an
467 480 object is only computed when foo?? is called, or even never, by
468 481 setting the object_info_string_level >= 2 in the configuration
469 482 file. This new option has been added and documented. After a
470 483 request by SAGE to be able to control the printing of very large
471 484 objects more easily.
472 485
473 486 2006-05-25 Fernando Perez <Fernando.Perez@colorado.edu>
474 487
475 488 * IPython/ipmaker.py (make_IPython): remove the ipython call path
476 489 from sys.argv, to be 100% consistent with how Python itself works
477 490 (as seen for example with python -i file.py). After a bug report
478 491 by Jeffrey Collins.
479 492
480 493 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix
481 494 nasty bug which was preventing custom namespaces with -pylab,
482 495 reported by M. Foord. Minor cleanup, remove old matplotlib.matlab
483 496 compatibility (long gone from mpl).
484 497
485 498 * IPython/ipapi.py (make_session): name change: create->make. We
486 499 use make in other places (ipmaker,...), it's shorter and easier to
487 500 type and say, etc. I'm trying to clean things before 0.7.2 so
488 501 that I can keep things stable wrt to ipapi in the chainsaw branch.
489 502
490 503 * ipython.el: fix the py-pdbtrack-input-prompt variable so that
491 504 python-mode recognizes our debugger mode. Add support for
492 505 autoindent inside (X)emacs. After a patch sent in by Jin Liu
493 506 <m.liu.jin-AT-gmail.com> originally written by
494 507 doxgen-AT-newsmth.net (with minor modifications for xemacs
495 508 compatibility)
496 509
497 510 * IPython/Debugger.py (Pdb.format_stack_entry): fix formatting of
498 511 tracebacks when walking the stack so that the stack tracking system
499 512 in emacs' python-mode can identify the frames correctly.
500 513
501 514 * IPython/ipmaker.py (make_IPython): make the internal (and
502 515 default config) autoedit_syntax value false by default. Too many
503 516 users have complained to me (both on and off-list) about problems
504 517 with this option being on by default, so I'm making it default to
505 518 off. It can still be enabled by anyone via the usual mechanisms.
506 519
507 520 * IPython/completer.py (Completer.attr_matches): add support for
508 521 PyCrust-style _getAttributeNames magic method. Patch contributed
509 522 by <mscott-AT-goldenspud.com>. Closes #50.
510 523
511 524 * IPython/iplib.py (InteractiveShell.__init__): remove the
512 525 deletion of exit/quit from __builtin__, which can break
513 526 third-party tools like the Zope debugging console. The
514 527 %exit/%quit magics remain. In general, it's probably a good idea
515 528 not to delete anything from __builtin__, since we never know what
516 529 that will break. In any case, python now (for 2.5) will support
517 530 'real' exit/quit, so this issue is moot. Closes #55.
518 531
519 532 * IPython/genutils.py (with_obj): rename the 'with' function to
520 533 'withobj' to avoid incompatibilities with Python 2.5, where 'with'
521 534 becomes a language keyword. Closes #53.
522 535
523 536 * IPython/FakeModule.py (FakeModule.__init__): add a proper
524 537 __file__ attribute to this so it fools more things into thinking
525 538 it is a real module. Closes #59.
526 539
527 540 * IPython/Magic.py (magic_edit): add -n option to open the editor
528 541 at a specific line number. After a patch by Stefan van der Walt.
529 542
530 543 2006-05-23 Fernando Perez <Fernando.Perez@colorado.edu>
531 544
532 545 * IPython/iplib.py (edit_syntax_error): fix crash when for some
533 546 reason the file could not be opened. After automatic crash
534 547 reports sent by James Graham <jgraham-AT-ast.cam.ac.uk> and
535 548 Charles Dolan <charlespatrickdolan-AT-yahoo.com>.
536 549 (_should_recompile): Don't fire editor if using %bg, since there
537 550 is no file in the first place. From the same report as above.
538 551 (raw_input): protect against faulty third-party prefilters. After
539 552 an automatic crash report sent by Dirk Laurie <dirk-AT-sun.ac.za>
540 553 while running under SAGE.
541 554
542 555 2006-05-23 Ville Vainio <vivainio@gmail.com>
543 556
544 557 * ipapi.py: Stripped down ip.to_user_ns() to work only as
545 558 ip.to_user_ns("x1 y1"), which exposes vars x1 and y1. ipapi.get()
546 559 now returns None (again), unless dummy is specifically allowed by
547 560 ipapi.get(allow_dummy=True).
548 561
549 562 2006-05-18 Fernando Perez <Fernando.Perez@colorado.edu>
550 563
551 564 * IPython: remove all 2.2-compatibility objects and hacks from
552 565 everywhere, since we only support 2.3 at this point. Docs
553 566 updated.
554 567
555 568 * IPython/ipapi.py (IPApi.__init__): Cleanup of all getters.
556 569 Anything requiring extra validation can be turned into a Python
557 570 property in the future. I used a property for the db one b/c
558 571 there was a nasty circularity problem with the initialization
559 572 order, which right now I don't have time to clean up.
560 573
561 574 * IPython/Shell.py (MTInteractiveShell.runcode): Fix, I think,
562 575 another locking bug reported by Jorgen. I'm not 100% sure though,
563 576 so more testing is needed...
564 577
565 578 2006-05-17 Fernando Perez <Fernando.Perez@colorado.edu>
566 579
567 580 * IPython/ipapi.py (IPApi.to_user_ns): New function to inject
568 581 local variables from any routine in user code (typically executed
569 582 with %run) directly into the interactive namespace. Very useful
570 583 when doing complex debugging.
571 584 (IPythonNotRunning): Changed the default None object to a dummy
572 585 whose attributes can be queried as well as called without
573 586 exploding, to ease writing code which works transparently both in
574 587 and out of ipython and uses some of this API.
575 588
576 589 2006-05-16 Fernando Perez <Fernando.Perez@colorado.edu>
577 590
578 591 * IPython/hooks.py (result_display): Fix the fact that our display
579 592 hook was using str() instead of repr(), as the default python
580 593 console does. This had gone unnoticed b/c it only happened if
581 594 %Pprint was off, but the inconsistency was there.
582 595
583 596 2006-05-15 Ville Vainio <vivainio@gmail.com>
584 597
585 598 * Oinspect.py: Only show docstring for nonexisting/binary files
586 599 when doing object??, closing ticket #62
587 600
588 601 2006-05-13 Fernando Perez <Fernando.Perez@colorado.edu>
589 602
590 603 * IPython/Shell.py (MTInteractiveShell.runsource): Fix threading
591 604 bug, closes http://www.scipy.net/roundup/ipython/issue55. A lock
592 605 was being released in a routine which hadn't checked if it had
593 606 been the one to acquire it.
594 607
595 608 2006-05-07 Fernando Perez <Fernando.Perez@colorado.edu>
596 609
597 610 * IPython/Release.py (version): put out 0.7.2.rc1 for testing.
598 611
599 612 2006-04-11 Ville Vainio <vivainio@gmail.com>
600 613
601 614 * iplib.py, ipmaker.py: .ipy extension now means "ipython batch file"
602 615 in command line. E.g. "ipython test.ipy" runs test.ipy with ipython
603 616 prefilters, allowing stuff like magics and aliases in the file.
604 617
605 618 * Prompts.py, Extensions/clearcmd.py, ipy_system_conf.py: %clear magic
606 619 added. Supported now are "%clear in" and "%clear out" (clear input and
607 620 output history, respectively). Also fixed CachedOutput.flush to
608 621 properly flush the output cache.
609 622
610 623 * Extensions/pspersistence.py: Fix %store to avoid "%store obj.attr"
611 624 half-success (and fail explicitly).
612 625
613 626 2006-03-28 Ville Vainio <vivainio@gmail.com>
614 627
615 628 * iplib.py: Fix quoting of aliases so that only argless ones
616 629 are quoted
617 630
618 631 2006-03-28 Ville Vainio <vivainio@gmail.com>
619 632
620 633 * iplib.py: Quote aliases with spaces in the name.
621 634 "c:\program files\blah\bin" is now legal alias target.
622 635
623 636 * ext_rehashdir.py: Space no longer allowed as arg
624 637 separator, since space is legal in path names.
625 638
626 639 2006-03-16 Ville Vainio <vivainio@gmail.com>
627 640
628 641 * upgrade_dir.py: Take path.py from Extensions, correcting
629 642 %upgrade magic
630 643
631 644 * ipmaker.py: Suggest using %upgrade if ipy_user_conf.py isn't found.
632 645
633 646 * hooks.py: Only enclose editor binary in quotes if legal and
634 647 necessary (space in the name, and is an existing file). Fixes a bug
635 648 reported by Zachary Pincus.
636 649
637 650 2006-03-13 Fernando Perez <Fernando.Perez@colorado.edu>
638 651
639 652 * Manual: thanks to a tip on proper color handling for Emacs, by
640 653 Eric J Haywiser <ejh1-AT-MIT.EDU>.
641 654
642 655 * ipython.el: close http://www.scipy.net/roundup/ipython/issue57
643 656 by applying the provided patch. Thanks to Liu Jin
644 657 <m.liu.jin-AT-gmail.com> for the contribution. No problems under
645 658 XEmacs/Linux, I'm trusting the submitter that it actually helps
646 659 under win32/GNU Emacs. Will revisit if any problems are reported.
647 660
648 661 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
649 662
650 663 * IPython/Gnuplot2.py (_FileClass): update for current Gnuplot.py
651 664 from SVN, thanks to a patch by Ryan Woodard <rywo@bas.ac.uk>.
652 665
653 666 2006-03-12 Ville Vainio <vivainio@gmail.com>
654 667
655 668 * Magic.py (magic_timeit): Added %timeit magic, contributed by
656 669 Torsten Marek.
657 670
658 671 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
659 672
660 673 * IPython/Magic.py (magic_macro): fix so that the n1-n2 syntax for
661 674 line ranges works again.
662 675
663 676 2006-03-11 Fernando Perez <Fernando.Perez@colorado.edu>
664 677
665 678 * IPython/iplib.py (showtraceback): add back sys.last_traceback
666 679 and friends, after a discussion with Zach Pincus on ipython-user.
667 680 I'm not 100% sure, but after thinking about it quite a bit, it may
668 681 be OK. Testing with the multithreaded shells didn't reveal any
669 682 problems, but let's keep an eye out.
670 683
671 684 In the process, I fixed a few things which were calling
672 685 self.InteractiveTB() directly (like safe_execfile), which is a
673 686 mistake: ALL exception reporting should be done by calling
674 687 self.showtraceback(), which handles state and tab-completion and
675 688 more.
676 689
677 690 2006-03-01 Ville Vainio <vivainio@gmail.com>
678 691
679 692 * Extensions/ipipe.py: Added Walter Doerwald's "ipipe" module.
680 693 To use, do "from ipipe import *".
681 694
682 695 2006-02-24 Ville Vainio <vivainio@gmail.com>
683 696
684 697 * Magic.py, upgrade_dir.py: %upgrade magic added. Does things more
685 698 "cleanly" and safely than the older upgrade mechanism.
686 699
687 700 2006-02-21 Ville Vainio <vivainio@gmail.com>
688 701
689 702 * Magic.py: %save works again.
690 703
691 704 2006-02-15 Ville Vainio <vivainio@gmail.com>
692 705
693 706 * Magic.py: %Pprint works again
694 707
695 708 * Extensions/ipy_sane_defaults.py: Provide everything provided
696 709 in default ipythonrc, to make it possible to have a completely empty
697 710 ipythonrc (and thus completely rc-file free configuration)
698 711
699 712 2006-02-11 Fernando Perez <Fernando.Perez@colorado.edu>
700 713
701 714 * IPython/hooks.py (editor): quote the call to the editor command,
702 715 to allow commands with spaces in them. Problem noted by watching
703 716 Ian Oswald's video about textpad under win32 at
704 717 http://showmedo.com/videoListPage?listKey=PythonIPythonSeries
705 718
706 719 * IPython/UserConfig/ipythonrc: Replace @ signs with % when
707 720 describing magics (we haven't used @ for a loong time).
708 721
709 722 * IPython/ultraTB.py (VerboseTB.text.text_repr): Added patch
710 723 contributed by marienz to close
711 724 http://www.scipy.net/roundup/ipython/issue53.
712 725
713 726 2006-02-10 Ville Vainio <vivainio@gmail.com>
714 727
715 728 * genutils.py: getoutput now works in win32 too
716 729
717 730 * completer.py: alias and magic completion only invoked
718 731 at the first "item" in the line, to avoid "cd %store"
719 732 nonsense.
720 733
721 734 2006-02-09 Ville Vainio <vivainio@gmail.com>
722 735
723 736 * test/*: Added a unit testing framework (finally).
724 737 '%run runtests.py' to run test_*.
725 738
726 739 * ipapi.py: Exposed runlines and set_custom_exc
727 740
728 741 2006-02-07 Ville Vainio <vivainio@gmail.com>
729 742
730 743 * iplib.py: don't split "f 1 2" to "f(1,2)" in autocall,
731 744 instead use "f(1 2)" as before.
732 745
733 746 2006-02-05 Fernando Perez <Fernando.Perez@colorado.edu>
734 747
735 748 * IPython/demo.py (IPythonDemo): Add new classes to the demo
736 749 facilities, for demos processed by the IPython input filter
737 750 (IPythonDemo), and for running a script one-line-at-a-time as a
738 751 demo, both for pure Python (LineDemo) and for IPython-processed
739 752 input (IPythonLineDemo). After a request by Dave Kohel, from the
740 753 SAGE team.
741 754 (Demo.edit): added an edit() method to the demo objects, to edit
742 755 the in-memory copy of the last executed block.
743 756
744 757 * IPython/Magic.py (magic_edit): add '-r' option for 'raw'
745 758 processing to %edit, %macro and %save. These commands can now be
746 759 invoked on the unprocessed input as it was typed by the user
747 760 (without any prefilters applied). After requests by the SAGE team
748 761 at SAGE days 2006: http://modular.ucsd.edu/sage/days1/schedule.html.
749 762
750 763 2006-02-01 Ville Vainio <vivainio@gmail.com>
751 764
752 765 * setup.py, eggsetup.py: easy_install ipython==dev works
753 766 correctly now (on Linux)
754 767
755 768 * ipy_user_conf,ipmaker: user config changes, removed spurious
756 769 warnings
757 770
758 771 * iplib: if rc.banner is string, use it as is.
759 772
760 773 * Magic: %pycat accepts a string argument and pages it's contents.
761 774
762 775
763 776 2006-01-30 Ville Vainio <vivainio@gmail.com>
764 777
765 778 * pickleshare,pspersistence,ipapi,Magic: persistence overhaul.
766 779 Now %store and bookmarks work through PickleShare, meaning that
767 780 concurrent access is possible and all ipython sessions see the
768 781 same database situation all the time, instead of snapshot of
769 782 the situation when the session was started. Hence, %bookmark
770 783 results are immediately accessible from othes sessions. The database
771 784 is also available for use by user extensions. See:
772 785 http://www.python.org/pypi/pickleshare
773 786
774 787 * hooks.py: Two new hooks, 'shutdown_hook' and 'late_startup_hook'.
775 788
776 789 * aliases can now be %store'd
777 790
778 791 * path.py moved to Extensions so that pickleshare does not need
779 792 IPython-specific import. Extensions added to pythonpath right
780 793 at __init__.
781 794
782 795 * iplib.py: ipalias deprecated/redundant; aliases are converted and
783 796 called with _ip.system and the pre-transformed command string.
784 797
785 798 2006-01-29 Fernando Perez <Fernando.Perez@colorado.edu>
786 799
787 800 * IPython/iplib.py (interact): Fix that we were not catching
788 801 KeyboardInterrupt exceptions properly. I'm not quite sure why the
789 802 logic here had to change, but it's fixed now.
790 803
791 804 2006-01-29 Ville Vainio <vivainio@gmail.com>
792 805
793 806 * iplib.py: Try to import pyreadline on Windows.
794 807
795 808 2006-01-27 Ville Vainio <vivainio@gmail.com>
796 809
797 810 * iplib.py: Expose ipapi as _ip in builtin namespace.
798 811 Makes ipmagic (-> _ip.magic), ipsystem (-> _ip.system)
799 812 and ip_set_hook (-> _ip.set_hook) redundant. % and !
800 813 syntax now produce _ip.* variant of the commands.
801 814
802 815 * "_ip.options().autoedit_syntax = 2" automatically throws
803 816 user to editor for syntax error correction without prompting.
804 817
805 818 2006-01-27 Ville Vainio <vivainio@gmail.com>
806 819
807 820 * ipmaker.py: Give "realistic" sys.argv for scripts (without
808 821 'ipython' at argv[0]) executed through command line.
809 822 NOTE: this DEPRECATES calling ipython with multiple scripts
810 823 ("ipython a.py b.py c.py")
811 824
812 825 * iplib.py, hooks.py: Added configurable input prefilter,
813 826 named 'input_prefilter'. See ext_rescapture.py for example
814 827 usage.
815 828
816 829 * ext_rescapture.py, Magic.py: Better system command output capture
817 830 through 'var = !ls' (deprecates user-visible %sc). Same notation
818 831 applies for magics, 'var = %alias' assigns alias list to var.
819 832
820 833 * ipapi.py: added meta() for accessing extension-usable data store.
821 834
822 835 * iplib.py: added InteractiveShell.getapi(). New magics should be
823 836 written doing self.getapi() instead of using the shell directly.
824 837
825 838 * Magic.py: %store now allows doing %store foo > ~/myfoo.txt and
826 839 %store foo >> ~/myfoo.txt to store variables to files (in clean
827 840 textual form, not a restorable pickle).
828 841
829 842 * ipmaker.py: now import ipy_profile_PROFILENAME automatically
830 843
831 844 * usage.py, Magic.py: added %quickref
832 845
833 846 * iplib.py: ESC_PAREN fixes: /f 1 2 -> f(1,2), not f(1 2).
834 847
835 848 * GetoptErrors when invoking magics etc. with wrong args
836 849 are now more helpful:
837 850 GetoptError: option -l not recognized (allowed: "qb" )
838 851
839 852 2006-01-25 Fernando Perez <Fernando.Perez@colorado.edu>
840 853
841 854 * IPython/demo.py (Demo.show): Flush stdout after each block, so
842 855 computationally intensive blocks don't appear to stall the demo.
843 856
844 857 2006-01-24 Ville Vainio <vivainio@gmail.com>
845 858
846 859 * iplib.py, hooks.py: 'result_display' hook can return a non-None
847 860 value to manipulate resulting history entry.
848 861
849 862 * ipapi.py: Moved TryNext here from hooks.py. Moved functions
850 863 to instance methods of IPApi class, to make extending an embedded
851 864 IPython feasible. See ext_rehashdir.py for example usage.
852 865
853 866 * Merged 1071-1076 from branches/0.7.1
854 867
855 868
856 869 2006-01-23 Fernando Perez <Fernando.Perez@colorado.edu>
857 870
858 871 * tools/release (daystamp): Fix build tools to use the new
859 872 eggsetup.py script to build lightweight eggs.
860 873
861 874 * Applied changesets 1062 and 1064 before 0.7.1 release.
862 875
863 876 * IPython/Magic.py (magic_history): Add '-r' option to %hist, to
864 877 see the raw input history (without conversions like %ls ->
865 878 ipmagic("ls")). After a request from W. Stein, SAGE
866 879 (http://modular.ucsd.edu/sage) developer. This information is
867 880 stored in the input_hist_raw attribute of the IPython instance, so
868 881 developers can access it if needed (it's an InputList instance).
869 882
870 883 * Versionstring = 0.7.2.svn
871 884
872 885 * eggsetup.py: A separate script for constructing eggs, creates
873 886 proper launch scripts even on Windows (an .exe file in
874 887 \python24\scripts).
875 888
876 889 * ipapi.py: launch_new_instance, launch entry point needed for the
877 890 egg.
878 891
879 892 2006-01-23 Ville Vainio <vivainio@gmail.com>
880 893
881 894 * Added %cpaste magic for pasting python code
882 895
883 896 2006-01-22 Ville Vainio <vivainio@gmail.com>
884 897
885 898 * Merge from branches/0.7.1 into trunk, revs 1052-1057
886 899
887 900 * Versionstring = 0.7.2.svn
888 901
889 902 * eggsetup.py: A separate script for constructing eggs, creates
890 903 proper launch scripts even on Windows (an .exe file in
891 904 \python24\scripts).
892 905
893 906 * ipapi.py: launch_new_instance, launch entry point needed for the
894 907 egg.
895 908
896 909 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
897 910
898 911 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
899 912 %pfile foo would print the file for foo even if it was a binary.
900 913 Now, extensions '.so' and '.dll' are skipped.
901 914
902 915 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
903 916 bug, where macros would fail in all threaded modes. I'm not 100%
904 917 sure, so I'm going to put out an rc instead of making a release
905 918 today, and wait for feedback for at least a few days.
906 919
907 920 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
908 921 it...) the handling of pasting external code with autoindent on.
909 922 To get out of a multiline input, the rule will appear for most
910 923 users unchanged: two blank lines or change the indent level
911 924 proposed by IPython. But there is a twist now: you can
912 925 add/subtract only *one or two spaces*. If you add/subtract three
913 926 or more (unless you completely delete the line), IPython will
914 927 accept that line, and you'll need to enter a second one of pure
915 928 whitespace. I know it sounds complicated, but I can't find a
916 929 different solution that covers all the cases, with the right
917 930 heuristics. Hopefully in actual use, nobody will really notice
918 931 all these strange rules and things will 'just work'.
919 932
920 933 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
921 934
922 935 * IPython/iplib.py (interact): catch exceptions which can be
923 936 triggered asynchronously by signal handlers. Thanks to an
924 937 automatic crash report, submitted by Colin Kingsley
925 938 <tercel-AT-gentoo.org>.
926 939
927 940 2006-01-20 Ville Vainio <vivainio@gmail.com>
928 941
929 942 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
930 943 (%rehashdir, very useful, try it out) of how to extend ipython
931 944 with new magics. Also added Extensions dir to pythonpath to make
932 945 importing extensions easy.
933 946
934 947 * %store now complains when trying to store interactively declared
935 948 classes / instances of those classes.
936 949
937 950 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
938 951 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
939 952 if they exist, and ipy_user_conf.py with some defaults is created for
940 953 the user.
941 954
942 955 * Startup rehashing done by the config file, not InterpreterExec.
943 956 This means system commands are available even without selecting the
944 957 pysh profile. It's the sensible default after all.
945 958
946 959 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
947 960
948 961 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
949 962 multiline code with autoindent on working. But I am really not
950 963 sure, so this needs more testing. Will commit a debug-enabled
951 964 version for now, while I test it some more, so that Ville and
952 965 others may also catch any problems. Also made
953 966 self.indent_current_str() a method, to ensure that there's no
954 967 chance of the indent space count and the corresponding string
955 968 falling out of sync. All code needing the string should just call
956 969 the method.
957 970
958 971 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
959 972
960 973 * IPython/Magic.py (magic_edit): fix check for when users don't
961 974 save their output files, the try/except was in the wrong section.
962 975
963 976 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
964 977
965 978 * IPython/Magic.py (magic_run): fix __file__ global missing from
966 979 script's namespace when executed via %run. After a report by
967 980 Vivian.
968 981
969 982 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
970 983 when using python 2.4. The parent constructor changed in 2.4, and
971 984 we need to track it directly (we can't call it, as it messes up
972 985 readline and tab-completion inside our pdb would stop working).
973 986 After a bug report by R. Bernstein <rocky-AT-panix.com>.
974 987
975 988 2006-01-16 Ville Vainio <vivainio@gmail.com>
976 989
977 990 * Ipython/magic.py: Reverted back to old %edit functionality
978 991 that returns file contents on exit.
979 992
980 993 * IPython/path.py: Added Jason Orendorff's "path" module to
981 994 IPython tree, http://www.jorendorff.com/articles/python/path/.
982 995 You can get path objects conveniently through %sc, and !!, e.g.:
983 996 sc files=ls
984 997 for p in files.paths: # or files.p
985 998 print p,p.mtime
986 999
987 1000 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
988 1001 now work again without considering the exclusion regexp -
989 1002 hence, things like ',foo my/path' turn to 'foo("my/path")'
990 1003 instead of syntax error.
991 1004
992 1005
993 1006 2006-01-14 Ville Vainio <vivainio@gmail.com>
994 1007
995 1008 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
996 1009 ipapi decorators for python 2.4 users, options() provides access to rc
997 1010 data.
998 1011
999 1012 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
1000 1013 as path separators (even on Linux ;-). Space character after
1001 1014 backslash (as yielded by tab completer) is still space;
1002 1015 "%cd long\ name" works as expected.
1003 1016
1004 1017 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
1005 1018 as "chain of command", with priority. API stays the same,
1006 1019 TryNext exception raised by a hook function signals that
1007 1020 current hook failed and next hook should try handling it, as
1008 1021 suggested by Walter DΓΆrwald <walter@livinglogic.de>. Walter also
1009 1022 requested configurable display hook, which is now implemented.
1010 1023
1011 1024 2006-01-13 Ville Vainio <vivainio@gmail.com>
1012 1025
1013 1026 * IPython/platutils*.py: platform specific utility functions,
1014 1027 so far only set_term_title is implemented (change terminal
1015 1028 label in windowing systems). %cd now changes the title to
1016 1029 current dir.
1017 1030
1018 1031 * IPython/Release.py: Added myself to "authors" list,
1019 1032 had to create new files.
1020 1033
1021 1034 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
1022 1035 shell escape; not a known bug but had potential to be one in the
1023 1036 future.
1024 1037
1025 1038 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
1026 1039 extension API for IPython! See the module for usage example. Fix
1027 1040 OInspect for docstring-less magic functions.
1028 1041
1029 1042
1030 1043 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
1031 1044
1032 1045 * IPython/iplib.py (raw_input): temporarily deactivate all
1033 1046 attempts at allowing pasting of code with autoindent on. It
1034 1047 introduced bugs (reported by Prabhu) and I can't seem to find a
1035 1048 robust combination which works in all cases. Will have to revisit
1036 1049 later.
1037 1050
1038 1051 * IPython/genutils.py: remove isspace() function. We've dropped
1039 1052 2.2 compatibility, so it's OK to use the string method.
1040 1053
1041 1054 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
1042 1055
1043 1056 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
1044 1057 matching what NOT to autocall on, to include all python binary
1045 1058 operators (including things like 'and', 'or', 'is' and 'in').
1046 1059 Prompted by a bug report on 'foo & bar', but I realized we had
1047 1060 many more potential bug cases with other operators. The regexp is
1048 1061 self.re_exclude_auto, it's fairly commented.
1049 1062
1050 1063 2006-01-12 Ville Vainio <vivainio@gmail.com>
1051 1064
1052 1065 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
1053 1066 Prettified and hardened string/backslash quoting with ipsystem(),
1054 1067 ipalias() and ipmagic(). Now even \ characters are passed to
1055 1068 %magics, !shell escapes and aliases exactly as they are in the
1056 1069 ipython command line. Should improve backslash experience,
1057 1070 particularly in Windows (path delimiter for some commands that
1058 1071 won't understand '/'), but Unix benefits as well (regexps). %cd
1059 1072 magic still doesn't support backslash path delimiters, though. Also
1060 1073 deleted all pretense of supporting multiline command strings in
1061 1074 !system or %magic commands. Thanks to Jerry McRae for suggestions.
1062 1075
1063 1076 * doc/build_doc_instructions.txt added. Documentation on how to
1064 1077 use doc/update_manual.py, added yesterday. Both files contributed
1065 1078 by JΓΆrgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
1066 1079 doc/*.sh for deprecation at a later date.
1067 1080
1068 1081 * /ipython.py Added ipython.py to root directory for
1069 1082 zero-installation (tar xzvf ipython.tgz; cd ipython; python
1070 1083 ipython.py) and development convenience (no need to keep doing
1071 1084 "setup.py install" between changes).
1072 1085
1073 1086 * Made ! and !! shell escapes work (again) in multiline expressions:
1074 1087 if 1:
1075 1088 !ls
1076 1089 !!ls
1077 1090
1078 1091 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
1079 1092
1080 1093 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
1081 1094 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
1082 1095 module in case-insensitive installation. Was causing crashes
1083 1096 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
1084 1097
1085 1098 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
1086 1099 <marienz-AT-gentoo.org>, closes
1087 1100 http://www.scipy.net/roundup/ipython/issue51.
1088 1101
1089 1102 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
1090 1103
1091 1104 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the
1092 1105 problem of excessive CPU usage under *nix and keyboard lag under
1093 1106 win32.
1094 1107
1095 1108 2006-01-10 *** Released version 0.7.0
1096 1109
1097 1110 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
1098 1111
1099 1112 * IPython/Release.py (revision): tag version number to 0.7.0,
1100 1113 ready for release.
1101 1114
1102 1115 * IPython/Magic.py (magic_edit): Add print statement to %edit so
1103 1116 it informs the user of the name of the temp. file used. This can
1104 1117 help if you decide later to reuse that same file, so you know
1105 1118 where to copy the info from.
1106 1119
1107 1120 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
1108 1121
1109 1122 * setup_bdist_egg.py: little script to build an egg. Added
1110 1123 support in the release tools as well.
1111 1124
1112 1125 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
1113 1126
1114 1127 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
1115 1128 version selection (new -wxversion command line and ipythonrc
1116 1129 parameter). Patch contributed by Arnd Baecker
1117 1130 <arnd.baecker-AT-web.de>.
1118 1131
1119 1132 * IPython/iplib.py (embed_mainloop): fix tab-completion in
1120 1133 embedded instances, for variables defined at the interactive
1121 1134 prompt of the embedded ipython. Reported by Arnd.
1122 1135
1123 1136 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
1124 1137 it can be used as a (stateful) toggle, or with a direct parameter.
1125 1138
1126 1139 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
1127 1140 could be triggered in certain cases and cause the traceback
1128 1141 printer not to work.
1129 1142
1130 1143 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
1131 1144
1132 1145 * IPython/iplib.py (_should_recompile): Small fix, closes
1133 1146 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
1134 1147
1135 1148 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
1136 1149
1137 1150 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
1138 1151 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
1139 1152 Moad for help with tracking it down.
1140 1153
1141 1154 * IPython/iplib.py (handle_auto): fix autocall handling for
1142 1155 objects which support BOTH __getitem__ and __call__ (so that f [x]
1143 1156 is left alone, instead of becoming f([x]) automatically).
1144 1157
1145 1158 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
1146 1159 Ville's patch.
1147 1160
1148 1161 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
1149 1162
1150 1163 * IPython/iplib.py (handle_auto): changed autocall semantics to
1151 1164 include 'smart' mode, where the autocall transformation is NOT
1152 1165 applied if there are no arguments on the line. This allows you to
1153 1166 just type 'foo' if foo is a callable to see its internal form,
1154 1167 instead of having it called with no arguments (typically a
1155 1168 mistake). The old 'full' autocall still exists: for that, you
1156 1169 need to set the 'autocall' parameter to 2 in your ipythonrc file.
1157 1170
1158 1171 * IPython/completer.py (Completer.attr_matches): add
1159 1172 tab-completion support for Enthoughts' traits. After a report by
1160 1173 Arnd and a patch by Prabhu.
1161 1174
1162 1175 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
1163 1176
1164 1177 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
1165 1178 Schmolck's patch to fix inspect.getinnerframes().
1166 1179
1167 1180 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
1168 1181 for embedded instances, regarding handling of namespaces and items
1169 1182 added to the __builtin__ one. Multiple embedded instances and
1170 1183 recursive embeddings should work better now (though I'm not sure
1171 1184 I've got all the corner cases fixed, that code is a bit of a brain
1172 1185 twister).
1173 1186
1174 1187 * IPython/Magic.py (magic_edit): added support to edit in-memory
1175 1188 macros (automatically creates the necessary temp files). %edit
1176 1189 also doesn't return the file contents anymore, it's just noise.
1177 1190
1178 1191 * IPython/completer.py (Completer.attr_matches): revert change to
1179 1192 complete only on attributes listed in __all__. I realized it
1180 1193 cripples the tab-completion system as a tool for exploring the
1181 1194 internals of unknown libraries (it renders any non-__all__
1182 1195 attribute off-limits). I got bit by this when trying to see
1183 1196 something inside the dis module.
1184 1197
1185 1198 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
1186 1199
1187 1200 * IPython/iplib.py (InteractiveShell.__init__): add .meta
1188 1201 namespace for users and extension writers to hold data in. This
1189 1202 follows the discussion in
1190 1203 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
1191 1204
1192 1205 * IPython/completer.py (IPCompleter.complete): small patch to help
1193 1206 tab-completion under Emacs, after a suggestion by John Barnard
1194 1207 <barnarj-AT-ccf.org>.
1195 1208
1196 1209 * IPython/Magic.py (Magic.extract_input_slices): added support for
1197 1210 the slice notation in magics to use N-M to represent numbers N...M
1198 1211 (closed endpoints). This is used by %macro and %save.
1199 1212
1200 1213 * IPython/completer.py (Completer.attr_matches): for modules which
1201 1214 define __all__, complete only on those. After a patch by Jeffrey
1202 1215 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
1203 1216 speed up this routine.
1204 1217
1205 1218 * IPython/Logger.py (Logger.log): fix a history handling bug. I
1206 1219 don't know if this is the end of it, but the behavior now is
1207 1220 certainly much more correct. Note that coupled with macros,
1208 1221 slightly surprising (at first) behavior may occur: a macro will in
1209 1222 general expand to multiple lines of input, so upon exiting, the
1210 1223 in/out counters will both be bumped by the corresponding amount
1211 1224 (as if the macro's contents had been typed interactively). Typing
1212 1225 %hist will reveal the intermediate (silently processed) lines.
1213 1226
1214 1227 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
1215 1228 pickle to fail (%run was overwriting __main__ and not restoring
1216 1229 it, but pickle relies on __main__ to operate).
1217 1230
1218 1231 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
1219 1232 using properties, but forgot to make the main InteractiveShell
1220 1233 class a new-style class. Properties fail silently, and
1221 1234 mysteriously, with old-style class (getters work, but
1222 1235 setters don't do anything).
1223 1236
1224 1237 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
1225 1238
1226 1239 * IPython/Magic.py (magic_history): fix history reporting bug (I
1227 1240 know some nasties are still there, I just can't seem to find a
1228 1241 reproducible test case to track them down; the input history is
1229 1242 falling out of sync...)
1230 1243
1231 1244 * IPython/iplib.py (handle_shell_escape): fix bug where both
1232 1245 aliases and system accesses where broken for indented code (such
1233 1246 as loops).
1234 1247
1235 1248 * IPython/genutils.py (shell): fix small but critical bug for
1236 1249 win32 system access.
1237 1250
1238 1251 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
1239 1252
1240 1253 * IPython/iplib.py (showtraceback): remove use of the
1241 1254 sys.last_{type/value/traceback} structures, which are non
1242 1255 thread-safe.
1243 1256 (_prefilter): change control flow to ensure that we NEVER
1244 1257 introspect objects when autocall is off. This will guarantee that
1245 1258 having an input line of the form 'x.y', where access to attribute
1246 1259 'y' has side effects, doesn't trigger the side effect TWICE. It
1247 1260 is important to note that, with autocall on, these side effects
1248 1261 can still happen.
1249 1262 (ipsystem): new builtin, to complete the ip{magic/alias/system}
1250 1263 trio. IPython offers these three kinds of special calls which are
1251 1264 not python code, and it's a good thing to have their call method
1252 1265 be accessible as pure python functions (not just special syntax at
1253 1266 the command line). It gives us a better internal implementation
1254 1267 structure, as well as exposing these for user scripting more
1255 1268 cleanly.
1256 1269
1257 1270 * IPython/macro.py (Macro.__init__): moved macros to a standalone
1258 1271 file. Now that they'll be more likely to be used with the
1259 1272 persistance system (%store), I want to make sure their module path
1260 1273 doesn't change in the future, so that we don't break things for
1261 1274 users' persisted data.
1262 1275
1263 1276 * IPython/iplib.py (autoindent_update): move indentation
1264 1277 management into the _text_ processing loop, not the keyboard
1265 1278 interactive one. This is necessary to correctly process non-typed
1266 1279 multiline input (such as macros).
1267 1280
1268 1281 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
1269 1282 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
1270 1283 which was producing problems in the resulting manual.
1271 1284 (magic_whos): improve reporting of instances (show their class,
1272 1285 instead of simply printing 'instance' which isn't terribly
1273 1286 informative).
1274 1287
1275 1288 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
1276 1289 (minor mods) to support network shares under win32.
1277 1290
1278 1291 * IPython/winconsole.py (get_console_size): add new winconsole
1279 1292 module and fixes to page_dumb() to improve its behavior under
1280 1293 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
1281 1294
1282 1295 * IPython/Magic.py (Macro): simplified Macro class to just
1283 1296 subclass list. We've had only 2.2 compatibility for a very long
1284 1297 time, yet I was still avoiding subclassing the builtin types. No
1285 1298 more (I'm also starting to use properties, though I won't shift to
1286 1299 2.3-specific features quite yet).
1287 1300 (magic_store): added Ville's patch for lightweight variable
1288 1301 persistence, after a request on the user list by Matt Wilkie
1289 1302 <maphew-AT-gmail.com>. The new %store magic's docstring has full
1290 1303 details.
1291 1304
1292 1305 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1293 1306 changed the default logfile name from 'ipython.log' to
1294 1307 'ipython_log.py'. These logs are real python files, and now that
1295 1308 we have much better multiline support, people are more likely to
1296 1309 want to use them as such. Might as well name them correctly.
1297 1310
1298 1311 * IPython/Magic.py: substantial cleanup. While we can't stop
1299 1312 using magics as mixins, due to the existing customizations 'out
1300 1313 there' which rely on the mixin naming conventions, at least I
1301 1314 cleaned out all cross-class name usage. So once we are OK with
1302 1315 breaking compatibility, the two systems can be separated.
1303 1316
1304 1317 * IPython/Logger.py: major cleanup. This one is NOT a mixin
1305 1318 anymore, and the class is a fair bit less hideous as well. New
1306 1319 features were also introduced: timestamping of input, and logging
1307 1320 of output results. These are user-visible with the -t and -o
1308 1321 options to %logstart. Closes
1309 1322 http://www.scipy.net/roundup/ipython/issue11 and a request by
1310 1323 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
1311 1324
1312 1325 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
1313 1326
1314 1327 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
1315 1328 better handle backslashes in paths. See the thread 'More Windows
1316 1329 questions part 2 - \/ characters revisited' on the iypthon user
1317 1330 list:
1318 1331 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
1319 1332
1320 1333 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
1321 1334
1322 1335 (InteractiveShell.__init__): change threaded shells to not use the
1323 1336 ipython crash handler. This was causing more problems than not,
1324 1337 as exceptions in the main thread (GUI code, typically) would
1325 1338 always show up as a 'crash', when they really weren't.
1326 1339
1327 1340 The colors and exception mode commands (%colors/%xmode) have been
1328 1341 synchronized to also take this into account, so users can get
1329 1342 verbose exceptions for their threaded code as well. I also added
1330 1343 support for activating pdb inside this exception handler as well,
1331 1344 so now GUI authors can use IPython's enhanced pdb at runtime.
1332 1345
1333 1346 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
1334 1347 true by default, and add it to the shipped ipythonrc file. Since
1335 1348 this asks the user before proceeding, I think it's OK to make it
1336 1349 true by default.
1337 1350
1338 1351 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
1339 1352 of the previous special-casing of input in the eval loop. I think
1340 1353 this is cleaner, as they really are commands and shouldn't have
1341 1354 a special role in the middle of the core code.
1342 1355
1343 1356 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
1344 1357
1345 1358 * IPython/iplib.py (edit_syntax_error): added support for
1346 1359 automatically reopening the editor if the file had a syntax error
1347 1360 in it. Thanks to scottt who provided the patch at:
1348 1361 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
1349 1362 version committed).
1350 1363
1351 1364 * IPython/iplib.py (handle_normal): add suport for multi-line
1352 1365 input with emtpy lines. This fixes
1353 1366 http://www.scipy.net/roundup/ipython/issue43 and a similar
1354 1367 discussion on the user list.
1355 1368
1356 1369 WARNING: a behavior change is necessarily introduced to support
1357 1370 blank lines: now a single blank line with whitespace does NOT
1358 1371 break the input loop, which means that when autoindent is on, by
1359 1372 default hitting return on the next (indented) line does NOT exit.
1360 1373
1361 1374 Instead, to exit a multiline input you can either have:
1362 1375
1363 1376 - TWO whitespace lines (just hit return again), or
1364 1377 - a single whitespace line of a different length than provided
1365 1378 by the autoindent (add or remove a space).
1366 1379
1367 1380 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
1368 1381 module to better organize all readline-related functionality.
1369 1382 I've deleted FlexCompleter and put all completion clases here.
1370 1383
1371 1384 * IPython/iplib.py (raw_input): improve indentation management.
1372 1385 It is now possible to paste indented code with autoindent on, and
1373 1386 the code is interpreted correctly (though it still looks bad on
1374 1387 screen, due to the line-oriented nature of ipython).
1375 1388 (MagicCompleter.complete): change behavior so that a TAB key on an
1376 1389 otherwise empty line actually inserts a tab, instead of completing
1377 1390 on the entire global namespace. This makes it easier to use the
1378 1391 TAB key for indentation. After a request by Hans Meine
1379 1392 <hans_meine-AT-gmx.net>
1380 1393 (_prefilter): add support so that typing plain 'exit' or 'quit'
1381 1394 does a sensible thing. Originally I tried to deviate as little as
1382 1395 possible from the default python behavior, but even that one may
1383 1396 change in this direction (thread on python-dev to that effect).
1384 1397 Regardless, ipython should do the right thing even if CPython's
1385 1398 '>>>' prompt doesn't.
1386 1399 (InteractiveShell): removed subclassing code.InteractiveConsole
1387 1400 class. By now we'd overridden just about all of its methods: I've
1388 1401 copied the remaining two over, and now ipython is a standalone
1389 1402 class. This will provide a clearer picture for the chainsaw
1390 1403 branch refactoring.
1391 1404
1392 1405 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
1393 1406
1394 1407 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
1395 1408 failures for objects which break when dir() is called on them.
1396 1409
1397 1410 * IPython/FlexCompleter.py (Completer.__init__): Added support for
1398 1411 distinct local and global namespaces in the completer API. This
1399 1412 change allows us to properly handle completion with distinct
1400 1413 scopes, including in embedded instances (this had never really
1401 1414 worked correctly).
1402 1415
1403 1416 Note: this introduces a change in the constructor for
1404 1417 MagicCompleter, as a new global_namespace parameter is now the
1405 1418 second argument (the others were bumped one position).
1406 1419
1407 1420 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
1408 1421
1409 1422 * IPython/iplib.py (embed_mainloop): fix tab-completion in
1410 1423 embedded instances (which can be done now thanks to Vivian's
1411 1424 frame-handling fixes for pdb).
1412 1425 (InteractiveShell.__init__): Fix namespace handling problem in
1413 1426 embedded instances. We were overwriting __main__ unconditionally,
1414 1427 and this should only be done for 'full' (non-embedded) IPython;
1415 1428 embedded instances must respect the caller's __main__. Thanks to
1416 1429 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
1417 1430
1418 1431 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
1419 1432
1420 1433 * setup.py: added download_url to setup(). This registers the
1421 1434 download address at PyPI, which is not only useful to humans
1422 1435 browsing the site, but is also picked up by setuptools (the Eggs
1423 1436 machinery). Thanks to Ville and R. Kern for the info/discussion
1424 1437 on this.
1425 1438
1426 1439 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
1427 1440
1428 1441 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
1429 1442 This brings a lot of nice functionality to the pdb mode, which now
1430 1443 has tab-completion, syntax highlighting, and better stack handling
1431 1444 than before. Many thanks to Vivian De Smedt
1432 1445 <vivian-AT-vdesmedt.com> for the original patches.
1433 1446
1434 1447 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
1435 1448
1436 1449 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
1437 1450 sequence to consistently accept the banner argument. The
1438 1451 inconsistency was tripping SAGE, thanks to Gary Zablackis
1439 1452 <gzabl-AT-yahoo.com> for the report.
1440 1453
1441 1454 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1442 1455
1443 1456 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1444 1457 Fix bug where a naked 'alias' call in the ipythonrc file would
1445 1458 cause a crash. Bug reported by Jorgen Stenarson.
1446 1459
1447 1460 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1448 1461
1449 1462 * IPython/ipmaker.py (make_IPython): cleanups which should improve
1450 1463 startup time.
1451 1464
1452 1465 * IPython/iplib.py (runcode): my globals 'fix' for embedded
1453 1466 instances had introduced a bug with globals in normal code. Now
1454 1467 it's working in all cases.
1455 1468
1456 1469 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
1457 1470 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
1458 1471 has been introduced to set the default case sensitivity of the
1459 1472 searches. Users can still select either mode at runtime on a
1460 1473 per-search basis.
1461 1474
1462 1475 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
1463 1476
1464 1477 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
1465 1478 attributes in wildcard searches for subclasses. Modified version
1466 1479 of a patch by Jorgen.
1467 1480
1468 1481 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
1469 1482
1470 1483 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
1471 1484 embedded instances. I added a user_global_ns attribute to the
1472 1485 InteractiveShell class to handle this.
1473 1486
1474 1487 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
1475 1488
1476 1489 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
1477 1490 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
1478 1491 (reported under win32, but may happen also in other platforms).
1479 1492 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
1480 1493
1481 1494 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
1482 1495
1483 1496 * IPython/Magic.py (magic_psearch): new support for wildcard
1484 1497 patterns. Now, typing ?a*b will list all names which begin with a
1485 1498 and end in b, for example. The %psearch magic has full
1486 1499 docstrings. Many thanks to JΓΆrgen Stenarson
1487 1500 <jorgen.stenarson-AT-bostream.nu>, author of the patches
1488 1501 implementing this functionality.
1489 1502
1490 1503 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1491 1504
1492 1505 * Manual: fixed long-standing annoyance of double-dashes (as in
1493 1506 --prefix=~, for example) being stripped in the HTML version. This
1494 1507 is a latex2html bug, but a workaround was provided. Many thanks
1495 1508 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
1496 1509 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
1497 1510 rolling. This seemingly small issue had tripped a number of users
1498 1511 when first installing, so I'm glad to see it gone.
1499 1512
1500 1513 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1501 1514
1502 1515 * IPython/Extensions/numeric_formats.py: fix missing import,
1503 1516 reported by Stephen Walton.
1504 1517
1505 1518 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
1506 1519
1507 1520 * IPython/demo.py: finish demo module, fully documented now.
1508 1521
1509 1522 * IPython/genutils.py (file_read): simple little utility to read a
1510 1523 file and ensure it's closed afterwards.
1511 1524
1512 1525 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
1513 1526
1514 1527 * IPython/demo.py (Demo.__init__): added support for individually
1515 1528 tagging blocks for automatic execution.
1516 1529
1517 1530 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
1518 1531 syntax-highlighted python sources, requested by John.
1519 1532
1520 1533 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
1521 1534
1522 1535 * IPython/demo.py (Demo.again): fix bug where again() blocks after
1523 1536 finishing.
1524 1537
1525 1538 * IPython/genutils.py (shlex_split): moved from Magic to here,
1526 1539 where all 2.2 compatibility stuff lives. I needed it for demo.py.
1527 1540
1528 1541 * IPython/demo.py (Demo.__init__): added support for silent
1529 1542 blocks, improved marks as regexps, docstrings written.
1530 1543 (Demo.__init__): better docstring, added support for sys.argv.
1531 1544
1532 1545 * IPython/genutils.py (marquee): little utility used by the demo
1533 1546 code, handy in general.
1534 1547
1535 1548 * IPython/demo.py (Demo.__init__): new class for interactive
1536 1549 demos. Not documented yet, I just wrote it in a hurry for
1537 1550 scipy'05. Will docstring later.
1538 1551
1539 1552 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
1540 1553
1541 1554 * IPython/Shell.py (sigint_handler): Drastic simplification which
1542 1555 also seems to make Ctrl-C work correctly across threads! This is
1543 1556 so simple, that I can't beleive I'd missed it before. Needs more
1544 1557 testing, though.
1545 1558 (KBINT): Never mind, revert changes. I'm sure I'd tried something
1546 1559 like this before...
1547 1560
1548 1561 * IPython/genutils.py (get_home_dir): add protection against
1549 1562 non-dirs in win32 registry.
1550 1563
1551 1564 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
1552 1565 bug where dict was mutated while iterating (pysh crash).
1553 1566
1554 1567 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
1555 1568
1556 1569 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
1557 1570 spurious newlines added by this routine. After a report by
1558 1571 F. Mantegazza.
1559 1572
1560 1573 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
1561 1574
1562 1575 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
1563 1576 calls. These were a leftover from the GTK 1.x days, and can cause
1564 1577 problems in certain cases (after a report by John Hunter).
1565 1578
1566 1579 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
1567 1580 os.getcwd() fails at init time. Thanks to patch from David Remahl
1568 1581 <chmod007-AT-mac.com>.
1569 1582 (InteractiveShell.__init__): prevent certain special magics from
1570 1583 being shadowed by aliases. Closes
1571 1584 http://www.scipy.net/roundup/ipython/issue41.
1572 1585
1573 1586 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
1574 1587
1575 1588 * IPython/iplib.py (InteractiveShell.complete): Added new
1576 1589 top-level completion method to expose the completion mechanism
1577 1590 beyond readline-based environments.
1578 1591
1579 1592 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
1580 1593
1581 1594 * tools/ipsvnc (svnversion): fix svnversion capture.
1582 1595
1583 1596 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
1584 1597 attribute to self, which was missing. Before, it was set by a
1585 1598 routine which in certain cases wasn't being called, so the
1586 1599 instance could end up missing the attribute. This caused a crash.
1587 1600 Closes http://www.scipy.net/roundup/ipython/issue40.
1588 1601
1589 1602 2005-08-16 Fernando Perez <fperez@colorado.edu>
1590 1603
1591 1604 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
1592 1605 contains non-string attribute. Closes
1593 1606 http://www.scipy.net/roundup/ipython/issue38.
1594 1607
1595 1608 2005-08-14 Fernando Perez <fperez@colorado.edu>
1596 1609
1597 1610 * tools/ipsvnc: Minor improvements, to add changeset info.
1598 1611
1599 1612 2005-08-12 Fernando Perez <fperez@colorado.edu>
1600 1613
1601 1614 * IPython/iplib.py (runsource): remove self.code_to_run_src
1602 1615 attribute. I realized this is nothing more than
1603 1616 '\n'.join(self.buffer), and having the same data in two different
1604 1617 places is just asking for synchronization bugs. This may impact
1605 1618 people who have custom exception handlers, so I need to warn
1606 1619 ipython-dev about it (F. Mantegazza may use them).
1607 1620
1608 1621 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
1609 1622
1610 1623 * IPython/genutils.py: fix 2.2 compatibility (generators)
1611 1624
1612 1625 2005-07-18 Fernando Perez <fperez@colorado.edu>
1613 1626
1614 1627 * IPython/genutils.py (get_home_dir): fix to help users with
1615 1628 invalid $HOME under win32.
1616 1629
1617 1630 2005-07-17 Fernando Perez <fperez@colorado.edu>
1618 1631
1619 1632 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
1620 1633 some old hacks and clean up a bit other routines; code should be
1621 1634 simpler and a bit faster.
1622 1635
1623 1636 * IPython/iplib.py (interact): removed some last-resort attempts
1624 1637 to survive broken stdout/stderr. That code was only making it
1625 1638 harder to abstract out the i/o (necessary for gui integration),
1626 1639 and the crashes it could prevent were extremely rare in practice
1627 1640 (besides being fully user-induced in a pretty violent manner).
1628 1641
1629 1642 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
1630 1643 Nothing major yet, but the code is simpler to read; this should
1631 1644 make it easier to do more serious modifications in the future.
1632 1645
1633 1646 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
1634 1647 which broke in .15 (thanks to a report by Ville).
1635 1648
1636 1649 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
1637 1650 be quite correct, I know next to nothing about unicode). This
1638 1651 will allow unicode strings to be used in prompts, amongst other
1639 1652 cases. It also will prevent ipython from crashing when unicode
1640 1653 shows up unexpectedly in many places. If ascii encoding fails, we
1641 1654 assume utf_8. Currently the encoding is not a user-visible
1642 1655 setting, though it could be made so if there is demand for it.
1643 1656
1644 1657 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
1645 1658
1646 1659 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
1647 1660
1648 1661 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
1649 1662
1650 1663 * IPython/genutils.py: Add 2.2 compatibility here, so all other
1651 1664 code can work transparently for 2.2/2.3.
1652 1665
1653 1666 2005-07-16 Fernando Perez <fperez@colorado.edu>
1654 1667
1655 1668 * IPython/ultraTB.py (ExceptionColors): Make a global variable
1656 1669 out of the color scheme table used for coloring exception
1657 1670 tracebacks. This allows user code to add new schemes at runtime.
1658 1671 This is a minimally modified version of the patch at
1659 1672 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
1660 1673 for the contribution.
1661 1674
1662 1675 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
1663 1676 slightly modified version of the patch in
1664 1677 http://www.scipy.net/roundup/ipython/issue34, which also allows me
1665 1678 to remove the previous try/except solution (which was costlier).
1666 1679 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
1667 1680
1668 1681 2005-06-08 Fernando Perez <fperez@colorado.edu>
1669 1682
1670 1683 * IPython/iplib.py (write/write_err): Add methods to abstract all
1671 1684 I/O a bit more.
1672 1685
1673 1686 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
1674 1687 warning, reported by Aric Hagberg, fix by JD Hunter.
1675 1688
1676 1689 2005-06-02 *** Released version 0.6.15
1677 1690
1678 1691 2005-06-01 Fernando Perez <fperez@colorado.edu>
1679 1692
1680 1693 * IPython/iplib.py (MagicCompleter.file_matches): Fix
1681 1694 tab-completion of filenames within open-quoted strings. Note that
1682 1695 this requires that in ~/.ipython/ipythonrc, users change the
1683 1696 readline delimiters configuration to read:
1684 1697
1685 1698 readline_remove_delims -/~
1686 1699
1687 1700
1688 1701 2005-05-31 *** Released version 0.6.14
1689 1702
1690 1703 2005-05-29 Fernando Perez <fperez@colorado.edu>
1691 1704
1692 1705 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
1693 1706 with files not on the filesystem. Reported by Eliyahu Sandler
1694 1707 <eli@gondolin.net>
1695 1708
1696 1709 2005-05-22 Fernando Perez <fperez@colorado.edu>
1697 1710
1698 1711 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
1699 1712 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
1700 1713
1701 1714 2005-05-19 Fernando Perez <fperez@colorado.edu>
1702 1715
1703 1716 * IPython/iplib.py (safe_execfile): close a file which could be
1704 1717 left open (causing problems in win32, which locks open files).
1705 1718 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
1706 1719
1707 1720 2005-05-18 Fernando Perez <fperez@colorado.edu>
1708 1721
1709 1722 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
1710 1723 keyword arguments correctly to safe_execfile().
1711 1724
1712 1725 2005-05-13 Fernando Perez <fperez@colorado.edu>
1713 1726
1714 1727 * ipython.1: Added info about Qt to manpage, and threads warning
1715 1728 to usage page (invoked with --help).
1716 1729
1717 1730 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
1718 1731 new matcher (it goes at the end of the priority list) to do
1719 1732 tab-completion on named function arguments. Submitted by George
1720 1733 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
1721 1734 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
1722 1735 for more details.
1723 1736
1724 1737 * IPython/Magic.py (magic_run): Added new -e flag to ignore
1725 1738 SystemExit exceptions in the script being run. Thanks to a report
1726 1739 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
1727 1740 producing very annoying behavior when running unit tests.
1728 1741
1729 1742 2005-05-12 Fernando Perez <fperez@colorado.edu>
1730 1743
1731 1744 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
1732 1745 which I'd broken (again) due to a changed regexp. In the process,
1733 1746 added ';' as an escape to auto-quote the whole line without
1734 1747 splitting its arguments. Thanks to a report by Jerry McRae
1735 1748 <qrs0xyc02-AT-sneakemail.com>.
1736 1749
1737 1750 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
1738 1751 possible crashes caused by a TokenError. Reported by Ed Schofield
1739 1752 <schofield-AT-ftw.at>.
1740 1753
1741 1754 2005-05-06 Fernando Perez <fperez@colorado.edu>
1742 1755
1743 1756 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
1744 1757
1745 1758 2005-04-29 Fernando Perez <fperez@colorado.edu>
1746 1759
1747 1760 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
1748 1761 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
1749 1762 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
1750 1763 which provides support for Qt interactive usage (similar to the
1751 1764 existing one for WX and GTK). This had been often requested.
1752 1765
1753 1766 2005-04-14 *** Released version 0.6.13
1754 1767
1755 1768 2005-04-08 Fernando Perez <fperez@colorado.edu>
1756 1769
1757 1770 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
1758 1771 from _ofind, which gets called on almost every input line. Now,
1759 1772 we only try to get docstrings if they are actually going to be
1760 1773 used (the overhead of fetching unnecessary docstrings can be
1761 1774 noticeable for certain objects, such as Pyro proxies).
1762 1775
1763 1776 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
1764 1777 for completers. For some reason I had been passing them the state
1765 1778 variable, which completers never actually need, and was in
1766 1779 conflict with the rlcompleter API. Custom completers ONLY need to
1767 1780 take the text parameter.
1768 1781
1769 1782 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
1770 1783 work correctly in pysh. I've also moved all the logic which used
1771 1784 to be in pysh.py here, which will prevent problems with future
1772 1785 upgrades. However, this time I must warn users to update their
1773 1786 pysh profile to include the line
1774 1787
1775 1788 import_all IPython.Extensions.InterpreterExec
1776 1789
1777 1790 because otherwise things won't work for them. They MUST also
1778 1791 delete pysh.py and the line
1779 1792
1780 1793 execfile pysh.py
1781 1794
1782 1795 from their ipythonrc-pysh.
1783 1796
1784 1797 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
1785 1798 robust in the face of objects whose dir() returns non-strings
1786 1799 (which it shouldn't, but some broken libs like ITK do). Thanks to
1787 1800 a patch by John Hunter (implemented differently, though). Also
1788 1801 minor improvements by using .extend instead of + on lists.
1789 1802
1790 1803 * pysh.py:
1791 1804
1792 1805 2005-04-06 Fernando Perez <fperez@colorado.edu>
1793 1806
1794 1807 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
1795 1808 by default, so that all users benefit from it. Those who don't
1796 1809 want it can still turn it off.
1797 1810
1798 1811 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
1799 1812 config file, I'd forgotten about this, so users were getting it
1800 1813 off by default.
1801 1814
1802 1815 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
1803 1816 consistency. Now magics can be called in multiline statements,
1804 1817 and python variables can be expanded in magic calls via $var.
1805 1818 This makes the magic system behave just like aliases or !system
1806 1819 calls.
1807 1820
1808 1821 2005-03-28 Fernando Perez <fperez@colorado.edu>
1809 1822
1810 1823 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
1811 1824 expensive string additions for building command. Add support for
1812 1825 trailing ';' when autocall is used.
1813 1826
1814 1827 2005-03-26 Fernando Perez <fperez@colorado.edu>
1815 1828
1816 1829 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
1817 1830 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
1818 1831 ipython.el robust against prompts with any number of spaces
1819 1832 (including 0) after the ':' character.
1820 1833
1821 1834 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
1822 1835 continuation prompt, which misled users to think the line was
1823 1836 already indented. Closes debian Bug#300847, reported to me by
1824 1837 Norbert Tretkowski <tretkowski-AT-inittab.de>.
1825 1838
1826 1839 2005-03-23 Fernando Perez <fperez@colorado.edu>
1827 1840
1828 1841 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
1829 1842 properly aligned if they have embedded newlines.
1830 1843
1831 1844 * IPython/iplib.py (runlines): Add a public method to expose
1832 1845 IPython's code execution machinery, so that users can run strings
1833 1846 as if they had been typed at the prompt interactively.
1834 1847 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
1835 1848 methods which can call the system shell, but with python variable
1836 1849 expansion. The three such methods are: __IPYTHON__.system,
1837 1850 .getoutput and .getoutputerror. These need to be documented in a
1838 1851 'public API' section (to be written) of the manual.
1839 1852
1840 1853 2005-03-20 Fernando Perez <fperez@colorado.edu>
1841 1854
1842 1855 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
1843 1856 for custom exception handling. This is quite powerful, and it
1844 1857 allows for user-installable exception handlers which can trap
1845 1858 custom exceptions at runtime and treat them separately from
1846 1859 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
1847 1860 Mantegazza <mantegazza-AT-ill.fr>.
1848 1861 (InteractiveShell.set_custom_completer): public API function to
1849 1862 add new completers at runtime.
1850 1863
1851 1864 2005-03-19 Fernando Perez <fperez@colorado.edu>
1852 1865
1853 1866 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
1854 1867 allow objects which provide their docstrings via non-standard
1855 1868 mechanisms (like Pyro proxies) to still be inspected by ipython's
1856 1869 ? system.
1857 1870
1858 1871 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
1859 1872 automatic capture system. I tried quite hard to make it work
1860 1873 reliably, and simply failed. I tried many combinations with the
1861 1874 subprocess module, but eventually nothing worked in all needed
1862 1875 cases (not blocking stdin for the child, duplicating stdout
1863 1876 without blocking, etc). The new %sc/%sx still do capture to these
1864 1877 magical list/string objects which make shell use much more
1865 1878 conveninent, so not all is lost.
1866 1879
1867 1880 XXX - FIX MANUAL for the change above!
1868 1881
1869 1882 (runsource): I copied code.py's runsource() into ipython to modify
1870 1883 it a bit. Now the code object and source to be executed are
1871 1884 stored in ipython. This makes this info accessible to third-party
1872 1885 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
1873 1886 Mantegazza <mantegazza-AT-ill.fr>.
1874 1887
1875 1888 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
1876 1889 history-search via readline (like C-p/C-n). I'd wanted this for a
1877 1890 long time, but only recently found out how to do it. For users
1878 1891 who already have their ipythonrc files made and want this, just
1879 1892 add:
1880 1893
1881 1894 readline_parse_and_bind "\e[A": history-search-backward
1882 1895 readline_parse_and_bind "\e[B": history-search-forward
1883 1896
1884 1897 2005-03-18 Fernando Perez <fperez@colorado.edu>
1885 1898
1886 1899 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
1887 1900 LSString and SList classes which allow transparent conversions
1888 1901 between list mode and whitespace-separated string.
1889 1902 (magic_r): Fix recursion problem in %r.
1890 1903
1891 1904 * IPython/genutils.py (LSString): New class to be used for
1892 1905 automatic storage of the results of all alias/system calls in _o
1893 1906 and _e (stdout/err). These provide a .l/.list attribute which
1894 1907 does automatic splitting on newlines. This means that for most
1895 1908 uses, you'll never need to do capturing of output with %sc/%sx
1896 1909 anymore, since ipython keeps this always done for you. Note that
1897 1910 only the LAST results are stored, the _o/e variables are
1898 1911 overwritten on each call. If you need to save their contents
1899 1912 further, simply bind them to any other name.
1900 1913
1901 1914 2005-03-17 Fernando Perez <fperez@colorado.edu>
1902 1915
1903 1916 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1904 1917 prompt namespace handling.
1905 1918
1906 1919 2005-03-16 Fernando Perez <fperez@colorado.edu>
1907 1920
1908 1921 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1909 1922 classic prompts to be '>>> ' (final space was missing, and it
1910 1923 trips the emacs python mode).
1911 1924 (BasePrompt.__str__): Added safe support for dynamic prompt
1912 1925 strings. Now you can set your prompt string to be '$x', and the
1913 1926 value of x will be printed from your interactive namespace. The
1914 1927 interpolation syntax includes the full Itpl support, so
1915 1928 ${foo()+x+bar()} is a valid prompt string now, and the function
1916 1929 calls will be made at runtime.
1917 1930
1918 1931 2005-03-15 Fernando Perez <fperez@colorado.edu>
1919 1932
1920 1933 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1921 1934 avoid name clashes in pylab. %hist still works, it just forwards
1922 1935 the call to %history.
1923 1936
1924 1937 2005-03-02 *** Released version 0.6.12
1925 1938
1926 1939 2005-03-02 Fernando Perez <fperez@colorado.edu>
1927 1940
1928 1941 * IPython/iplib.py (handle_magic): log magic calls properly as
1929 1942 ipmagic() function calls.
1930 1943
1931 1944 * IPython/Magic.py (magic_time): Improved %time to support
1932 1945 statements and provide wall-clock as well as CPU time.
1933 1946
1934 1947 2005-02-27 Fernando Perez <fperez@colorado.edu>
1935 1948
1936 1949 * IPython/hooks.py: New hooks module, to expose user-modifiable
1937 1950 IPython functionality in a clean manner. For now only the editor
1938 1951 hook is actually written, and other thigns which I intend to turn
1939 1952 into proper hooks aren't yet there. The display and prefilter
1940 1953 stuff, for example, should be hooks. But at least now the
1941 1954 framework is in place, and the rest can be moved here with more
1942 1955 time later. IPython had had a .hooks variable for a long time for
1943 1956 this purpose, but I'd never actually used it for anything.
1944 1957
1945 1958 2005-02-26 Fernando Perez <fperez@colorado.edu>
1946 1959
1947 1960 * IPython/ipmaker.py (make_IPython): make the default ipython
1948 1961 directory be called _ipython under win32, to follow more the
1949 1962 naming peculiarities of that platform (where buggy software like
1950 1963 Visual Sourcesafe breaks with .named directories). Reported by
1951 1964 Ville Vainio.
1952 1965
1953 1966 2005-02-23 Fernando Perez <fperez@colorado.edu>
1954 1967
1955 1968 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1956 1969 auto_aliases for win32 which were causing problems. Users can
1957 1970 define the ones they personally like.
1958 1971
1959 1972 2005-02-21 Fernando Perez <fperez@colorado.edu>
1960 1973
1961 1974 * IPython/Magic.py (magic_time): new magic to time execution of
1962 1975 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1963 1976
1964 1977 2005-02-19 Fernando Perez <fperez@colorado.edu>
1965 1978
1966 1979 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1967 1980 into keys (for prompts, for example).
1968 1981
1969 1982 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1970 1983 prompts in case users want them. This introduces a small behavior
1971 1984 change: ipython does not automatically add a space to all prompts
1972 1985 anymore. To get the old prompts with a space, users should add it
1973 1986 manually to their ipythonrc file, so for example prompt_in1 should
1974 1987 now read 'In [\#]: ' instead of 'In [\#]:'.
1975 1988 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1976 1989 file) to control left-padding of secondary prompts.
1977 1990
1978 1991 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1979 1992 the profiler can't be imported. Fix for Debian, which removed
1980 1993 profile.py because of License issues. I applied a slightly
1981 1994 modified version of the original Debian patch at
1982 1995 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1983 1996
1984 1997 2005-02-17 Fernando Perez <fperez@colorado.edu>
1985 1998
1986 1999 * IPython/genutils.py (native_line_ends): Fix bug which would
1987 2000 cause improper line-ends under win32 b/c I was not opening files
1988 2001 in binary mode. Bug report and fix thanks to Ville.
1989 2002
1990 2003 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1991 2004 trying to catch spurious foo[1] autocalls. My fix actually broke
1992 2005 ',/' autoquote/call with explicit escape (bad regexp).
1993 2006
1994 2007 2005-02-15 *** Released version 0.6.11
1995 2008
1996 2009 2005-02-14 Fernando Perez <fperez@colorado.edu>
1997 2010
1998 2011 * IPython/background_jobs.py: New background job management
1999 2012 subsystem. This is implemented via a new set of classes, and
2000 2013 IPython now provides a builtin 'jobs' object for background job
2001 2014 execution. A convenience %bg magic serves as a lightweight
2002 2015 frontend for starting the more common type of calls. This was
2003 2016 inspired by discussions with B. Granger and the BackgroundCommand
2004 2017 class described in the book Python Scripting for Computational
2005 2018 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
2006 2019 (although ultimately no code from this text was used, as IPython's
2007 2020 system is a separate implementation).
2008 2021
2009 2022 * IPython/iplib.py (MagicCompleter.python_matches): add new option
2010 2023 to control the completion of single/double underscore names
2011 2024 separately. As documented in the example ipytonrc file, the
2012 2025 readline_omit__names variable can now be set to 2, to omit even
2013 2026 single underscore names. Thanks to a patch by Brian Wong
2014 2027 <BrianWong-AT-AirgoNetworks.Com>.
2015 2028 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
2016 2029 be autocalled as foo([1]) if foo were callable. A problem for
2017 2030 things which are both callable and implement __getitem__.
2018 2031 (init_readline): Fix autoindentation for win32. Thanks to a patch
2019 2032 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
2020 2033
2021 2034 2005-02-12 Fernando Perez <fperez@colorado.edu>
2022 2035
2023 2036 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
2024 2037 which I had written long ago to sort out user error messages which
2025 2038 may occur during startup. This seemed like a good idea initially,
2026 2039 but it has proven a disaster in retrospect. I don't want to
2027 2040 change much code for now, so my fix is to set the internal 'debug'
2028 2041 flag to true everywhere, whose only job was precisely to control
2029 2042 this subsystem. This closes issue 28 (as well as avoiding all
2030 2043 sorts of strange hangups which occur from time to time).
2031 2044
2032 2045 2005-02-07 Fernando Perez <fperez@colorado.edu>
2033 2046
2034 2047 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
2035 2048 previous call produced a syntax error.
2036 2049
2037 2050 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
2038 2051 classes without constructor.
2039 2052
2040 2053 2005-02-06 Fernando Perez <fperez@colorado.edu>
2041 2054
2042 2055 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
2043 2056 completions with the results of each matcher, so we return results
2044 2057 to the user from all namespaces. This breaks with ipython
2045 2058 tradition, but I think it's a nicer behavior. Now you get all
2046 2059 possible completions listed, from all possible namespaces (python,
2047 2060 filesystem, magics...) After a request by John Hunter
2048 2061 <jdhunter-AT-nitace.bsd.uchicago.edu>.
2049 2062
2050 2063 2005-02-05 Fernando Perez <fperez@colorado.edu>
2051 2064
2052 2065 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
2053 2066 the call had quote characters in it (the quotes were stripped).
2054 2067
2055 2068 2005-01-31 Fernando Perez <fperez@colorado.edu>
2056 2069
2057 2070 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
2058 2071 Itpl.itpl() to make the code more robust against psyco
2059 2072 optimizations.
2060 2073
2061 2074 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
2062 2075 of causing an exception. Quicker, cleaner.
2063 2076
2064 2077 2005-01-28 Fernando Perez <fperez@colorado.edu>
2065 2078
2066 2079 * scripts/ipython_win_post_install.py (install): hardcode
2067 2080 sys.prefix+'python.exe' as the executable path. It turns out that
2068 2081 during the post-installation run, sys.executable resolves to the
2069 2082 name of the binary installer! I should report this as a distutils
2070 2083 bug, I think. I updated the .10 release with this tiny fix, to
2071 2084 avoid annoying the lists further.
2072 2085
2073 2086 2005-01-27 *** Released version 0.6.10
2074 2087
2075 2088 2005-01-27 Fernando Perez <fperez@colorado.edu>
2076 2089
2077 2090 * IPython/numutils.py (norm): Added 'inf' as optional name for
2078 2091 L-infinity norm, included references to mathworld.com for vector
2079 2092 norm definitions.
2080 2093 (amin/amax): added amin/amax for array min/max. Similar to what
2081 2094 pylab ships with after the recent reorganization of names.
2082 2095 (spike/spike_odd): removed deprecated spike/spike_odd functions.
2083 2096
2084 2097 * ipython.el: committed Alex's recent fixes and improvements.
2085 2098 Tested with python-mode from CVS, and it looks excellent. Since
2086 2099 python-mode hasn't released anything in a while, I'm temporarily
2087 2100 putting a copy of today's CVS (v 4.70) of python-mode in:
2088 2101 http://ipython.scipy.org/tmp/python-mode.el
2089 2102
2090 2103 * scripts/ipython_win_post_install.py (install): Win32 fix to use
2091 2104 sys.executable for the executable name, instead of assuming it's
2092 2105 called 'python.exe' (the post-installer would have produced broken
2093 2106 setups on systems with a differently named python binary).
2094 2107
2095 2108 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
2096 2109 references to os.linesep, to make the code more
2097 2110 platform-independent. This is also part of the win32 coloring
2098 2111 fixes.
2099 2112
2100 2113 * IPython/genutils.py (page_dumb): Remove attempts to chop long
2101 2114 lines, which actually cause coloring bugs because the length of
2102 2115 the line is very difficult to correctly compute with embedded
2103 2116 escapes. This was the source of all the coloring problems under
2104 2117 Win32. I think that _finally_, Win32 users have a properly
2105 2118 working ipython in all respects. This would never have happened
2106 2119 if not for Gary Bishop and Viktor Ransmayr's great help and work.
2107 2120
2108 2121 2005-01-26 *** Released version 0.6.9
2109 2122
2110 2123 2005-01-25 Fernando Perez <fperez@colorado.edu>
2111 2124
2112 2125 * setup.py: finally, we have a true Windows installer, thanks to
2113 2126 the excellent work of Viktor Ransmayr
2114 2127 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
2115 2128 Windows users. The setup routine is quite a bit cleaner thanks to
2116 2129 this, and the post-install script uses the proper functions to
2117 2130 allow a clean de-installation using the standard Windows Control
2118 2131 Panel.
2119 2132
2120 2133 * IPython/genutils.py (get_home_dir): changed to use the $HOME
2121 2134 environment variable under all OSes (including win32) if
2122 2135 available. This will give consistency to win32 users who have set
2123 2136 this variable for any reason. If os.environ['HOME'] fails, the
2124 2137 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
2125 2138
2126 2139 2005-01-24 Fernando Perez <fperez@colorado.edu>
2127 2140
2128 2141 * IPython/numutils.py (empty_like): add empty_like(), similar to
2129 2142 zeros_like() but taking advantage of the new empty() Numeric routine.
2130 2143
2131 2144 2005-01-23 *** Released version 0.6.8
2132 2145
2133 2146 2005-01-22 Fernando Perez <fperez@colorado.edu>
2134 2147
2135 2148 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
2136 2149 automatic show() calls. After discussing things with JDH, it
2137 2150 turns out there are too many corner cases where this can go wrong.
2138 2151 It's best not to try to be 'too smart', and simply have ipython
2139 2152 reproduce as much as possible the default behavior of a normal
2140 2153 python shell.
2141 2154
2142 2155 * IPython/iplib.py (InteractiveShell.__init__): Modified the
2143 2156 line-splitting regexp and _prefilter() to avoid calling getattr()
2144 2157 on assignments. This closes
2145 2158 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
2146 2159 readline uses getattr(), so a simple <TAB> keypress is still
2147 2160 enough to trigger getattr() calls on an object.
2148 2161
2149 2162 2005-01-21 Fernando Perez <fperez@colorado.edu>
2150 2163
2151 2164 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
2152 2165 docstring under pylab so it doesn't mask the original.
2153 2166
2154 2167 2005-01-21 *** Released version 0.6.7
2155 2168
2156 2169 2005-01-21 Fernando Perez <fperez@colorado.edu>
2157 2170
2158 2171 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
2159 2172 signal handling for win32 users in multithreaded mode.
2160 2173
2161 2174 2005-01-17 Fernando Perez <fperez@colorado.edu>
2162 2175
2163 2176 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
2164 2177 instances with no __init__. After a crash report by Norbert Nemec
2165 2178 <Norbert-AT-nemec-online.de>.
2166 2179
2167 2180 2005-01-14 Fernando Perez <fperez@colorado.edu>
2168 2181
2169 2182 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
2170 2183 names for verbose exceptions, when multiple dotted names and the
2171 2184 'parent' object were present on the same line.
2172 2185
2173 2186 2005-01-11 Fernando Perez <fperez@colorado.edu>
2174 2187
2175 2188 * IPython/genutils.py (flag_calls): new utility to trap and flag
2176 2189 calls in functions. I need it to clean up matplotlib support.
2177 2190 Also removed some deprecated code in genutils.
2178 2191
2179 2192 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
2180 2193 that matplotlib scripts called with %run, which don't call show()
2181 2194 themselves, still have their plotting windows open.
2182 2195
2183 2196 2005-01-05 Fernando Perez <fperez@colorado.edu>
2184 2197
2185 2198 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
2186 2199 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
2187 2200
2188 2201 2004-12-19 Fernando Perez <fperez@colorado.edu>
2189 2202
2190 2203 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
2191 2204 parent_runcode, which was an eyesore. The same result can be
2192 2205 obtained with Python's regular superclass mechanisms.
2193 2206
2194 2207 2004-12-17 Fernando Perez <fperez@colorado.edu>
2195 2208
2196 2209 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
2197 2210 reported by Prabhu.
2198 2211 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
2199 2212 sys.stderr) instead of explicitly calling sys.stderr. This helps
2200 2213 maintain our I/O abstractions clean, for future GUI embeddings.
2201 2214
2202 2215 * IPython/genutils.py (info): added new utility for sys.stderr
2203 2216 unified info message handling (thin wrapper around warn()).
2204 2217
2205 2218 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
2206 2219 composite (dotted) names on verbose exceptions.
2207 2220 (VerboseTB.nullrepr): harden against another kind of errors which
2208 2221 Python's inspect module can trigger, and which were crashing
2209 2222 IPython. Thanks to a report by Marco Lombardi
2210 2223 <mlombard-AT-ma010192.hq.eso.org>.
2211 2224
2212 2225 2004-12-13 *** Released version 0.6.6
2213 2226
2214 2227 2004-12-12 Fernando Perez <fperez@colorado.edu>
2215 2228
2216 2229 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
2217 2230 generated by pygtk upon initialization if it was built without
2218 2231 threads (for matplotlib users). After a crash reported by
2219 2232 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
2220 2233
2221 2234 * IPython/ipmaker.py (make_IPython): fix small bug in the
2222 2235 import_some parameter for multiple imports.
2223 2236
2224 2237 * IPython/iplib.py (ipmagic): simplified the interface of
2225 2238 ipmagic() to take a single string argument, just as it would be
2226 2239 typed at the IPython cmd line.
2227 2240 (ipalias): Added new ipalias() with an interface identical to
2228 2241 ipmagic(). This completes exposing a pure python interface to the
2229 2242 alias and magic system, which can be used in loops or more complex
2230 2243 code where IPython's automatic line mangling is not active.
2231 2244
2232 2245 * IPython/genutils.py (timing): changed interface of timing to
2233 2246 simply run code once, which is the most common case. timings()
2234 2247 remains unchanged, for the cases where you want multiple runs.
2235 2248
2236 2249 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
2237 2250 bug where Python2.2 crashes with exec'ing code which does not end
2238 2251 in a single newline. Python 2.3 is OK, so I hadn't noticed this
2239 2252 before.
2240 2253
2241 2254 2004-12-10 Fernando Perez <fperez@colorado.edu>
2242 2255
2243 2256 * IPython/Magic.py (Magic.magic_prun): changed name of option from
2244 2257 -t to -T, to accomodate the new -t flag in %run (the %run and
2245 2258 %prun options are kind of intermixed, and it's not easy to change
2246 2259 this with the limitations of python's getopt).
2247 2260
2248 2261 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
2249 2262 the execution of scripts. It's not as fine-tuned as timeit.py,
2250 2263 but it works from inside ipython (and under 2.2, which lacks
2251 2264 timeit.py). Optionally a number of runs > 1 can be given for
2252 2265 timing very short-running code.
2253 2266
2254 2267 * IPython/genutils.py (uniq_stable): new routine which returns a
2255 2268 list of unique elements in any iterable, but in stable order of
2256 2269 appearance. I needed this for the ultraTB fixes, and it's a handy
2257 2270 utility.
2258 2271
2259 2272 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
2260 2273 dotted names in Verbose exceptions. This had been broken since
2261 2274 the very start, now x.y will properly be printed in a Verbose
2262 2275 traceback, instead of x being shown and y appearing always as an
2263 2276 'undefined global'. Getting this to work was a bit tricky,
2264 2277 because by default python tokenizers are stateless. Saved by
2265 2278 python's ability to easily add a bit of state to an arbitrary
2266 2279 function (without needing to build a full-blown callable object).
2267 2280
2268 2281 Also big cleanup of this code, which had horrendous runtime
2269 2282 lookups of zillions of attributes for colorization. Moved all
2270 2283 this code into a few templates, which make it cleaner and quicker.
2271 2284
2272 2285 Printout quality was also improved for Verbose exceptions: one
2273 2286 variable per line, and memory addresses are printed (this can be
2274 2287 quite handy in nasty debugging situations, which is what Verbose
2275 2288 is for).
2276 2289
2277 2290 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
2278 2291 the command line as scripts to be loaded by embedded instances.
2279 2292 Doing so has the potential for an infinite recursion if there are
2280 2293 exceptions thrown in the process. This fixes a strange crash
2281 2294 reported by Philippe MULLER <muller-AT-irit.fr>.
2282 2295
2283 2296 2004-12-09 Fernando Perez <fperez@colorado.edu>
2284 2297
2285 2298 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
2286 2299 to reflect new names in matplotlib, which now expose the
2287 2300 matlab-compatible interface via a pylab module instead of the
2288 2301 'matlab' name. The new code is backwards compatible, so users of
2289 2302 all matplotlib versions are OK. Patch by J. Hunter.
2290 2303
2291 2304 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
2292 2305 of __init__ docstrings for instances (class docstrings are already
2293 2306 automatically printed). Instances with customized docstrings
2294 2307 (indep. of the class) are also recognized and all 3 separate
2295 2308 docstrings are printed (instance, class, constructor). After some
2296 2309 comments/suggestions by J. Hunter.
2297 2310
2298 2311 2004-12-05 Fernando Perez <fperez@colorado.edu>
2299 2312
2300 2313 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
2301 2314 warnings when tab-completion fails and triggers an exception.
2302 2315
2303 2316 2004-12-03 Fernando Perez <fperez@colorado.edu>
2304 2317
2305 2318 * IPython/Magic.py (magic_prun): Fix bug where an exception would
2306 2319 be triggered when using 'run -p'. An incorrect option flag was
2307 2320 being set ('d' instead of 'D').
2308 2321 (manpage): fix missing escaped \- sign.
2309 2322
2310 2323 2004-11-30 *** Released version 0.6.5
2311 2324
2312 2325 2004-11-30 Fernando Perez <fperez@colorado.edu>
2313 2326
2314 2327 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
2315 2328 setting with -d option.
2316 2329
2317 2330 * setup.py (docfiles): Fix problem where the doc glob I was using
2318 2331 was COMPLETELY BROKEN. It was giving the right files by pure
2319 2332 accident, but failed once I tried to include ipython.el. Note:
2320 2333 glob() does NOT allow you to do exclusion on multiple endings!
2321 2334
2322 2335 2004-11-29 Fernando Perez <fperez@colorado.edu>
2323 2336
2324 2337 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
2325 2338 the manpage as the source. Better formatting & consistency.
2326 2339
2327 2340 * IPython/Magic.py (magic_run): Added new -d option, to run
2328 2341 scripts under the control of the python pdb debugger. Note that
2329 2342 this required changing the %prun option -d to -D, to avoid a clash
2330 2343 (since %run must pass options to %prun, and getopt is too dumb to
2331 2344 handle options with string values with embedded spaces). Thanks
2332 2345 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
2333 2346 (magic_who_ls): added type matching to %who and %whos, so that one
2334 2347 can filter their output to only include variables of certain
2335 2348 types. Another suggestion by Matthew.
2336 2349 (magic_whos): Added memory summaries in kb and Mb for arrays.
2337 2350 (magic_who): Improve formatting (break lines every 9 vars).
2338 2351
2339 2352 2004-11-28 Fernando Perez <fperez@colorado.edu>
2340 2353
2341 2354 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
2342 2355 cache when empty lines were present.
2343 2356
2344 2357 2004-11-24 Fernando Perez <fperez@colorado.edu>
2345 2358
2346 2359 * IPython/usage.py (__doc__): document the re-activated threading
2347 2360 options for WX and GTK.
2348 2361
2349 2362 2004-11-23 Fernando Perez <fperez@colorado.edu>
2350 2363
2351 2364 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
2352 2365 the -wthread and -gthread options, along with a new -tk one to try
2353 2366 and coordinate Tk threading with wx/gtk. The tk support is very
2354 2367 platform dependent, since it seems to require Tcl and Tk to be
2355 2368 built with threads (Fedora1/2 appears NOT to have it, but in
2356 2369 Prabhu's Debian boxes it works OK). But even with some Tk
2357 2370 limitations, this is a great improvement.
2358 2371
2359 2372 * IPython/Prompts.py (prompt_specials_color): Added \t for time
2360 2373 info in user prompts. Patch by Prabhu.
2361 2374
2362 2375 2004-11-18 Fernando Perez <fperez@colorado.edu>
2363 2376
2364 2377 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
2365 2378 EOFErrors and bail, to avoid infinite loops if a non-terminating
2366 2379 file is fed into ipython. Patch submitted in issue 19 by user,
2367 2380 many thanks.
2368 2381
2369 2382 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
2370 2383 autoquote/parens in continuation prompts, which can cause lots of
2371 2384 problems. Closes roundup issue 20.
2372 2385
2373 2386 2004-11-17 Fernando Perez <fperez@colorado.edu>
2374 2387
2375 2388 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
2376 2389 reported as debian bug #280505. I'm not sure my local changelog
2377 2390 entry has the proper debian format (Jack?).
2378 2391
2379 2392 2004-11-08 *** Released version 0.6.4
2380 2393
2381 2394 2004-11-08 Fernando Perez <fperez@colorado.edu>
2382 2395
2383 2396 * IPython/iplib.py (init_readline): Fix exit message for Windows
2384 2397 when readline is active. Thanks to a report by Eric Jones
2385 2398 <eric-AT-enthought.com>.
2386 2399
2387 2400 2004-11-07 Fernando Perez <fperez@colorado.edu>
2388 2401
2389 2402 * IPython/genutils.py (page): Add a trap for OSError exceptions,
2390 2403 sometimes seen by win2k/cygwin users.
2391 2404
2392 2405 2004-11-06 Fernando Perez <fperez@colorado.edu>
2393 2406
2394 2407 * IPython/iplib.py (interact): Change the handling of %Exit from
2395 2408 trying to propagate a SystemExit to an internal ipython flag.
2396 2409 This is less elegant than using Python's exception mechanism, but
2397 2410 I can't get that to work reliably with threads, so under -pylab
2398 2411 %Exit was hanging IPython. Cross-thread exception handling is
2399 2412 really a bitch. Thaks to a bug report by Stephen Walton
2400 2413 <stephen.walton-AT-csun.edu>.
2401 2414
2402 2415 2004-11-04 Fernando Perez <fperez@colorado.edu>
2403 2416
2404 2417 * IPython/iplib.py (raw_input_original): store a pointer to the
2405 2418 true raw_input to harden against code which can modify it
2406 2419 (wx.py.PyShell does this and would otherwise crash ipython).
2407 2420 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
2408 2421
2409 2422 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
2410 2423 Ctrl-C problem, which does not mess up the input line.
2411 2424
2412 2425 2004-11-03 Fernando Perez <fperez@colorado.edu>
2413 2426
2414 2427 * IPython/Release.py: Changed licensing to BSD, in all files.
2415 2428 (name): lowercase name for tarball/RPM release.
2416 2429
2417 2430 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
2418 2431 use throughout ipython.
2419 2432
2420 2433 * IPython/Magic.py (Magic._ofind): Switch to using the new
2421 2434 OInspect.getdoc() function.
2422 2435
2423 2436 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
2424 2437 of the line currently being canceled via Ctrl-C. It's extremely
2425 2438 ugly, but I don't know how to do it better (the problem is one of
2426 2439 handling cross-thread exceptions).
2427 2440
2428 2441 2004-10-28 Fernando Perez <fperez@colorado.edu>
2429 2442
2430 2443 * IPython/Shell.py (signal_handler): add signal handlers to trap
2431 2444 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
2432 2445 report by Francesc Alted.
2433 2446
2434 2447 2004-10-21 Fernando Perez <fperez@colorado.edu>
2435 2448
2436 2449 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
2437 2450 to % for pysh syntax extensions.
2438 2451
2439 2452 2004-10-09 Fernando Perez <fperez@colorado.edu>
2440 2453
2441 2454 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
2442 2455 arrays to print a more useful summary, without calling str(arr).
2443 2456 This avoids the problem of extremely lengthy computations which
2444 2457 occur if arr is large, and appear to the user as a system lockup
2445 2458 with 100% cpu activity. After a suggestion by Kristian Sandberg
2446 2459 <Kristian.Sandberg@colorado.edu>.
2447 2460 (Magic.__init__): fix bug in global magic escapes not being
2448 2461 correctly set.
2449 2462
2450 2463 2004-10-08 Fernando Perez <fperez@colorado.edu>
2451 2464
2452 2465 * IPython/Magic.py (__license__): change to absolute imports of
2453 2466 ipython's own internal packages, to start adapting to the absolute
2454 2467 import requirement of PEP-328.
2455 2468
2456 2469 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
2457 2470 files, and standardize author/license marks through the Release
2458 2471 module instead of having per/file stuff (except for files with
2459 2472 particular licenses, like the MIT/PSF-licensed codes).
2460 2473
2461 2474 * IPython/Debugger.py: remove dead code for python 2.1
2462 2475
2463 2476 2004-10-04 Fernando Perez <fperez@colorado.edu>
2464 2477
2465 2478 * IPython/iplib.py (ipmagic): New function for accessing magics
2466 2479 via a normal python function call.
2467 2480
2468 2481 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
2469 2482 from '@' to '%', to accomodate the new @decorator syntax of python
2470 2483 2.4.
2471 2484
2472 2485 2004-09-29 Fernando Perez <fperez@colorado.edu>
2473 2486
2474 2487 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
2475 2488 matplotlib.use to prevent running scripts which try to switch
2476 2489 interactive backends from within ipython. This will just crash
2477 2490 the python interpreter, so we can't allow it (but a detailed error
2478 2491 is given to the user).
2479 2492
2480 2493 2004-09-28 Fernando Perez <fperez@colorado.edu>
2481 2494
2482 2495 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
2483 2496 matplotlib-related fixes so that using @run with non-matplotlib
2484 2497 scripts doesn't pop up spurious plot windows. This requires
2485 2498 matplotlib >= 0.63, where I had to make some changes as well.
2486 2499
2487 2500 * IPython/ipmaker.py (make_IPython): update version requirement to
2488 2501 python 2.2.
2489 2502
2490 2503 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
2491 2504 banner arg for embedded customization.
2492 2505
2493 2506 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
2494 2507 explicit uses of __IP as the IPython's instance name. Now things
2495 2508 are properly handled via the shell.name value. The actual code
2496 2509 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
2497 2510 is much better than before. I'll clean things completely when the
2498 2511 magic stuff gets a real overhaul.
2499 2512
2500 2513 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
2501 2514 minor changes to debian dir.
2502 2515
2503 2516 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
2504 2517 pointer to the shell itself in the interactive namespace even when
2505 2518 a user-supplied dict is provided. This is needed for embedding
2506 2519 purposes (found by tests with Michel Sanner).
2507 2520
2508 2521 2004-09-27 Fernando Perez <fperez@colorado.edu>
2509 2522
2510 2523 * IPython/UserConfig/ipythonrc: remove []{} from
2511 2524 readline_remove_delims, so that things like [modname.<TAB> do
2512 2525 proper completion. This disables [].TAB, but that's a less common
2513 2526 case than module names in list comprehensions, for example.
2514 2527 Thanks to a report by Andrea Riciputi.
2515 2528
2516 2529 2004-09-09 Fernando Perez <fperez@colorado.edu>
2517 2530
2518 2531 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
2519 2532 blocking problems in win32 and osx. Fix by John.
2520 2533
2521 2534 2004-09-08 Fernando Perez <fperez@colorado.edu>
2522 2535
2523 2536 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
2524 2537 for Win32 and OSX. Fix by John Hunter.
2525 2538
2526 2539 2004-08-30 *** Released version 0.6.3
2527 2540
2528 2541 2004-08-30 Fernando Perez <fperez@colorado.edu>
2529 2542
2530 2543 * setup.py (isfile): Add manpages to list of dependent files to be
2531 2544 updated.
2532 2545
2533 2546 2004-08-27 Fernando Perez <fperez@colorado.edu>
2534 2547
2535 2548 * IPython/Shell.py (start): I've disabled -wthread and -gthread
2536 2549 for now. They don't really work with standalone WX/GTK code
2537 2550 (though matplotlib IS working fine with both of those backends).
2538 2551 This will neeed much more testing. I disabled most things with
2539 2552 comments, so turning it back on later should be pretty easy.
2540 2553
2541 2554 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
2542 2555 autocalling of expressions like r'foo', by modifying the line
2543 2556 split regexp. Closes
2544 2557 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
2545 2558 Riley <ipythonbugs-AT-sabi.net>.
2546 2559 (InteractiveShell.mainloop): honor --nobanner with banner
2547 2560 extensions.
2548 2561
2549 2562 * IPython/Shell.py: Significant refactoring of all classes, so
2550 2563 that we can really support ALL matplotlib backends and threading
2551 2564 models (John spotted a bug with Tk which required this). Now we
2552 2565 should support single-threaded, WX-threads and GTK-threads, both
2553 2566 for generic code and for matplotlib.
2554 2567
2555 2568 * IPython/ipmaker.py (__call__): Changed -mpthread option to
2556 2569 -pylab, to simplify things for users. Will also remove the pylab
2557 2570 profile, since now all of matplotlib configuration is directly
2558 2571 handled here. This also reduces startup time.
2559 2572
2560 2573 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
2561 2574 shell wasn't being correctly called. Also in IPShellWX.
2562 2575
2563 2576 * IPython/iplib.py (InteractiveShell.__init__): Added option to
2564 2577 fine-tune banner.
2565 2578
2566 2579 * IPython/numutils.py (spike): Deprecate these spike functions,
2567 2580 delete (long deprecated) gnuplot_exec handler.
2568 2581
2569 2582 2004-08-26 Fernando Perez <fperez@colorado.edu>
2570 2583
2571 2584 * ipython.1: Update for threading options, plus some others which
2572 2585 were missing.
2573 2586
2574 2587 * IPython/ipmaker.py (__call__): Added -wthread option for
2575 2588 wxpython thread handling. Make sure threading options are only
2576 2589 valid at the command line.
2577 2590
2578 2591 * scripts/ipython: moved shell selection into a factory function
2579 2592 in Shell.py, to keep the starter script to a minimum.
2580 2593
2581 2594 2004-08-25 Fernando Perez <fperez@colorado.edu>
2582 2595
2583 2596 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
2584 2597 John. Along with some recent changes he made to matplotlib, the
2585 2598 next versions of both systems should work very well together.
2586 2599
2587 2600 2004-08-24 Fernando Perez <fperez@colorado.edu>
2588 2601
2589 2602 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
2590 2603 tried to switch the profiling to using hotshot, but I'm getting
2591 2604 strange errors from prof.runctx() there. I may be misreading the
2592 2605 docs, but it looks weird. For now the profiling code will
2593 2606 continue to use the standard profiler.
2594 2607
2595 2608 2004-08-23 Fernando Perez <fperez@colorado.edu>
2596 2609
2597 2610 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
2598 2611 threaded shell, by John Hunter. It's not quite ready yet, but
2599 2612 close.
2600 2613
2601 2614 2004-08-22 Fernando Perez <fperez@colorado.edu>
2602 2615
2603 2616 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
2604 2617 in Magic and ultraTB.
2605 2618
2606 2619 * ipython.1: document threading options in manpage.
2607 2620
2608 2621 * scripts/ipython: Changed name of -thread option to -gthread,
2609 2622 since this is GTK specific. I want to leave the door open for a
2610 2623 -wthread option for WX, which will most likely be necessary. This
2611 2624 change affects usage and ipmaker as well.
2612 2625
2613 2626 * IPython/Shell.py (matplotlib_shell): Add a factory function to
2614 2627 handle the matplotlib shell issues. Code by John Hunter
2615 2628 <jdhunter-AT-nitace.bsd.uchicago.edu>.
2616 2629 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
2617 2630 broken (and disabled for end users) for now, but it puts the
2618 2631 infrastructure in place.
2619 2632
2620 2633 2004-08-21 Fernando Perez <fperez@colorado.edu>
2621 2634
2622 2635 * ipythonrc-pylab: Add matplotlib support.
2623 2636
2624 2637 * matplotlib_config.py: new files for matplotlib support, part of
2625 2638 the pylab profile.
2626 2639
2627 2640 * IPython/usage.py (__doc__): documented the threading options.
2628 2641
2629 2642 2004-08-20 Fernando Perez <fperez@colorado.edu>
2630 2643
2631 2644 * ipython: Modified the main calling routine to handle the -thread
2632 2645 and -mpthread options. This needs to be done as a top-level hack,
2633 2646 because it determines which class to instantiate for IPython
2634 2647 itself.
2635 2648
2636 2649 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
2637 2650 classes to support multithreaded GTK operation without blocking,
2638 2651 and matplotlib with all backends. This is a lot of still very
2639 2652 experimental code, and threads are tricky. So it may still have a
2640 2653 few rough edges... This code owes a lot to
2641 2654 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
2642 2655 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
2643 2656 to John Hunter for all the matplotlib work.
2644 2657
2645 2658 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
2646 2659 options for gtk thread and matplotlib support.
2647 2660
2648 2661 2004-08-16 Fernando Perez <fperez@colorado.edu>
2649 2662
2650 2663 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
2651 2664 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
2652 2665 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
2653 2666
2654 2667 2004-08-11 Fernando Perez <fperez@colorado.edu>
2655 2668
2656 2669 * setup.py (isfile): Fix build so documentation gets updated for
2657 2670 rpms (it was only done for .tgz builds).
2658 2671
2659 2672 2004-08-10 Fernando Perez <fperez@colorado.edu>
2660 2673
2661 2674 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
2662 2675
2663 2676 * iplib.py : Silence syntax error exceptions in tab-completion.
2664 2677
2665 2678 2004-08-05 Fernando Perez <fperez@colorado.edu>
2666 2679
2667 2680 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
2668 2681 'color off' mark for continuation prompts. This was causing long
2669 2682 continuation lines to mis-wrap.
2670 2683
2671 2684 2004-08-01 Fernando Perez <fperez@colorado.edu>
2672 2685
2673 2686 * IPython/ipmaker.py (make_IPython): Allow the shell class used
2674 2687 for building ipython to be a parameter. All this is necessary
2675 2688 right now to have a multithreaded version, but this insane
2676 2689 non-design will be cleaned up soon. For now, it's a hack that
2677 2690 works.
2678 2691
2679 2692 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
2680 2693 args in various places. No bugs so far, but it's a dangerous
2681 2694 practice.
2682 2695
2683 2696 2004-07-31 Fernando Perez <fperez@colorado.edu>
2684 2697
2685 2698 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
2686 2699 fix completion of files with dots in their names under most
2687 2700 profiles (pysh was OK because the completion order is different).
2688 2701
2689 2702 2004-07-27 Fernando Perez <fperez@colorado.edu>
2690 2703
2691 2704 * IPython/iplib.py (InteractiveShell.__init__): build dict of
2692 2705 keywords manually, b/c the one in keyword.py was removed in python
2693 2706 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
2694 2707 This is NOT a bug under python 2.3 and earlier.
2695 2708
2696 2709 2004-07-26 Fernando Perez <fperez@colorado.edu>
2697 2710
2698 2711 * IPython/ultraTB.py (VerboseTB.text): Add another
2699 2712 linecache.checkcache() call to try to prevent inspect.py from
2700 2713 crashing under python 2.3. I think this fixes
2701 2714 http://www.scipy.net/roundup/ipython/issue17.
2702 2715
2703 2716 2004-07-26 *** Released version 0.6.2
2704 2717
2705 2718 2004-07-26 Fernando Perez <fperez@colorado.edu>
2706 2719
2707 2720 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
2708 2721 fail for any number.
2709 2722 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
2710 2723 empty bookmarks.
2711 2724
2712 2725 2004-07-26 *** Released version 0.6.1
2713 2726
2714 2727 2004-07-26 Fernando Perez <fperez@colorado.edu>
2715 2728
2716 2729 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
2717 2730
2718 2731 * IPython/iplib.py (protect_filename): Applied Ville's patch for
2719 2732 escaping '()[]{}' in filenames.
2720 2733
2721 2734 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
2722 2735 Python 2.2 users who lack a proper shlex.split.
2723 2736
2724 2737 2004-07-19 Fernando Perez <fperez@colorado.edu>
2725 2738
2726 2739 * IPython/iplib.py (InteractiveShell.init_readline): Add support
2727 2740 for reading readline's init file. I follow the normal chain:
2728 2741 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
2729 2742 report by Mike Heeter. This closes
2730 2743 http://www.scipy.net/roundup/ipython/issue16.
2731 2744
2732 2745 2004-07-18 Fernando Perez <fperez@colorado.edu>
2733 2746
2734 2747 * IPython/iplib.py (__init__): Add better handling of '\' under
2735 2748 Win32 for filenames. After a patch by Ville.
2736 2749
2737 2750 2004-07-17 Fernando Perez <fperez@colorado.edu>
2738 2751
2739 2752 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2740 2753 autocalling would be triggered for 'foo is bar' if foo is
2741 2754 callable. I also cleaned up the autocall detection code to use a
2742 2755 regexp, which is faster. Bug reported by Alexander Schmolck.
2743 2756
2744 2757 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
2745 2758 '?' in them would confuse the help system. Reported by Alex
2746 2759 Schmolck.
2747 2760
2748 2761 2004-07-16 Fernando Perez <fperez@colorado.edu>
2749 2762
2750 2763 * IPython/GnuplotInteractive.py (__all__): added plot2.
2751 2764
2752 2765 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
2753 2766 plotting dictionaries, lists or tuples of 1d arrays.
2754 2767
2755 2768 * IPython/Magic.py (Magic.magic_hist): small clenaups and
2756 2769 optimizations.
2757 2770
2758 2771 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
2759 2772 the information which was there from Janko's original IPP code:
2760 2773
2761 2774 03.05.99 20:53 porto.ifm.uni-kiel.de
2762 2775 --Started changelog.
2763 2776 --make clear do what it say it does
2764 2777 --added pretty output of lines from inputcache
2765 2778 --Made Logger a mixin class, simplifies handling of switches
2766 2779 --Added own completer class. .string<TAB> expands to last history
2767 2780 line which starts with string. The new expansion is also present
2768 2781 with Ctrl-r from the readline library. But this shows, who this
2769 2782 can be done for other cases.
2770 2783 --Added convention that all shell functions should accept a
2771 2784 parameter_string This opens the door for different behaviour for
2772 2785 each function. @cd is a good example of this.
2773 2786
2774 2787 04.05.99 12:12 porto.ifm.uni-kiel.de
2775 2788 --added logfile rotation
2776 2789 --added new mainloop method which freezes first the namespace
2777 2790
2778 2791 07.05.99 21:24 porto.ifm.uni-kiel.de
2779 2792 --added the docreader classes. Now there is a help system.
2780 2793 -This is only a first try. Currently it's not easy to put new
2781 2794 stuff in the indices. But this is the way to go. Info would be
2782 2795 better, but HTML is every where and not everybody has an info
2783 2796 system installed and it's not so easy to change html-docs to info.
2784 2797 --added global logfile option
2785 2798 --there is now a hook for object inspection method pinfo needs to
2786 2799 be provided for this. Can be reached by two '??'.
2787 2800
2788 2801 08.05.99 20:51 porto.ifm.uni-kiel.de
2789 2802 --added a README
2790 2803 --bug in rc file. Something has changed so functions in the rc
2791 2804 file need to reference the shell and not self. Not clear if it's a
2792 2805 bug or feature.
2793 2806 --changed rc file for new behavior
2794 2807
2795 2808 2004-07-15 Fernando Perez <fperez@colorado.edu>
2796 2809
2797 2810 * IPython/Logger.py (Logger.log): fixed recent bug where the input
2798 2811 cache was falling out of sync in bizarre manners when multi-line
2799 2812 input was present. Minor optimizations and cleanup.
2800 2813
2801 2814 (Logger): Remove old Changelog info for cleanup. This is the
2802 2815 information which was there from Janko's original code:
2803 2816
2804 2817 Changes to Logger: - made the default log filename a parameter
2805 2818
2806 2819 - put a check for lines beginning with !@? in log(). Needed
2807 2820 (even if the handlers properly log their lines) for mid-session
2808 2821 logging activation to work properly. Without this, lines logged
2809 2822 in mid session, which get read from the cache, would end up
2810 2823 'bare' (with !@? in the open) in the log. Now they are caught
2811 2824 and prepended with a #.
2812 2825
2813 2826 * IPython/iplib.py (InteractiveShell.init_readline): added check
2814 2827 in case MagicCompleter fails to be defined, so we don't crash.
2815 2828
2816 2829 2004-07-13 Fernando Perez <fperez@colorado.edu>
2817 2830
2818 2831 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
2819 2832 of EPS if the requested filename ends in '.eps'.
2820 2833
2821 2834 2004-07-04 Fernando Perez <fperez@colorado.edu>
2822 2835
2823 2836 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
2824 2837 escaping of quotes when calling the shell.
2825 2838
2826 2839 2004-07-02 Fernando Perez <fperez@colorado.edu>
2827 2840
2828 2841 * IPython/Prompts.py (CachedOutput.update): Fix problem with
2829 2842 gettext not working because we were clobbering '_'. Fixes
2830 2843 http://www.scipy.net/roundup/ipython/issue6.
2831 2844
2832 2845 2004-07-01 Fernando Perez <fperez@colorado.edu>
2833 2846
2834 2847 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
2835 2848 into @cd. Patch by Ville.
2836 2849
2837 2850 * IPython/iplib.py (InteractiveShell.post_config_initialization):
2838 2851 new function to store things after ipmaker runs. Patch by Ville.
2839 2852 Eventually this will go away once ipmaker is removed and the class
2840 2853 gets cleaned up, but for now it's ok. Key functionality here is
2841 2854 the addition of the persistent storage mechanism, a dict for
2842 2855 keeping data across sessions (for now just bookmarks, but more can
2843 2856 be implemented later).
2844 2857
2845 2858 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
2846 2859 persistent across sections. Patch by Ville, I modified it
2847 2860 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
2848 2861 added a '-l' option to list all bookmarks.
2849 2862
2850 2863 * IPython/iplib.py (InteractiveShell.atexit_operations): new
2851 2864 center for cleanup. Registered with atexit.register(). I moved
2852 2865 here the old exit_cleanup(). After a patch by Ville.
2853 2866
2854 2867 * IPython/Magic.py (get_py_filename): added '~' to the accepted
2855 2868 characters in the hacked shlex_split for python 2.2.
2856 2869
2857 2870 * IPython/iplib.py (file_matches): more fixes to filenames with
2858 2871 whitespace in them. It's not perfect, but limitations in python's
2859 2872 readline make it impossible to go further.
2860 2873
2861 2874 2004-06-29 Fernando Perez <fperez@colorado.edu>
2862 2875
2863 2876 * IPython/iplib.py (file_matches): escape whitespace correctly in
2864 2877 filename completions. Bug reported by Ville.
2865 2878
2866 2879 2004-06-28 Fernando Perez <fperez@colorado.edu>
2867 2880
2868 2881 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
2869 2882 the history file will be called 'history-PROFNAME' (or just
2870 2883 'history' if no profile is loaded). I was getting annoyed at
2871 2884 getting my Numerical work history clobbered by pysh sessions.
2872 2885
2873 2886 * IPython/iplib.py (InteractiveShell.__init__): Internal
2874 2887 getoutputerror() function so that we can honor the system_verbose
2875 2888 flag for _all_ system calls. I also added escaping of #
2876 2889 characters here to avoid confusing Itpl.
2877 2890
2878 2891 * IPython/Magic.py (shlex_split): removed call to shell in
2879 2892 parse_options and replaced it with shlex.split(). The annoying
2880 2893 part was that in Python 2.2, shlex.split() doesn't exist, so I had
2881 2894 to backport it from 2.3, with several frail hacks (the shlex
2882 2895 module is rather limited in 2.2). Thanks to a suggestion by Ville
2883 2896 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
2884 2897 problem.
2885 2898
2886 2899 (Magic.magic_system_verbose): new toggle to print the actual
2887 2900 system calls made by ipython. Mainly for debugging purposes.
2888 2901
2889 2902 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
2890 2903 doesn't support persistence. Reported (and fix suggested) by
2891 2904 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2892 2905
2893 2906 2004-06-26 Fernando Perez <fperez@colorado.edu>
2894 2907
2895 2908 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2896 2909 continue prompts.
2897 2910
2898 2911 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2899 2912 function (basically a big docstring) and a few more things here to
2900 2913 speedup startup. pysh.py is now very lightweight. We want because
2901 2914 it gets execfile'd, while InterpreterExec gets imported, so
2902 2915 byte-compilation saves time.
2903 2916
2904 2917 2004-06-25 Fernando Perez <fperez@colorado.edu>
2905 2918
2906 2919 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2907 2920 -NUM', which was recently broken.
2908 2921
2909 2922 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2910 2923 in multi-line input (but not !!, which doesn't make sense there).
2911 2924
2912 2925 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2913 2926 It's just too useful, and people can turn it off in the less
2914 2927 common cases where it's a problem.
2915 2928
2916 2929 2004-06-24 Fernando Perez <fperez@colorado.edu>
2917 2930
2918 2931 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2919 2932 special syntaxes (like alias calling) is now allied in multi-line
2920 2933 input. This is still _very_ experimental, but it's necessary for
2921 2934 efficient shell usage combining python looping syntax with system
2922 2935 calls. For now it's restricted to aliases, I don't think it
2923 2936 really even makes sense to have this for magics.
2924 2937
2925 2938 2004-06-23 Fernando Perez <fperez@colorado.edu>
2926 2939
2927 2940 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2928 2941 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2929 2942
2930 2943 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2931 2944 extensions under Windows (after code sent by Gary Bishop). The
2932 2945 extensions considered 'executable' are stored in IPython's rc
2933 2946 structure as win_exec_ext.
2934 2947
2935 2948 * IPython/genutils.py (shell): new function, like system() but
2936 2949 without return value. Very useful for interactive shell work.
2937 2950
2938 2951 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2939 2952 delete aliases.
2940 2953
2941 2954 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2942 2955 sure that the alias table doesn't contain python keywords.
2943 2956
2944 2957 2004-06-21 Fernando Perez <fperez@colorado.edu>
2945 2958
2946 2959 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2947 2960 non-existent items are found in $PATH. Reported by Thorsten.
2948 2961
2949 2962 2004-06-20 Fernando Perez <fperez@colorado.edu>
2950 2963
2951 2964 * IPython/iplib.py (complete): modified the completer so that the
2952 2965 order of priorities can be easily changed at runtime.
2953 2966
2954 2967 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2955 2968 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2956 2969
2957 2970 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2958 2971 expand Python variables prepended with $ in all system calls. The
2959 2972 same was done to InteractiveShell.handle_shell_escape. Now all
2960 2973 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2961 2974 expansion of python variables and expressions according to the
2962 2975 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2963 2976
2964 2977 Though PEP-215 has been rejected, a similar (but simpler) one
2965 2978 seems like it will go into Python 2.4, PEP-292 -
2966 2979 http://www.python.org/peps/pep-0292.html.
2967 2980
2968 2981 I'll keep the full syntax of PEP-215, since IPython has since the
2969 2982 start used Ka-Ping Yee's reference implementation discussed there
2970 2983 (Itpl), and I actually like the powerful semantics it offers.
2971 2984
2972 2985 In order to access normal shell variables, the $ has to be escaped
2973 2986 via an extra $. For example:
2974 2987
2975 2988 In [7]: PATH='a python variable'
2976 2989
2977 2990 In [8]: !echo $PATH
2978 2991 a python variable
2979 2992
2980 2993 In [9]: !echo $$PATH
2981 2994 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2982 2995
2983 2996 (Magic.parse_options): escape $ so the shell doesn't evaluate
2984 2997 things prematurely.
2985 2998
2986 2999 * IPython/iplib.py (InteractiveShell.call_alias): added the
2987 3000 ability for aliases to expand python variables via $.
2988 3001
2989 3002 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2990 3003 system, now there's a @rehash/@rehashx pair of magics. These work
2991 3004 like the csh rehash command, and can be invoked at any time. They
2992 3005 build a table of aliases to everything in the user's $PATH
2993 3006 (@rehash uses everything, @rehashx is slower but only adds
2994 3007 executable files). With this, the pysh.py-based shell profile can
2995 3008 now simply call rehash upon startup, and full access to all
2996 3009 programs in the user's path is obtained.
2997 3010
2998 3011 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2999 3012 functionality is now fully in place. I removed the old dynamic
3000 3013 code generation based approach, in favor of a much lighter one
3001 3014 based on a simple dict. The advantage is that this allows me to
3002 3015 now have thousands of aliases with negligible cost (unthinkable
3003 3016 with the old system).
3004 3017
3005 3018 2004-06-19 Fernando Perez <fperez@colorado.edu>
3006 3019
3007 3020 * IPython/iplib.py (__init__): extended MagicCompleter class to
3008 3021 also complete (last in priority) on user aliases.
3009 3022
3010 3023 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
3011 3024 call to eval.
3012 3025 (ItplNS.__init__): Added a new class which functions like Itpl,
3013 3026 but allows configuring the namespace for the evaluation to occur
3014 3027 in.
3015 3028
3016 3029 2004-06-18 Fernando Perez <fperez@colorado.edu>
3017 3030
3018 3031 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
3019 3032 better message when 'exit' or 'quit' are typed (a common newbie
3020 3033 confusion).
3021 3034
3022 3035 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
3023 3036 check for Windows users.
3024 3037
3025 3038 * IPython/iplib.py (InteractiveShell.user_setup): removed
3026 3039 disabling of colors for Windows. I'll test at runtime and issue a
3027 3040 warning if Gary's readline isn't found, as to nudge users to
3028 3041 download it.
3029 3042
3030 3043 2004-06-16 Fernando Perez <fperez@colorado.edu>
3031 3044
3032 3045 * IPython/genutils.py (Stream.__init__): changed to print errors
3033 3046 to sys.stderr. I had a circular dependency here. Now it's
3034 3047 possible to run ipython as IDLE's shell (consider this pre-alpha,
3035 3048 since true stdout things end up in the starting terminal instead
3036 3049 of IDLE's out).
3037 3050
3038 3051 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
3039 3052 users who haven't # updated their prompt_in2 definitions. Remove
3040 3053 eventually.
3041 3054 (multiple_replace): added credit to original ASPN recipe.
3042 3055
3043 3056 2004-06-15 Fernando Perez <fperez@colorado.edu>
3044 3057
3045 3058 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
3046 3059 list of auto-defined aliases.
3047 3060
3048 3061 2004-06-13 Fernando Perez <fperez@colorado.edu>
3049 3062
3050 3063 * setup.py (scriptfiles): Don't trigger win_post_install unless an
3051 3064 install was really requested (so setup.py can be used for other
3052 3065 things under Windows).
3053 3066
3054 3067 2004-06-10 Fernando Perez <fperez@colorado.edu>
3055 3068
3056 3069 * IPython/Logger.py (Logger.create_log): Manually remove any old
3057 3070 backup, since os.remove may fail under Windows. Fixes bug
3058 3071 reported by Thorsten.
3059 3072
3060 3073 2004-06-09 Fernando Perez <fperez@colorado.edu>
3061 3074
3062 3075 * examples/example-embed.py: fixed all references to %n (replaced
3063 3076 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
3064 3077 for all examples and the manual as well.
3065 3078
3066 3079 2004-06-08 Fernando Perez <fperez@colorado.edu>
3067 3080
3068 3081 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
3069 3082 alignment and color management. All 3 prompt subsystems now
3070 3083 inherit from BasePrompt.
3071 3084
3072 3085 * tools/release: updates for windows installer build and tag rpms
3073 3086 with python version (since paths are fixed).
3074 3087
3075 3088 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
3076 3089 which will become eventually obsolete. Also fixed the default
3077 3090 prompt_in2 to use \D, so at least new users start with the correct
3078 3091 defaults.
3079 3092 WARNING: Users with existing ipythonrc files will need to apply
3080 3093 this fix manually!
3081 3094
3082 3095 * setup.py: make windows installer (.exe). This is finally the
3083 3096 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
3084 3097 which I hadn't included because it required Python 2.3 (or recent
3085 3098 distutils).
3086 3099
3087 3100 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
3088 3101 usage of new '\D' escape.
3089 3102
3090 3103 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
3091 3104 lacks os.getuid())
3092 3105 (CachedOutput.set_colors): Added the ability to turn coloring
3093 3106 on/off with @colors even for manually defined prompt colors. It
3094 3107 uses a nasty global, but it works safely and via the generic color
3095 3108 handling mechanism.
3096 3109 (Prompt2.__init__): Introduced new escape '\D' for continuation
3097 3110 prompts. It represents the counter ('\#') as dots.
3098 3111 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
3099 3112 need to update their ipythonrc files and replace '%n' with '\D' in
3100 3113 their prompt_in2 settings everywhere. Sorry, but there's
3101 3114 otherwise no clean way to get all prompts to properly align. The
3102 3115 ipythonrc shipped with IPython has been updated.
3103 3116
3104 3117 2004-06-07 Fernando Perez <fperez@colorado.edu>
3105 3118
3106 3119 * setup.py (isfile): Pass local_icons option to latex2html, so the
3107 3120 resulting HTML file is self-contained. Thanks to
3108 3121 dryice-AT-liu.com.cn for the tip.
3109 3122
3110 3123 * pysh.py: I created a new profile 'shell', which implements a
3111 3124 _rudimentary_ IPython-based shell. This is in NO WAY a realy
3112 3125 system shell, nor will it become one anytime soon. It's mainly
3113 3126 meant to illustrate the use of the new flexible bash-like prompts.
3114 3127 I guess it could be used by hardy souls for true shell management,
3115 3128 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
3116 3129 profile. This uses the InterpreterExec extension provided by
3117 3130 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
3118 3131
3119 3132 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
3120 3133 auto-align itself with the length of the previous input prompt
3121 3134 (taking into account the invisible color escapes).
3122 3135 (CachedOutput.__init__): Large restructuring of this class. Now
3123 3136 all three prompts (primary1, primary2, output) are proper objects,
3124 3137 managed by the 'parent' CachedOutput class. The code is still a
3125 3138 bit hackish (all prompts share state via a pointer to the cache),
3126 3139 but it's overall far cleaner than before.
3127 3140
3128 3141 * IPython/genutils.py (getoutputerror): modified to add verbose,
3129 3142 debug and header options. This makes the interface of all getout*
3130 3143 functions uniform.
3131 3144 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
3132 3145
3133 3146 * IPython/Magic.py (Magic.default_option): added a function to
3134 3147 allow registering default options for any magic command. This
3135 3148 makes it easy to have profiles which customize the magics globally
3136 3149 for a certain use. The values set through this function are
3137 3150 picked up by the parse_options() method, which all magics should
3138 3151 use to parse their options.
3139 3152
3140 3153 * IPython/genutils.py (warn): modified the warnings framework to
3141 3154 use the Term I/O class. I'm trying to slowly unify all of
3142 3155 IPython's I/O operations to pass through Term.
3143 3156
3144 3157 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
3145 3158 the secondary prompt to correctly match the length of the primary
3146 3159 one for any prompt. Now multi-line code will properly line up
3147 3160 even for path dependent prompts, such as the new ones available
3148 3161 via the prompt_specials.
3149 3162
3150 3163 2004-06-06 Fernando Perez <fperez@colorado.edu>
3151 3164
3152 3165 * IPython/Prompts.py (prompt_specials): Added the ability to have
3153 3166 bash-like special sequences in the prompts, which get
3154 3167 automatically expanded. Things like hostname, current working
3155 3168 directory and username are implemented already, but it's easy to
3156 3169 add more in the future. Thanks to a patch by W.J. van der Laan
3157 3170 <gnufnork-AT-hetdigitalegat.nl>
3158 3171 (prompt_specials): Added color support for prompt strings, so
3159 3172 users can define arbitrary color setups for their prompts.
3160 3173
3161 3174 2004-06-05 Fernando Perez <fperez@colorado.edu>
3162 3175
3163 3176 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
3164 3177 code to load Gary Bishop's readline and configure it
3165 3178 automatically. Thanks to Gary for help on this.
3166 3179
3167 3180 2004-06-01 Fernando Perez <fperez@colorado.edu>
3168 3181
3169 3182 * IPython/Logger.py (Logger.create_log): fix bug for logging
3170 3183 with no filename (previous fix was incomplete).
3171 3184
3172 3185 2004-05-25 Fernando Perez <fperez@colorado.edu>
3173 3186
3174 3187 * IPython/Magic.py (Magic.parse_options): fix bug where naked
3175 3188 parens would get passed to the shell.
3176 3189
3177 3190 2004-05-20 Fernando Perez <fperez@colorado.edu>
3178 3191
3179 3192 * IPython/Magic.py (Magic.magic_prun): changed default profile
3180 3193 sort order to 'time' (the more common profiling need).
3181 3194
3182 3195 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
3183 3196 so that source code shown is guaranteed in sync with the file on
3184 3197 disk (also changed in psource). Similar fix to the one for
3185 3198 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
3186 3199 <yann.ledu-AT-noos.fr>.
3187 3200
3188 3201 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
3189 3202 with a single option would not be correctly parsed. Closes
3190 3203 http://www.scipy.net/roundup/ipython/issue14. This bug had been
3191 3204 introduced in 0.6.0 (on 2004-05-06).
3192 3205
3193 3206 2004-05-13 *** Released version 0.6.0
3194 3207
3195 3208 2004-05-13 Fernando Perez <fperez@colorado.edu>
3196 3209
3197 3210 * debian/: Added debian/ directory to CVS, so that debian support
3198 3211 is publicly accessible. The debian package is maintained by Jack
3199 3212 Moffit <jack-AT-xiph.org>.
3200 3213
3201 3214 * Documentation: included the notes about an ipython-based system
3202 3215 shell (the hypothetical 'pysh') into the new_design.pdf document,
3203 3216 so that these ideas get distributed to users along with the
3204 3217 official documentation.
3205 3218
3206 3219 2004-05-10 Fernando Perez <fperez@colorado.edu>
3207 3220
3208 3221 * IPython/Logger.py (Logger.create_log): fix recently introduced
3209 3222 bug (misindented line) where logstart would fail when not given an
3210 3223 explicit filename.
3211 3224
3212 3225 2004-05-09 Fernando Perez <fperez@colorado.edu>
3213 3226
3214 3227 * IPython/Magic.py (Magic.parse_options): skip system call when
3215 3228 there are no options to look for. Faster, cleaner for the common
3216 3229 case.
3217 3230
3218 3231 * Documentation: many updates to the manual: describing Windows
3219 3232 support better, Gnuplot updates, credits, misc small stuff. Also
3220 3233 updated the new_design doc a bit.
3221 3234
3222 3235 2004-05-06 *** Released version 0.6.0.rc1
3223 3236
3224 3237 2004-05-06 Fernando Perez <fperez@colorado.edu>
3225 3238
3226 3239 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
3227 3240 operations to use the vastly more efficient list/''.join() method.
3228 3241 (FormattedTB.text): Fix
3229 3242 http://www.scipy.net/roundup/ipython/issue12 - exception source
3230 3243 extract not updated after reload. Thanks to Mike Salib
3231 3244 <msalib-AT-mit.edu> for pinning the source of the problem.
3232 3245 Fortunately, the solution works inside ipython and doesn't require
3233 3246 any changes to python proper.
3234 3247
3235 3248 * IPython/Magic.py (Magic.parse_options): Improved to process the
3236 3249 argument list as a true shell would (by actually using the
3237 3250 underlying system shell). This way, all @magics automatically get
3238 3251 shell expansion for variables. Thanks to a comment by Alex
3239 3252 Schmolck.
3240 3253
3241 3254 2004-04-04 Fernando Perez <fperez@colorado.edu>
3242 3255
3243 3256 * IPython/iplib.py (InteractiveShell.interact): Added a special
3244 3257 trap for a debugger quit exception, which is basically impossible
3245 3258 to handle by normal mechanisms, given what pdb does to the stack.
3246 3259 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
3247 3260
3248 3261 2004-04-03 Fernando Perez <fperez@colorado.edu>
3249 3262
3250 3263 * IPython/genutils.py (Term): Standardized the names of the Term
3251 3264 class streams to cin/cout/cerr, following C++ naming conventions
3252 3265 (I can't use in/out/err because 'in' is not a valid attribute
3253 3266 name).
3254 3267
3255 3268 * IPython/iplib.py (InteractiveShell.interact): don't increment
3256 3269 the prompt if there's no user input. By Daniel 'Dang' Griffith
3257 3270 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
3258 3271 Francois Pinard.
3259 3272
3260 3273 2004-04-02 Fernando Perez <fperez@colorado.edu>
3261 3274
3262 3275 * IPython/genutils.py (Stream.__init__): Modified to survive at
3263 3276 least importing in contexts where stdin/out/err aren't true file
3264 3277 objects, such as PyCrust (they lack fileno() and mode). However,
3265 3278 the recovery facilities which rely on these things existing will
3266 3279 not work.
3267 3280
3268 3281 2004-04-01 Fernando Perez <fperez@colorado.edu>
3269 3282
3270 3283 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
3271 3284 use the new getoutputerror() function, so it properly
3272 3285 distinguishes stdout/err.
3273 3286
3274 3287 * IPython/genutils.py (getoutputerror): added a function to
3275 3288 capture separately the standard output and error of a command.
3276 3289 After a comment from dang on the mailing lists. This code is
3277 3290 basically a modified version of commands.getstatusoutput(), from
3278 3291 the standard library.
3279 3292
3280 3293 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
3281 3294 '!!' as a special syntax (shorthand) to access @sx.
3282 3295
3283 3296 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
3284 3297 command and return its output as a list split on '\n'.
3285 3298
3286 3299 2004-03-31 Fernando Perez <fperez@colorado.edu>
3287 3300
3288 3301 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
3289 3302 method to dictionaries used as FakeModule instances if they lack
3290 3303 it. At least pydoc in python2.3 breaks for runtime-defined
3291 3304 functions without this hack. At some point I need to _really_
3292 3305 understand what FakeModule is doing, because it's a gross hack.
3293 3306 But it solves Arnd's problem for now...
3294 3307
3295 3308 2004-02-27 Fernando Perez <fperez@colorado.edu>
3296 3309
3297 3310 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
3298 3311 mode would behave erratically. Also increased the number of
3299 3312 possible logs in rotate mod to 999. Thanks to Rod Holland
3300 3313 <rhh@StructureLABS.com> for the report and fixes.
3301 3314
3302 3315 2004-02-26 Fernando Perez <fperez@colorado.edu>
3303 3316
3304 3317 * IPython/genutils.py (page): Check that the curses module really
3305 3318 has the initscr attribute before trying to use it. For some
3306 3319 reason, the Solaris curses module is missing this. I think this
3307 3320 should be considered a Solaris python bug, but I'm not sure.
3308 3321
3309 3322 2004-01-17 Fernando Perez <fperez@colorado.edu>
3310 3323
3311 3324 * IPython/genutils.py (Stream.__init__): Changes to try to make
3312 3325 ipython robust against stdin/out/err being closed by the user.
3313 3326 This is 'user error' (and blocks a normal python session, at least
3314 3327 the stdout case). However, Ipython should be able to survive such
3315 3328 instances of abuse as gracefully as possible. To simplify the
3316 3329 coding and maintain compatibility with Gary Bishop's Term
3317 3330 contributions, I've made use of classmethods for this. I think
3318 3331 this introduces a dependency on python 2.2.
3319 3332
3320 3333 2004-01-13 Fernando Perez <fperez@colorado.edu>
3321 3334
3322 3335 * IPython/numutils.py (exp_safe): simplified the code a bit and
3323 3336 removed the need for importing the kinds module altogether.
3324 3337
3325 3338 2004-01-06 Fernando Perez <fperez@colorado.edu>
3326 3339
3327 3340 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
3328 3341 a magic function instead, after some community feedback. No
3329 3342 special syntax will exist for it, but its name is deliberately
3330 3343 very short.
3331 3344
3332 3345 2003-12-20 Fernando Perez <fperez@colorado.edu>
3333 3346
3334 3347 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
3335 3348 new functionality, to automagically assign the result of a shell
3336 3349 command to a variable. I'll solicit some community feedback on
3337 3350 this before making it permanent.
3338 3351
3339 3352 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
3340 3353 requested about callables for which inspect couldn't obtain a
3341 3354 proper argspec. Thanks to a crash report sent by Etienne
3342 3355 Posthumus <etienne-AT-apple01.cs.vu.nl>.
3343 3356
3344 3357 2003-12-09 Fernando Perez <fperez@colorado.edu>
3345 3358
3346 3359 * IPython/genutils.py (page): patch for the pager to work across
3347 3360 various versions of Windows. By Gary Bishop.
3348 3361
3349 3362 2003-12-04 Fernando Perez <fperez@colorado.edu>
3350 3363
3351 3364 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
3352 3365 Gnuplot.py version 1.7, whose internal names changed quite a bit.
3353 3366 While I tested this and it looks ok, there may still be corner
3354 3367 cases I've missed.
3355 3368
3356 3369 2003-12-01 Fernando Perez <fperez@colorado.edu>
3357 3370
3358 3371 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
3359 3372 where a line like 'p,q=1,2' would fail because the automagic
3360 3373 system would be triggered for @p.
3361 3374
3362 3375 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
3363 3376 cleanups, code unmodified.
3364 3377
3365 3378 * IPython/genutils.py (Term): added a class for IPython to handle
3366 3379 output. In most cases it will just be a proxy for stdout/err, but
3367 3380 having this allows modifications to be made for some platforms,
3368 3381 such as handling color escapes under Windows. All of this code
3369 3382 was contributed by Gary Bishop, with minor modifications by me.
3370 3383 The actual changes affect many files.
3371 3384
3372 3385 2003-11-30 Fernando Perez <fperez@colorado.edu>
3373 3386
3374 3387 * IPython/iplib.py (file_matches): new completion code, courtesy
3375 3388 of Jeff Collins. This enables filename completion again under
3376 3389 python 2.3, which disabled it at the C level.
3377 3390
3378 3391 2003-11-11 Fernando Perez <fperez@colorado.edu>
3379 3392
3380 3393 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
3381 3394 for Numeric.array(map(...)), but often convenient.
3382 3395
3383 3396 2003-11-05 Fernando Perez <fperez@colorado.edu>
3384 3397
3385 3398 * IPython/numutils.py (frange): Changed a call from int() to
3386 3399 int(round()) to prevent a problem reported with arange() in the
3387 3400 numpy list.
3388 3401
3389 3402 2003-10-06 Fernando Perez <fperez@colorado.edu>
3390 3403
3391 3404 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
3392 3405 prevent crashes if sys lacks an argv attribute (it happens with
3393 3406 embedded interpreters which build a bare-bones sys module).
3394 3407 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
3395 3408
3396 3409 2003-09-24 Fernando Perez <fperez@colorado.edu>
3397 3410
3398 3411 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
3399 3412 to protect against poorly written user objects where __getattr__
3400 3413 raises exceptions other than AttributeError. Thanks to a bug
3401 3414 report by Oliver Sander <osander-AT-gmx.de>.
3402 3415
3403 3416 * IPython/FakeModule.py (FakeModule.__repr__): this method was
3404 3417 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
3405 3418
3406 3419 2003-09-09 Fernando Perez <fperez@colorado.edu>
3407 3420
3408 3421 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
3409 3422 unpacking a list whith a callable as first element would
3410 3423 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
3411 3424 Collins.
3412 3425
3413 3426 2003-08-25 *** Released version 0.5.0
3414 3427
3415 3428 2003-08-22 Fernando Perez <fperez@colorado.edu>
3416 3429
3417 3430 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
3418 3431 improperly defined user exceptions. Thanks to feedback from Mark
3419 3432 Russell <mrussell-AT-verio.net>.
3420 3433
3421 3434 2003-08-20 Fernando Perez <fperez@colorado.edu>
3422 3435
3423 3436 * IPython/OInspect.py (Inspector.pinfo): changed String Form
3424 3437 printing so that it would print multi-line string forms starting
3425 3438 with a new line. This way the formatting is better respected for
3426 3439 objects which work hard to make nice string forms.
3427 3440
3428 3441 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
3429 3442 autocall would overtake data access for objects with both
3430 3443 __getitem__ and __call__.
3431 3444
3432 3445 2003-08-19 *** Released version 0.5.0-rc1
3433 3446
3434 3447 2003-08-19 Fernando Perez <fperez@colorado.edu>
3435 3448
3436 3449 * IPython/deep_reload.py (load_tail): single tiny change here
3437 3450 seems to fix the long-standing bug of dreload() failing to work
3438 3451 for dotted names. But this module is pretty tricky, so I may have
3439 3452 missed some subtlety. Needs more testing!.
3440 3453
3441 3454 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
3442 3455 exceptions which have badly implemented __str__ methods.
3443 3456 (VerboseTB.text): harden against inspect.getinnerframes crashing,
3444 3457 which I've been getting reports about from Python 2.3 users. I
3445 3458 wish I had a simple test case to reproduce the problem, so I could
3446 3459 either write a cleaner workaround or file a bug report if
3447 3460 necessary.
3448 3461
3449 3462 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
3450 3463 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
3451 3464 a bug report by Tjabo Kloppenburg.
3452 3465
3453 3466 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
3454 3467 crashes. Wrapped the pdb call in a blanket try/except, since pdb
3455 3468 seems rather unstable. Thanks to a bug report by Tjabo
3456 3469 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
3457 3470
3458 3471 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
3459 3472 this out soon because of the critical fixes in the inner loop for
3460 3473 generators.
3461 3474
3462 3475 * IPython/Magic.py (Magic.getargspec): removed. This (and
3463 3476 _get_def) have been obsoleted by OInspect for a long time, I
3464 3477 hadn't noticed that they were dead code.
3465 3478 (Magic._ofind): restored _ofind functionality for a few literals
3466 3479 (those in ["''",'""','[]','{}','()']). But it won't work anymore
3467 3480 for things like "hello".capitalize?, since that would require a
3468 3481 potentially dangerous eval() again.
3469 3482
3470 3483 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
3471 3484 logic a bit more to clean up the escapes handling and minimize the
3472 3485 use of _ofind to only necessary cases. The interactive 'feel' of
3473 3486 IPython should have improved quite a bit with the changes in
3474 3487 _prefilter and _ofind (besides being far safer than before).
3475 3488
3476 3489 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
3477 3490 obscure, never reported). Edit would fail to find the object to
3478 3491 edit under some circumstances.
3479 3492 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
3480 3493 which were causing double-calling of generators. Those eval calls
3481 3494 were _very_ dangerous, since code with side effects could be
3482 3495 triggered. As they say, 'eval is evil'... These were the
3483 3496 nastiest evals in IPython. Besides, _ofind is now far simpler,
3484 3497 and it should also be quite a bit faster. Its use of inspect is
3485 3498 also safer, so perhaps some of the inspect-related crashes I've
3486 3499 seen lately with Python 2.3 might be taken care of. That will
3487 3500 need more testing.
3488 3501
3489 3502 2003-08-17 Fernando Perez <fperez@colorado.edu>
3490 3503
3491 3504 * IPython/iplib.py (InteractiveShell._prefilter): significant
3492 3505 simplifications to the logic for handling user escapes. Faster
3493 3506 and simpler code.
3494 3507
3495 3508 2003-08-14 Fernando Perez <fperez@colorado.edu>
3496 3509
3497 3510 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
3498 3511 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
3499 3512 but it should be quite a bit faster. And the recursive version
3500 3513 generated O(log N) intermediate storage for all rank>1 arrays,
3501 3514 even if they were contiguous.
3502 3515 (l1norm): Added this function.
3503 3516 (norm): Added this function for arbitrary norms (including
3504 3517 l-infinity). l1 and l2 are still special cases for convenience
3505 3518 and speed.
3506 3519
3507 3520 2003-08-03 Fernando Perez <fperez@colorado.edu>
3508 3521
3509 3522 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
3510 3523 exceptions, which now raise PendingDeprecationWarnings in Python
3511 3524 2.3. There were some in Magic and some in Gnuplot2.
3512 3525
3513 3526 2003-06-30 Fernando Perez <fperez@colorado.edu>
3514 3527
3515 3528 * IPython/genutils.py (page): modified to call curses only for
3516 3529 terminals where TERM=='xterm'. After problems under many other
3517 3530 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
3518 3531
3519 3532 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
3520 3533 would be triggered when readline was absent. This was just an old
3521 3534 debugging statement I'd forgotten to take out.
3522 3535
3523 3536 2003-06-20 Fernando Perez <fperez@colorado.edu>
3524 3537
3525 3538 * IPython/genutils.py (clock): modified to return only user time
3526 3539 (not counting system time), after a discussion on scipy. While
3527 3540 system time may be a useful quantity occasionally, it may much
3528 3541 more easily be skewed by occasional swapping or other similar
3529 3542 activity.
3530 3543
3531 3544 2003-06-05 Fernando Perez <fperez@colorado.edu>
3532 3545
3533 3546 * IPython/numutils.py (identity): new function, for building
3534 3547 arbitrary rank Kronecker deltas (mostly backwards compatible with
3535 3548 Numeric.identity)
3536 3549
3537 3550 2003-06-03 Fernando Perez <fperez@colorado.edu>
3538 3551
3539 3552 * IPython/iplib.py (InteractiveShell.handle_magic): protect
3540 3553 arguments passed to magics with spaces, to allow trailing '\' to
3541 3554 work normally (mainly for Windows users).
3542 3555
3543 3556 2003-05-29 Fernando Perez <fperez@colorado.edu>
3544 3557
3545 3558 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
3546 3559 instead of pydoc.help. This fixes a bizarre behavior where
3547 3560 printing '%s' % locals() would trigger the help system. Now
3548 3561 ipython behaves like normal python does.
3549 3562
3550 3563 Note that if one does 'from pydoc import help', the bizarre
3551 3564 behavior returns, but this will also happen in normal python, so
3552 3565 it's not an ipython bug anymore (it has to do with how pydoc.help
3553 3566 is implemented).
3554 3567
3555 3568 2003-05-22 Fernando Perez <fperez@colorado.edu>
3556 3569
3557 3570 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
3558 3571 return [] instead of None when nothing matches, also match to end
3559 3572 of line. Patch by Gary Bishop.
3560 3573
3561 3574 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
3562 3575 protection as before, for files passed on the command line. This
3563 3576 prevents the CrashHandler from kicking in if user files call into
3564 3577 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
3565 3578 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
3566 3579
3567 3580 2003-05-20 *** Released version 0.4.0
3568 3581
3569 3582 2003-05-20 Fernando Perez <fperez@colorado.edu>
3570 3583
3571 3584 * setup.py: added support for manpages. It's a bit hackish b/c of
3572 3585 a bug in the way the bdist_rpm distutils target handles gzipped
3573 3586 manpages, but it works. After a patch by Jack.
3574 3587
3575 3588 2003-05-19 Fernando Perez <fperez@colorado.edu>
3576 3589
3577 3590 * IPython/numutils.py: added a mockup of the kinds module, since
3578 3591 it was recently removed from Numeric. This way, numutils will
3579 3592 work for all users even if they are missing kinds.
3580 3593
3581 3594 * IPython/Magic.py (Magic._ofind): Harden against an inspect
3582 3595 failure, which can occur with SWIG-wrapped extensions. After a
3583 3596 crash report from Prabhu.
3584 3597
3585 3598 2003-05-16 Fernando Perez <fperez@colorado.edu>
3586 3599
3587 3600 * IPython/iplib.py (InteractiveShell.excepthook): New method to
3588 3601 protect ipython from user code which may call directly
3589 3602 sys.excepthook (this looks like an ipython crash to the user, even
3590 3603 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3591 3604 This is especially important to help users of WxWindows, but may
3592 3605 also be useful in other cases.
3593 3606
3594 3607 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
3595 3608 an optional tb_offset to be specified, and to preserve exception
3596 3609 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3597 3610
3598 3611 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
3599 3612
3600 3613 2003-05-15 Fernando Perez <fperez@colorado.edu>
3601 3614
3602 3615 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
3603 3616 installing for a new user under Windows.
3604 3617
3605 3618 2003-05-12 Fernando Perez <fperez@colorado.edu>
3606 3619
3607 3620 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
3608 3621 handler for Emacs comint-based lines. Currently it doesn't do
3609 3622 much (but importantly, it doesn't update the history cache). In
3610 3623 the future it may be expanded if Alex needs more functionality
3611 3624 there.
3612 3625
3613 3626 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
3614 3627 info to crash reports.
3615 3628
3616 3629 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
3617 3630 just like Python's -c. Also fixed crash with invalid -color
3618 3631 option value at startup. Thanks to Will French
3619 3632 <wfrench-AT-bestweb.net> for the bug report.
3620 3633
3621 3634 2003-05-09 Fernando Perez <fperez@colorado.edu>
3622 3635
3623 3636 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
3624 3637 to EvalDict (it's a mapping, after all) and simplified its code
3625 3638 quite a bit, after a nice discussion on c.l.py where Gustavo
3626 3639 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
3627 3640
3628 3641 2003-04-30 Fernando Perez <fperez@colorado.edu>
3629 3642
3630 3643 * IPython/genutils.py (timings_out): modified it to reduce its
3631 3644 overhead in the common reps==1 case.
3632 3645
3633 3646 2003-04-29 Fernando Perez <fperez@colorado.edu>
3634 3647
3635 3648 * IPython/genutils.py (timings_out): Modified to use the resource
3636 3649 module, which avoids the wraparound problems of time.clock().
3637 3650
3638 3651 2003-04-17 *** Released version 0.2.15pre4
3639 3652
3640 3653 2003-04-17 Fernando Perez <fperez@colorado.edu>
3641 3654
3642 3655 * setup.py (scriptfiles): Split windows-specific stuff over to a
3643 3656 separate file, in an attempt to have a Windows GUI installer.
3644 3657 That didn't work, but part of the groundwork is done.
3645 3658
3646 3659 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
3647 3660 indent/unindent with 4 spaces. Particularly useful in combination
3648 3661 with the new auto-indent option.
3649 3662
3650 3663 2003-04-16 Fernando Perez <fperez@colorado.edu>
3651 3664
3652 3665 * IPython/Magic.py: various replacements of self.rc for
3653 3666 self.shell.rc. A lot more remains to be done to fully disentangle
3654 3667 this class from the main Shell class.
3655 3668
3656 3669 * IPython/GnuplotRuntime.py: added checks for mouse support so
3657 3670 that we don't try to enable it if the current gnuplot doesn't
3658 3671 really support it. Also added checks so that we don't try to
3659 3672 enable persist under Windows (where Gnuplot doesn't recognize the
3660 3673 option).
3661 3674
3662 3675 * IPython/iplib.py (InteractiveShell.interact): Added optional
3663 3676 auto-indenting code, after a patch by King C. Shu
3664 3677 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
3665 3678 get along well with pasting indented code. If I ever figure out
3666 3679 how to make that part go well, it will become on by default.
3667 3680
3668 3681 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
3669 3682 crash ipython if there was an unmatched '%' in the user's prompt
3670 3683 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3671 3684
3672 3685 * IPython/iplib.py (InteractiveShell.interact): removed the
3673 3686 ability to ask the user whether he wants to crash or not at the
3674 3687 'last line' exception handler. Calling functions at that point
3675 3688 changes the stack, and the error reports would have incorrect
3676 3689 tracebacks.
3677 3690
3678 3691 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
3679 3692 pass through a peger a pretty-printed form of any object. After a
3680 3693 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
3681 3694
3682 3695 2003-04-14 Fernando Perez <fperez@colorado.edu>
3683 3696
3684 3697 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
3685 3698 all files in ~ would be modified at first install (instead of
3686 3699 ~/.ipython). This could be potentially disastrous, as the
3687 3700 modification (make line-endings native) could damage binary files.
3688 3701
3689 3702 2003-04-10 Fernando Perez <fperez@colorado.edu>
3690 3703
3691 3704 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
3692 3705 handle only lines which are invalid python. This now means that
3693 3706 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
3694 3707 for the bug report.
3695 3708
3696 3709 2003-04-01 Fernando Perez <fperez@colorado.edu>
3697 3710
3698 3711 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
3699 3712 where failing to set sys.last_traceback would crash pdb.pm().
3700 3713 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
3701 3714 report.
3702 3715
3703 3716 2003-03-25 Fernando Perez <fperez@colorado.edu>
3704 3717
3705 3718 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
3706 3719 before printing it (it had a lot of spurious blank lines at the
3707 3720 end).
3708 3721
3709 3722 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
3710 3723 output would be sent 21 times! Obviously people don't use this
3711 3724 too often, or I would have heard about it.
3712 3725
3713 3726 2003-03-24 Fernando Perez <fperez@colorado.edu>
3714 3727
3715 3728 * setup.py (scriptfiles): renamed the data_files parameter from
3716 3729 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
3717 3730 for the patch.
3718 3731
3719 3732 2003-03-20 Fernando Perez <fperez@colorado.edu>
3720 3733
3721 3734 * IPython/genutils.py (error): added error() and fatal()
3722 3735 functions.
3723 3736
3724 3737 2003-03-18 *** Released version 0.2.15pre3
3725 3738
3726 3739 2003-03-18 Fernando Perez <fperez@colorado.edu>
3727 3740
3728 3741 * setupext/install_data_ext.py
3729 3742 (install_data_ext.initialize_options): Class contributed by Jack
3730 3743 Moffit for fixing the old distutils hack. He is sending this to
3731 3744 the distutils folks so in the future we may not need it as a
3732 3745 private fix.
3733 3746
3734 3747 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
3735 3748 changes for Debian packaging. See his patch for full details.
3736 3749 The old distutils hack of making the ipythonrc* files carry a
3737 3750 bogus .py extension is gone, at last. Examples were moved to a
3738 3751 separate subdir under doc/, and the separate executable scripts
3739 3752 now live in their own directory. Overall a great cleanup. The
3740 3753 manual was updated to use the new files, and setup.py has been
3741 3754 fixed for this setup.
3742 3755
3743 3756 * IPython/PyColorize.py (Parser.usage): made non-executable and
3744 3757 created a pycolor wrapper around it to be included as a script.
3745 3758
3746 3759 2003-03-12 *** Released version 0.2.15pre2
3747 3760
3748 3761 2003-03-12 Fernando Perez <fperez@colorado.edu>
3749 3762
3750 3763 * IPython/ColorANSI.py (make_color_table): Finally fixed the
3751 3764 long-standing problem with garbage characters in some terminals.
3752 3765 The issue was really that the \001 and \002 escapes must _only_ be
3753 3766 passed to input prompts (which call readline), but _never_ to
3754 3767 normal text to be printed on screen. I changed ColorANSI to have
3755 3768 two classes: TermColors and InputTermColors, each with the
3756 3769 appropriate escapes for input prompts or normal text. The code in
3757 3770 Prompts.py got slightly more complicated, but this very old and
3758 3771 annoying bug is finally fixed.
3759 3772
3760 3773 All the credit for nailing down the real origin of this problem
3761 3774 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
3762 3775 *Many* thanks to him for spending quite a bit of effort on this.
3763 3776
3764 3777 2003-03-05 *** Released version 0.2.15pre1
3765 3778
3766 3779 2003-03-03 Fernando Perez <fperez@colorado.edu>
3767 3780
3768 3781 * IPython/FakeModule.py: Moved the former _FakeModule to a
3769 3782 separate file, because it's also needed by Magic (to fix a similar
3770 3783 pickle-related issue in @run).
3771 3784
3772 3785 2003-03-02 Fernando Perez <fperez@colorado.edu>
3773 3786
3774 3787 * IPython/Magic.py (Magic.magic_autocall): new magic to control
3775 3788 the autocall option at runtime.
3776 3789 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
3777 3790 across Magic.py to start separating Magic from InteractiveShell.
3778 3791 (Magic._ofind): Fixed to return proper namespace for dotted
3779 3792 names. Before, a dotted name would always return 'not currently
3780 3793 defined', because it would find the 'parent'. s.x would be found,
3781 3794 but since 'x' isn't defined by itself, it would get confused.
3782 3795 (Magic.magic_run): Fixed pickling problems reported by Ralf
3783 3796 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
3784 3797 that I'd used when Mike Heeter reported similar issues at the
3785 3798 top-level, but now for @run. It boils down to injecting the
3786 3799 namespace where code is being executed with something that looks
3787 3800 enough like a module to fool pickle.dump(). Since a pickle stores
3788 3801 a named reference to the importing module, we need this for
3789 3802 pickles to save something sensible.
3790 3803
3791 3804 * IPython/ipmaker.py (make_IPython): added an autocall option.
3792 3805
3793 3806 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
3794 3807 the auto-eval code. Now autocalling is an option, and the code is
3795 3808 also vastly safer. There is no more eval() involved at all.
3796 3809
3797 3810 2003-03-01 Fernando Perez <fperez@colorado.edu>
3798 3811
3799 3812 * IPython/Magic.py (Magic._ofind): Changed interface to return a
3800 3813 dict with named keys instead of a tuple.
3801 3814
3802 3815 * IPython: Started using CVS for IPython as of 0.2.15pre1.
3803 3816
3804 3817 * setup.py (make_shortcut): Fixed message about directories
3805 3818 created during Windows installation (the directories were ok, just
3806 3819 the printed message was misleading). Thanks to Chris Liechti
3807 3820 <cliechti-AT-gmx.net> for the heads up.
3808 3821
3809 3822 2003-02-21 Fernando Perez <fperez@colorado.edu>
3810 3823
3811 3824 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
3812 3825 of ValueError exception when checking for auto-execution. This
3813 3826 one is raised by things like Numeric arrays arr.flat when the
3814 3827 array is non-contiguous.
3815 3828
3816 3829 2003-01-31 Fernando Perez <fperez@colorado.edu>
3817 3830
3818 3831 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
3819 3832 not return any value at all (even though the command would get
3820 3833 executed).
3821 3834 (xsys): Flush stdout right after printing the command to ensure
3822 3835 proper ordering of commands and command output in the total
3823 3836 output.
3824 3837 (SystemExec/xsys/bq): Switched the names of xsys/bq and
3825 3838 system/getoutput as defaults. The old ones are kept for
3826 3839 compatibility reasons, so no code which uses this library needs
3827 3840 changing.
3828 3841
3829 3842 2003-01-27 *** Released version 0.2.14
3830 3843
3831 3844 2003-01-25 Fernando Perez <fperez@colorado.edu>
3832 3845
3833 3846 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
3834 3847 functions defined in previous edit sessions could not be re-edited
3835 3848 (because the temp files were immediately removed). Now temp files
3836 3849 are removed only at IPython's exit.
3837 3850 (Magic.magic_run): Improved @run to perform shell-like expansions
3838 3851 on its arguments (~users and $VARS). With this, @run becomes more
3839 3852 like a normal command-line.
3840 3853
3841 3854 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
3842 3855 bugs related to embedding and cleaned up that code. A fairly
3843 3856 important one was the impossibility to access the global namespace
3844 3857 through the embedded IPython (only local variables were visible).
3845 3858
3846 3859 2003-01-14 Fernando Perez <fperez@colorado.edu>
3847 3860
3848 3861 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
3849 3862 auto-calling to be a bit more conservative. Now it doesn't get
3850 3863 triggered if any of '!=()<>' are in the rest of the input line, to
3851 3864 allow comparing callables. Thanks to Alex for the heads up.
3852 3865
3853 3866 2003-01-07 Fernando Perez <fperez@colorado.edu>
3854 3867
3855 3868 * IPython/genutils.py (page): fixed estimation of the number of
3856 3869 lines in a string to be paged to simply count newlines. This
3857 3870 prevents over-guessing due to embedded escape sequences. A better
3858 3871 long-term solution would involve stripping out the control chars
3859 3872 for the count, but it's potentially so expensive I just don't
3860 3873 think it's worth doing.
3861 3874
3862 3875 2002-12-19 *** Released version 0.2.14pre50
3863 3876
3864 3877 2002-12-19 Fernando Perez <fperez@colorado.edu>
3865 3878
3866 3879 * tools/release (version): Changed release scripts to inform
3867 3880 Andrea and build a NEWS file with a list of recent changes.
3868 3881
3869 3882 * IPython/ColorANSI.py (__all__): changed terminal detection
3870 3883 code. Seems to work better for xterms without breaking
3871 3884 konsole. Will need more testing to determine if WinXP and Mac OSX
3872 3885 also work ok.
3873 3886
3874 3887 2002-12-18 *** Released version 0.2.14pre49
3875 3888
3876 3889 2002-12-18 Fernando Perez <fperez@colorado.edu>
3877 3890
3878 3891 * Docs: added new info about Mac OSX, from Andrea.
3879 3892
3880 3893 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
3881 3894 allow direct plotting of python strings whose format is the same
3882 3895 of gnuplot data files.
3883 3896
3884 3897 2002-12-16 Fernando Perez <fperez@colorado.edu>
3885 3898
3886 3899 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
3887 3900 value of exit question to be acknowledged.
3888 3901
3889 3902 2002-12-03 Fernando Perez <fperez@colorado.edu>
3890 3903
3891 3904 * IPython/ipmaker.py: removed generators, which had been added
3892 3905 by mistake in an earlier debugging run. This was causing trouble
3893 3906 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3894 3907 for pointing this out.
3895 3908
3896 3909 2002-11-17 Fernando Perez <fperez@colorado.edu>
3897 3910
3898 3911 * Manual: updated the Gnuplot section.
3899 3912
3900 3913 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3901 3914 a much better split of what goes in Runtime and what goes in
3902 3915 Interactive.
3903 3916
3904 3917 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3905 3918 being imported from iplib.
3906 3919
3907 3920 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3908 3921 for command-passing. Now the global Gnuplot instance is called
3909 3922 'gp' instead of 'g', which was really a far too fragile and
3910 3923 common name.
3911 3924
3912 3925 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3913 3926 bounding boxes generated by Gnuplot for square plots.
3914 3927
3915 3928 * IPython/genutils.py (popkey): new function added. I should
3916 3929 suggest this on c.l.py as a dict method, it seems useful.
3917 3930
3918 3931 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3919 3932 to transparently handle PostScript generation. MUCH better than
3920 3933 the previous plot_eps/replot_eps (which I removed now). The code
3921 3934 is also fairly clean and well documented now (including
3922 3935 docstrings).
3923 3936
3924 3937 2002-11-13 Fernando Perez <fperez@colorado.edu>
3925 3938
3926 3939 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3927 3940 (inconsistent with options).
3928 3941
3929 3942 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3930 3943 manually disabled, I don't know why. Fixed it.
3931 3944 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3932 3945 eps output.
3933 3946
3934 3947 2002-11-12 Fernando Perez <fperez@colorado.edu>
3935 3948
3936 3949 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3937 3950 don't propagate up to caller. Fixes crash reported by François
3938 3951 Pinard.
3939 3952
3940 3953 2002-11-09 Fernando Perez <fperez@colorado.edu>
3941 3954
3942 3955 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3943 3956 history file for new users.
3944 3957 (make_IPython): fixed bug where initial install would leave the
3945 3958 user running in the .ipython dir.
3946 3959 (make_IPython): fixed bug where config dir .ipython would be
3947 3960 created regardless of the given -ipythondir option. Thanks to Cory
3948 3961 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3949 3962
3950 3963 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3951 3964 type confirmations. Will need to use it in all of IPython's code
3952 3965 consistently.
3953 3966
3954 3967 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3955 3968 context to print 31 lines instead of the default 5. This will make
3956 3969 the crash reports extremely detailed in case the problem is in
3957 3970 libraries I don't have access to.
3958 3971
3959 3972 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3960 3973 line of defense' code to still crash, but giving users fair
3961 3974 warning. I don't want internal errors to go unreported: if there's
3962 3975 an internal problem, IPython should crash and generate a full
3963 3976 report.
3964 3977
3965 3978 2002-11-08 Fernando Perez <fperez@colorado.edu>
3966 3979
3967 3980 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3968 3981 otherwise uncaught exceptions which can appear if people set
3969 3982 sys.stdout to something badly broken. Thanks to a crash report
3970 3983 from henni-AT-mail.brainbot.com.
3971 3984
3972 3985 2002-11-04 Fernando Perez <fperez@colorado.edu>
3973 3986
3974 3987 * IPython/iplib.py (InteractiveShell.interact): added
3975 3988 __IPYTHON__active to the builtins. It's a flag which goes on when
3976 3989 the interaction starts and goes off again when it stops. This
3977 3990 allows embedding code to detect being inside IPython. Before this
3978 3991 was done via __IPYTHON__, but that only shows that an IPython
3979 3992 instance has been created.
3980 3993
3981 3994 * IPython/Magic.py (Magic.magic_env): I realized that in a
3982 3995 UserDict, instance.data holds the data as a normal dict. So I
3983 3996 modified @env to return os.environ.data instead of rebuilding a
3984 3997 dict by hand.
3985 3998
3986 3999 2002-11-02 Fernando Perez <fperez@colorado.edu>
3987 4000
3988 4001 * IPython/genutils.py (warn): changed so that level 1 prints no
3989 4002 header. Level 2 is now the default (with 'WARNING' header, as
3990 4003 before). I think I tracked all places where changes were needed in
3991 4004 IPython, but outside code using the old level numbering may have
3992 4005 broken.
3993 4006
3994 4007 * IPython/iplib.py (InteractiveShell.runcode): added this to
3995 4008 handle the tracebacks in SystemExit traps correctly. The previous
3996 4009 code (through interact) was printing more of the stack than
3997 4010 necessary, showing IPython internal code to the user.
3998 4011
3999 4012 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
4000 4013 default. Now that the default at the confirmation prompt is yes,
4001 4014 it's not so intrusive. François' argument that ipython sessions
4002 4015 tend to be complex enough not to lose them from an accidental C-d,
4003 4016 is a valid one.
4004 4017
4005 4018 * IPython/iplib.py (InteractiveShell.interact): added a
4006 4019 showtraceback() call to the SystemExit trap, and modified the exit
4007 4020 confirmation to have yes as the default.
4008 4021
4009 4022 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
4010 4023 this file. It's been gone from the code for a long time, this was
4011 4024 simply leftover junk.
4012 4025
4013 4026 2002-11-01 Fernando Perez <fperez@colorado.edu>
4014 4027
4015 4028 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
4016 4029 added. If set, IPython now traps EOF and asks for
4017 4030 confirmation. After a request by François Pinard.
4018 4031
4019 4032 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
4020 4033 of @abort, and with a new (better) mechanism for handling the
4021 4034 exceptions.
4022 4035
4023 4036 2002-10-27 Fernando Perez <fperez@colorado.edu>
4024 4037
4025 4038 * IPython/usage.py (__doc__): updated the --help information and
4026 4039 the ipythonrc file to indicate that -log generates
4027 4040 ./ipython.log. Also fixed the corresponding info in @logstart.
4028 4041 This and several other fixes in the manuals thanks to reports by
4029 4042 François Pinard <pinard-AT-iro.umontreal.ca>.
4030 4043
4031 4044 * IPython/Logger.py (Logger.switch_log): Fixed error message to
4032 4045 refer to @logstart (instead of @log, which doesn't exist).
4033 4046
4034 4047 * IPython/iplib.py (InteractiveShell._prefilter): fixed
4035 4048 AttributeError crash. Thanks to Christopher Armstrong
4036 4049 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
4037 4050 introduced recently (in 0.2.14pre37) with the fix to the eval
4038 4051 problem mentioned below.
4039 4052
4040 4053 2002-10-17 Fernando Perez <fperez@colorado.edu>
4041 4054
4042 4055 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
4043 4056 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
4044 4057
4045 4058 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
4046 4059 this function to fix a problem reported by Alex Schmolck. He saw
4047 4060 it with list comprehensions and generators, which were getting
4048 4061 called twice. The real problem was an 'eval' call in testing for
4049 4062 automagic which was evaluating the input line silently.
4050 4063
4051 4064 This is a potentially very nasty bug, if the input has side
4052 4065 effects which must not be repeated. The code is much cleaner now,
4053 4066 without any blanket 'except' left and with a regexp test for
4054 4067 actual function names.
4055 4068
4056 4069 But an eval remains, which I'm not fully comfortable with. I just
4057 4070 don't know how to find out if an expression could be a callable in
4058 4071 the user's namespace without doing an eval on the string. However
4059 4072 that string is now much more strictly checked so that no code
4060 4073 slips by, so the eval should only happen for things that can
4061 4074 really be only function/method names.
4062 4075
4063 4076 2002-10-15 Fernando Perez <fperez@colorado.edu>
4064 4077
4065 4078 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
4066 4079 OSX information to main manual, removed README_Mac_OSX file from
4067 4080 distribution. Also updated credits for recent additions.
4068 4081
4069 4082 2002-10-10 Fernando Perez <fperez@colorado.edu>
4070 4083
4071 4084 * README_Mac_OSX: Added a README for Mac OSX users for fixing
4072 4085 terminal-related issues. Many thanks to Andrea Riciputi
4073 4086 <andrea.riciputi-AT-libero.it> for writing it.
4074 4087
4075 4088 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
4076 4089 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
4077 4090
4078 4091 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
4079 4092 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
4080 4093 <syver-en-AT-online.no> who both submitted patches for this problem.
4081 4094
4082 4095 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
4083 4096 global embedding to make sure that things don't overwrite user
4084 4097 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
4085 4098
4086 4099 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
4087 4100 compatibility. Thanks to Hayden Callow
4088 4101 <h.callow-AT-elec.canterbury.ac.nz>
4089 4102
4090 4103 2002-10-04 Fernando Perez <fperez@colorado.edu>
4091 4104
4092 4105 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
4093 4106 Gnuplot.File objects.
4094 4107
4095 4108 2002-07-23 Fernando Perez <fperez@colorado.edu>
4096 4109
4097 4110 * IPython/genutils.py (timing): Added timings() and timing() for
4098 4111 quick access to the most commonly needed data, the execution
4099 4112 times. Old timing() renamed to timings_out().
4100 4113
4101 4114 2002-07-18 Fernando Perez <fperez@colorado.edu>
4102 4115
4103 4116 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
4104 4117 bug with nested instances disrupting the parent's tab completion.
4105 4118
4106 4119 * IPython/iplib.py (all_completions): Added Alex Schmolck's
4107 4120 all_completions code to begin the emacs integration.
4108 4121
4109 4122 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
4110 4123 argument to allow titling individual arrays when plotting.
4111 4124
4112 4125 2002-07-15 Fernando Perez <fperez@colorado.edu>
4113 4126
4114 4127 * setup.py (make_shortcut): changed to retrieve the value of
4115 4128 'Program Files' directory from the registry (this value changes in
4116 4129 non-english versions of Windows). Thanks to Thomas Fanslau
4117 4130 <tfanslau-AT-gmx.de> for the report.
4118 4131
4119 4132 2002-07-10 Fernando Perez <fperez@colorado.edu>
4120 4133
4121 4134 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
4122 4135 a bug in pdb, which crashes if a line with only whitespace is
4123 4136 entered. Bug report submitted to sourceforge.
4124 4137
4125 4138 2002-07-09 Fernando Perez <fperez@colorado.edu>
4126 4139
4127 4140 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
4128 4141 reporting exceptions (it's a bug in inspect.py, I just set a
4129 4142 workaround).
4130 4143
4131 4144 2002-07-08 Fernando Perez <fperez@colorado.edu>
4132 4145
4133 4146 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
4134 4147 __IPYTHON__ in __builtins__ to show up in user_ns.
4135 4148
4136 4149 2002-07-03 Fernando Perez <fperez@colorado.edu>
4137 4150
4138 4151 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
4139 4152 name from @gp_set_instance to @gp_set_default.
4140 4153
4141 4154 * IPython/ipmaker.py (make_IPython): default editor value set to
4142 4155 '0' (a string), to match the rc file. Otherwise will crash when
4143 4156 .strip() is called on it.
4144 4157
4145 4158
4146 4159 2002-06-28 Fernando Perez <fperez@colorado.edu>
4147 4160
4148 4161 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
4149 4162 of files in current directory when a file is executed via
4150 4163 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
4151 4164
4152 4165 * setup.py (manfiles): fix for rpm builds, submitted by RA
4153 4166 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
4154 4167
4155 4168 * IPython/ipmaker.py (make_IPython): fixed lookup of default
4156 4169 editor when set to '0'. Problem was, '0' evaluates to True (it's a
4157 4170 string!). A. Schmolck caught this one.
4158 4171
4159 4172 2002-06-27 Fernando Perez <fperez@colorado.edu>
4160 4173
4161 4174 * IPython/ipmaker.py (make_IPython): fixed bug when running user
4162 4175 defined files at the cmd line. __name__ wasn't being set to
4163 4176 __main__.
4164 4177
4165 4178 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
4166 4179 regular lists and tuples besides Numeric arrays.
4167 4180
4168 4181 * IPython/Prompts.py (CachedOutput.__call__): Added output
4169 4182 supression for input ending with ';'. Similar to Mathematica and
4170 4183 Matlab. The _* vars and Out[] list are still updated, just like
4171 4184 Mathematica behaves.
4172 4185
4173 4186 2002-06-25 Fernando Perez <fperez@colorado.edu>
4174 4187
4175 4188 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
4176 4189 .ini extensions for profiels under Windows.
4177 4190
4178 4191 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
4179 4192 string form. Fix contributed by Alexander Schmolck
4180 4193 <a.schmolck-AT-gmx.net>
4181 4194
4182 4195 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
4183 4196 pre-configured Gnuplot instance.
4184 4197
4185 4198 2002-06-21 Fernando Perez <fperez@colorado.edu>
4186 4199
4187 4200 * IPython/numutils.py (exp_safe): new function, works around the
4188 4201 underflow problems in Numeric.
4189 4202 (log2): New fn. Safe log in base 2: returns exact integer answer
4190 4203 for exact integer powers of 2.
4191 4204
4192 4205 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
4193 4206 properly.
4194 4207
4195 4208 2002-06-20 Fernando Perez <fperez@colorado.edu>
4196 4209
4197 4210 * IPython/genutils.py (timing): new function like
4198 4211 Mathematica's. Similar to time_test, but returns more info.
4199 4212
4200 4213 2002-06-18 Fernando Perez <fperez@colorado.edu>
4201 4214
4202 4215 * IPython/Magic.py (Magic.magic_save): modified @save and @r
4203 4216 according to Mike Heeter's suggestions.
4204 4217
4205 4218 2002-06-16 Fernando Perez <fperez@colorado.edu>
4206 4219
4207 4220 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
4208 4221 system. GnuplotMagic is gone as a user-directory option. New files
4209 4222 make it easier to use all the gnuplot stuff both from external
4210 4223 programs as well as from IPython. Had to rewrite part of
4211 4224 hardcopy() b/c of a strange bug: often the ps files simply don't
4212 4225 get created, and require a repeat of the command (often several
4213 4226 times).
4214 4227
4215 4228 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
4216 4229 resolve output channel at call time, so that if sys.stderr has
4217 4230 been redirected by user this gets honored.
4218 4231
4219 4232 2002-06-13 Fernando Perez <fperez@colorado.edu>
4220 4233
4221 4234 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
4222 4235 IPShell. Kept a copy with the old names to avoid breaking people's
4223 4236 embedded code.
4224 4237
4225 4238 * IPython/ipython: simplified it to the bare minimum after
4226 4239 Holger's suggestions. Added info about how to use it in
4227 4240 PYTHONSTARTUP.
4228 4241
4229 4242 * IPython/Shell.py (IPythonShell): changed the options passing
4230 4243 from a string with funky %s replacements to a straight list. Maybe
4231 4244 a bit more typing, but it follows sys.argv conventions, so there's
4232 4245 less special-casing to remember.
4233 4246
4234 4247 2002-06-12 Fernando Perez <fperez@colorado.edu>
4235 4248
4236 4249 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
4237 4250 command. Thanks to a suggestion by Mike Heeter.
4238 4251 (Magic.magic_pfile): added behavior to look at filenames if given
4239 4252 arg is not a defined object.
4240 4253 (Magic.magic_save): New @save function to save code snippets. Also
4241 4254 a Mike Heeter idea.
4242 4255
4243 4256 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
4244 4257 plot() and replot(). Much more convenient now, especially for
4245 4258 interactive use.
4246 4259
4247 4260 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
4248 4261 filenames.
4249 4262
4250 4263 2002-06-02 Fernando Perez <fperez@colorado.edu>
4251 4264
4252 4265 * IPython/Struct.py (Struct.__init__): modified to admit
4253 4266 initialization via another struct.
4254 4267
4255 4268 * IPython/genutils.py (SystemExec.__init__): New stateful
4256 4269 interface to xsys and bq. Useful for writing system scripts.
4257 4270
4258 4271 2002-05-30 Fernando Perez <fperez@colorado.edu>
4259 4272
4260 4273 * MANIFEST.in: Changed docfile selection to exclude all the lyx
4261 4274 documents. This will make the user download smaller (it's getting
4262 4275 too big).
4263 4276
4264 4277 2002-05-29 Fernando Perez <fperez@colorado.edu>
4265 4278
4266 4279 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
4267 4280 fix problems with shelve and pickle. Seems to work, but I don't
4268 4281 know if corner cases break it. Thanks to Mike Heeter
4269 4282 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
4270 4283
4271 4284 2002-05-24 Fernando Perez <fperez@colorado.edu>
4272 4285
4273 4286 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
4274 4287 macros having broken.
4275 4288
4276 4289 2002-05-21 Fernando Perez <fperez@colorado.edu>
4277 4290
4278 4291 * IPython/Magic.py (Magic.magic_logstart): fixed recently
4279 4292 introduced logging bug: all history before logging started was
4280 4293 being written one character per line! This came from the redesign
4281 4294 of the input history as a special list which slices to strings,
4282 4295 not to lists.
4283 4296
4284 4297 2002-05-20 Fernando Perez <fperez@colorado.edu>
4285 4298
4286 4299 * IPython/Prompts.py (CachedOutput.__init__): made the color table
4287 4300 be an attribute of all classes in this module. The design of these
4288 4301 classes needs some serious overhauling.
4289 4302
4290 4303 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
4291 4304 which was ignoring '_' in option names.
4292 4305
4293 4306 * IPython/ultraTB.py (FormattedTB.__init__): Changed
4294 4307 'Verbose_novars' to 'Context' and made it the new default. It's a
4295 4308 bit more readable and also safer than verbose.
4296 4309
4297 4310 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
4298 4311 triple-quoted strings.
4299 4312
4300 4313 * IPython/OInspect.py (__all__): new module exposing the object
4301 4314 introspection facilities. Now the corresponding magics are dummy
4302 4315 wrappers around this. Having this module will make it much easier
4303 4316 to put these functions into our modified pdb.
4304 4317 This new object inspector system uses the new colorizing module,
4305 4318 so source code and other things are nicely syntax highlighted.
4306 4319
4307 4320 2002-05-18 Fernando Perez <fperez@colorado.edu>
4308 4321
4309 4322 * IPython/ColorANSI.py: Split the coloring tools into a separate
4310 4323 module so I can use them in other code easier (they were part of
4311 4324 ultraTB).
4312 4325
4313 4326 2002-05-17 Fernando Perez <fperez@colorado.edu>
4314 4327
4315 4328 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4316 4329 fixed it to set the global 'g' also to the called instance, as
4317 4330 long as 'g' was still a gnuplot instance (so it doesn't overwrite
4318 4331 user's 'g' variables).
4319 4332
4320 4333 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
4321 4334 global variables (aliases to _ih,_oh) so that users which expect
4322 4335 In[5] or Out[7] to work aren't unpleasantly surprised.
4323 4336 (InputList.__getslice__): new class to allow executing slices of
4324 4337 input history directly. Very simple class, complements the use of
4325 4338 macros.
4326 4339
4327 4340 2002-05-16 Fernando Perez <fperez@colorado.edu>
4328 4341
4329 4342 * setup.py (docdirbase): make doc directory be just doc/IPython
4330 4343 without version numbers, it will reduce clutter for users.
4331 4344
4332 4345 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
4333 4346 execfile call to prevent possible memory leak. See for details:
4334 4347 http://mail.python.org/pipermail/python-list/2002-February/088476.html
4335 4348
4336 4349 2002-05-15 Fernando Perez <fperez@colorado.edu>
4337 4350
4338 4351 * IPython/Magic.py (Magic.magic_psource): made the object
4339 4352 introspection names be more standard: pdoc, pdef, pfile and
4340 4353 psource. They all print/page their output, and it makes
4341 4354 remembering them easier. Kept old names for compatibility as
4342 4355 aliases.
4343 4356
4344 4357 2002-05-14 Fernando Perez <fperez@colorado.edu>
4345 4358
4346 4359 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
4347 4360 what the mouse problem was. The trick is to use gnuplot with temp
4348 4361 files and NOT with pipes (for data communication), because having
4349 4362 both pipes and the mouse on is bad news.
4350 4363
4351 4364 2002-05-13 Fernando Perez <fperez@colorado.edu>
4352 4365
4353 4366 * IPython/Magic.py (Magic._ofind): fixed namespace order search
4354 4367 bug. Information would be reported about builtins even when
4355 4368 user-defined functions overrode them.
4356 4369
4357 4370 2002-05-11 Fernando Perez <fperez@colorado.edu>
4358 4371
4359 4372 * IPython/__init__.py (__all__): removed FlexCompleter from
4360 4373 __all__ so that things don't fail in platforms without readline.
4361 4374
4362 4375 2002-05-10 Fernando Perez <fperez@colorado.edu>
4363 4376
4364 4377 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
4365 4378 it requires Numeric, effectively making Numeric a dependency for
4366 4379 IPython.
4367 4380
4368 4381 * Released 0.2.13
4369 4382
4370 4383 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
4371 4384 profiler interface. Now all the major options from the profiler
4372 4385 module are directly supported in IPython, both for single
4373 4386 expressions (@prun) and for full programs (@run -p).
4374 4387
4375 4388 2002-05-09 Fernando Perez <fperez@colorado.edu>
4376 4389
4377 4390 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
4378 4391 magic properly formatted for screen.
4379 4392
4380 4393 * setup.py (make_shortcut): Changed things to put pdf version in
4381 4394 doc/ instead of doc/manual (had to change lyxport a bit).
4382 4395
4383 4396 * IPython/Magic.py (Profile.string_stats): made profile runs go
4384 4397 through pager (they are long and a pager allows searching, saving,
4385 4398 etc.)
4386 4399
4387 4400 2002-05-08 Fernando Perez <fperez@colorado.edu>
4388 4401
4389 4402 * Released 0.2.12
4390 4403
4391 4404 2002-05-06 Fernando Perez <fperez@colorado.edu>
4392 4405
4393 4406 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
4394 4407 introduced); 'hist n1 n2' was broken.
4395 4408 (Magic.magic_pdb): added optional on/off arguments to @pdb
4396 4409 (Magic.magic_run): added option -i to @run, which executes code in
4397 4410 the IPython namespace instead of a clean one. Also added @irun as
4398 4411 an alias to @run -i.
4399 4412
4400 4413 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4401 4414 fixed (it didn't really do anything, the namespaces were wrong).
4402 4415
4403 4416 * IPython/Debugger.py (__init__): Added workaround for python 2.1
4404 4417
4405 4418 * IPython/__init__.py (__all__): Fixed package namespace, now
4406 4419 'import IPython' does give access to IPython.<all> as
4407 4420 expected. Also renamed __release__ to Release.
4408 4421
4409 4422 * IPython/Debugger.py (__license__): created new Pdb class which
4410 4423 functions like a drop-in for the normal pdb.Pdb but does NOT
4411 4424 import readline by default. This way it doesn't muck up IPython's
4412 4425 readline handling, and now tab-completion finally works in the
4413 4426 debugger -- sort of. It completes things globally visible, but the
4414 4427 completer doesn't track the stack as pdb walks it. That's a bit
4415 4428 tricky, and I'll have to implement it later.
4416 4429
4417 4430 2002-05-05 Fernando Perez <fperez@colorado.edu>
4418 4431
4419 4432 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
4420 4433 magic docstrings when printed via ? (explicit \'s were being
4421 4434 printed).
4422 4435
4423 4436 * IPython/ipmaker.py (make_IPython): fixed namespace
4424 4437 identification bug. Now variables loaded via logs or command-line
4425 4438 files are recognized in the interactive namespace by @who.
4426 4439
4427 4440 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
4428 4441 log replay system stemming from the string form of Structs.
4429 4442
4430 4443 * IPython/Magic.py (Macro.__init__): improved macros to properly
4431 4444 handle magic commands in them.
4432 4445 (Magic.magic_logstart): usernames are now expanded so 'logstart
4433 4446 ~/mylog' now works.
4434 4447
4435 4448 * IPython/iplib.py (complete): fixed bug where paths starting with
4436 4449 '/' would be completed as magic names.
4437 4450
4438 4451 2002-05-04 Fernando Perez <fperez@colorado.edu>
4439 4452
4440 4453 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
4441 4454 allow running full programs under the profiler's control.
4442 4455
4443 4456 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
4444 4457 mode to report exceptions verbosely but without formatting
4445 4458 variables. This addresses the issue of ipython 'freezing' (it's
4446 4459 not frozen, but caught in an expensive formatting loop) when huge
4447 4460 variables are in the context of an exception.
4448 4461 (VerboseTB.text): Added '--->' markers at line where exception was
4449 4462 triggered. Much clearer to read, especially in NoColor modes.
4450 4463
4451 4464 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
4452 4465 implemented in reverse when changing to the new parse_options().
4453 4466
4454 4467 2002-05-03 Fernando Perez <fperez@colorado.edu>
4455 4468
4456 4469 * IPython/Magic.py (Magic.parse_options): new function so that
4457 4470 magics can parse options easier.
4458 4471 (Magic.magic_prun): new function similar to profile.run(),
4459 4472 suggested by Chris Hart.
4460 4473 (Magic.magic_cd): fixed behavior so that it only changes if
4461 4474 directory actually is in history.
4462 4475
4463 4476 * IPython/usage.py (__doc__): added information about potential
4464 4477 slowness of Verbose exception mode when there are huge data
4465 4478 structures to be formatted (thanks to Archie Paulson).
4466 4479
4467 4480 * IPython/ipmaker.py (make_IPython): Changed default logging
4468 4481 (when simply called with -log) to use curr_dir/ipython.log in
4469 4482 rotate mode. Fixed crash which was occuring with -log before
4470 4483 (thanks to Jim Boyle).
4471 4484
4472 4485 2002-05-01 Fernando Perez <fperez@colorado.edu>
4473 4486
4474 4487 * Released 0.2.11 for these fixes (mainly the ultraTB one which
4475 4488 was nasty -- though somewhat of a corner case).
4476 4489
4477 4490 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
4478 4491 text (was a bug).
4479 4492
4480 4493 2002-04-30 Fernando Perez <fperez@colorado.edu>
4481 4494
4482 4495 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
4483 4496 a print after ^D or ^C from the user so that the In[] prompt
4484 4497 doesn't over-run the gnuplot one.
4485 4498
4486 4499 2002-04-29 Fernando Perez <fperez@colorado.edu>
4487 4500
4488 4501 * Released 0.2.10
4489 4502
4490 4503 * IPython/__release__.py (version): get date dynamically.
4491 4504
4492 4505 * Misc. documentation updates thanks to Arnd's comments. Also ran
4493 4506 a full spellcheck on the manual (hadn't been done in a while).
4494 4507
4495 4508 2002-04-27 Fernando Perez <fperez@colorado.edu>
4496 4509
4497 4510 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
4498 4511 starting a log in mid-session would reset the input history list.
4499 4512
4500 4513 2002-04-26 Fernando Perez <fperez@colorado.edu>
4501 4514
4502 4515 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
4503 4516 all files were being included in an update. Now anything in
4504 4517 UserConfig that matches [A-Za-z]*.py will go (this excludes
4505 4518 __init__.py)
4506 4519
4507 4520 2002-04-25 Fernando Perez <fperez@colorado.edu>
4508 4521
4509 4522 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
4510 4523 to __builtins__ so that any form of embedded or imported code can
4511 4524 test for being inside IPython.
4512 4525
4513 4526 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
4514 4527 changed to GnuplotMagic because it's now an importable module,
4515 4528 this makes the name follow that of the standard Gnuplot module.
4516 4529 GnuplotMagic can now be loaded at any time in mid-session.
4517 4530
4518 4531 2002-04-24 Fernando Perez <fperez@colorado.edu>
4519 4532
4520 4533 * IPython/numutils.py: removed SIUnits. It doesn't properly set
4521 4534 the globals (IPython has its own namespace) and the
4522 4535 PhysicalQuantity stuff is much better anyway.
4523 4536
4524 4537 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
4525 4538 embedding example to standard user directory for
4526 4539 distribution. Also put it in the manual.
4527 4540
4528 4541 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
4529 4542 instance as first argument (so it doesn't rely on some obscure
4530 4543 hidden global).
4531 4544
4532 4545 * IPython/UserConfig/ipythonrc.py: put () back in accepted
4533 4546 delimiters. While it prevents ().TAB from working, it allows
4534 4547 completions in open (... expressions. This is by far a more common
4535 4548 case.
4536 4549
4537 4550 2002-04-23 Fernando Perez <fperez@colorado.edu>
4538 4551
4539 4552 * IPython/Extensions/InterpreterPasteInput.py: new
4540 4553 syntax-processing module for pasting lines with >>> or ... at the
4541 4554 start.
4542 4555
4543 4556 * IPython/Extensions/PhysicalQ_Interactive.py
4544 4557 (PhysicalQuantityInteractive.__int__): fixed to work with either
4545 4558 Numeric or math.
4546 4559
4547 4560 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
4548 4561 provided profiles. Now we have:
4549 4562 -math -> math module as * and cmath with its own namespace.
4550 4563 -numeric -> Numeric as *, plus gnuplot & grace
4551 4564 -physics -> same as before
4552 4565
4553 4566 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
4554 4567 user-defined magics wouldn't be found by @magic if they were
4555 4568 defined as class methods. Also cleaned up the namespace search
4556 4569 logic and the string building (to use %s instead of many repeated
4557 4570 string adds).
4558 4571
4559 4572 * IPython/UserConfig/example-magic.py (magic_foo): updated example
4560 4573 of user-defined magics to operate with class methods (cleaner, in
4561 4574 line with the gnuplot code).
4562 4575
4563 4576 2002-04-22 Fernando Perez <fperez@colorado.edu>
4564 4577
4565 4578 * setup.py: updated dependency list so that manual is updated when
4566 4579 all included files change.
4567 4580
4568 4581 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
4569 4582 the delimiter removal option (the fix is ugly right now).
4570 4583
4571 4584 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
4572 4585 all of the math profile (quicker loading, no conflict between
4573 4586 g-9.8 and g-gnuplot).
4574 4587
4575 4588 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
4576 4589 name of post-mortem files to IPython_crash_report.txt.
4577 4590
4578 4591 * Cleanup/update of the docs. Added all the new readline info and
4579 4592 formatted all lists as 'real lists'.
4580 4593
4581 4594 * IPython/ipmaker.py (make_IPython): removed now-obsolete
4582 4595 tab-completion options, since the full readline parse_and_bind is
4583 4596 now accessible.
4584 4597
4585 4598 * IPython/iplib.py (InteractiveShell.init_readline): Changed
4586 4599 handling of readline options. Now users can specify any string to
4587 4600 be passed to parse_and_bind(), as well as the delimiters to be
4588 4601 removed.
4589 4602 (InteractiveShell.__init__): Added __name__ to the global
4590 4603 namespace so that things like Itpl which rely on its existence
4591 4604 don't crash.
4592 4605 (InteractiveShell._prefilter): Defined the default with a _ so
4593 4606 that prefilter() is easier to override, while the default one
4594 4607 remains available.
4595 4608
4596 4609 2002-04-18 Fernando Perez <fperez@colorado.edu>
4597 4610
4598 4611 * Added information about pdb in the docs.
4599 4612
4600 4613 2002-04-17 Fernando Perez <fperez@colorado.edu>
4601 4614
4602 4615 * IPython/ipmaker.py (make_IPython): added rc_override option to
4603 4616 allow passing config options at creation time which may override
4604 4617 anything set in the config files or command line. This is
4605 4618 particularly useful for configuring embedded instances.
4606 4619
4607 4620 2002-04-15 Fernando Perez <fperez@colorado.edu>
4608 4621
4609 4622 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
4610 4623 crash embedded instances because of the input cache falling out of
4611 4624 sync with the output counter.
4612 4625
4613 4626 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
4614 4627 mode which calls pdb after an uncaught exception in IPython itself.
4615 4628
4616 4629 2002-04-14 Fernando Perez <fperez@colorado.edu>
4617 4630
4618 4631 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
4619 4632 readline, fix it back after each call.
4620 4633
4621 4634 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
4622 4635 method to force all access via __call__(), which guarantees that
4623 4636 traceback references are properly deleted.
4624 4637
4625 4638 * IPython/Prompts.py (CachedOutput._display): minor fixes to
4626 4639 improve printing when pprint is in use.
4627 4640
4628 4641 2002-04-13 Fernando Perez <fperez@colorado.edu>
4629 4642
4630 4643 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
4631 4644 exceptions aren't caught anymore. If the user triggers one, he
4632 4645 should know why he's doing it and it should go all the way up,
4633 4646 just like any other exception. So now @abort will fully kill the
4634 4647 embedded interpreter and the embedding code (unless that happens
4635 4648 to catch SystemExit).
4636 4649
4637 4650 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
4638 4651 and a debugger() method to invoke the interactive pdb debugger
4639 4652 after printing exception information. Also added the corresponding
4640 4653 -pdb option and @pdb magic to control this feature, and updated
4641 4654 the docs. After a suggestion from Christopher Hart
4642 4655 (hart-AT-caltech.edu).
4643 4656
4644 4657 2002-04-12 Fernando Perez <fperez@colorado.edu>
4645 4658
4646 4659 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
4647 4660 the exception handlers defined by the user (not the CrashHandler)
4648 4661 so that user exceptions don't trigger an ipython bug report.
4649 4662
4650 4663 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
4651 4664 configurable (it should have always been so).
4652 4665
4653 4666 2002-03-26 Fernando Perez <fperez@colorado.edu>
4654 4667
4655 4668 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
4656 4669 and there to fix embedding namespace issues. This should all be
4657 4670 done in a more elegant way.
4658 4671
4659 4672 2002-03-25 Fernando Perez <fperez@colorado.edu>
4660 4673
4661 4674 * IPython/genutils.py (get_home_dir): Try to make it work under
4662 4675 win9x also.
4663 4676
4664 4677 2002-03-20 Fernando Perez <fperez@colorado.edu>
4665 4678
4666 4679 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
4667 4680 sys.displayhook untouched upon __init__.
4668 4681
4669 4682 2002-03-19 Fernando Perez <fperez@colorado.edu>
4670 4683
4671 4684 * Released 0.2.9 (for embedding bug, basically).
4672 4685
4673 4686 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
4674 4687 exceptions so that enclosing shell's state can be restored.
4675 4688
4676 4689 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
4677 4690 naming conventions in the .ipython/ dir.
4678 4691
4679 4692 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
4680 4693 from delimiters list so filenames with - in them get expanded.
4681 4694
4682 4695 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
4683 4696 sys.displayhook not being properly restored after an embedded call.
4684 4697
4685 4698 2002-03-18 Fernando Perez <fperez@colorado.edu>
4686 4699
4687 4700 * Released 0.2.8
4688 4701
4689 4702 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
4690 4703 some files weren't being included in a -upgrade.
4691 4704 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
4692 4705 on' so that the first tab completes.
4693 4706 (InteractiveShell.handle_magic): fixed bug with spaces around
4694 4707 quotes breaking many magic commands.
4695 4708
4696 4709 * setup.py: added note about ignoring the syntax error messages at
4697 4710 installation.
4698 4711
4699 4712 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
4700 4713 streamlining the gnuplot interface, now there's only one magic @gp.
4701 4714
4702 4715 2002-03-17 Fernando Perez <fperez@colorado.edu>
4703 4716
4704 4717 * IPython/UserConfig/magic_gnuplot.py: new name for the
4705 4718 example-magic_pm.py file. Much enhanced system, now with a shell
4706 4719 for communicating directly with gnuplot, one command at a time.
4707 4720
4708 4721 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
4709 4722 setting __name__=='__main__'.
4710 4723
4711 4724 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
4712 4725 mini-shell for accessing gnuplot from inside ipython. Should
4713 4726 extend it later for grace access too. Inspired by Arnd's
4714 4727 suggestion.
4715 4728
4716 4729 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
4717 4730 calling magic functions with () in their arguments. Thanks to Arnd
4718 4731 Baecker for pointing this to me.
4719 4732
4720 4733 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
4721 4734 infinitely for integer or complex arrays (only worked with floats).
4722 4735
4723 4736 2002-03-16 Fernando Perez <fperez@colorado.edu>
4724 4737
4725 4738 * setup.py: Merged setup and setup_windows into a single script
4726 4739 which properly handles things for windows users.
4727 4740
4728 4741 2002-03-15 Fernando Perez <fperez@colorado.edu>
4729 4742
4730 4743 * Big change to the manual: now the magics are all automatically
4731 4744 documented. This information is generated from their docstrings
4732 4745 and put in a latex file included by the manual lyx file. This way
4733 4746 we get always up to date information for the magics. The manual
4734 4747 now also has proper version information, also auto-synced.
4735 4748
4736 4749 For this to work, an undocumented --magic_docstrings option was added.
4737 4750
4738 4751 2002-03-13 Fernando Perez <fperez@colorado.edu>
4739 4752
4740 4753 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
4741 4754 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
4742 4755
4743 4756 2002-03-12 Fernando Perez <fperez@colorado.edu>
4744 4757
4745 4758 * IPython/ultraTB.py (TermColors): changed color escapes again to
4746 4759 fix the (old, reintroduced) line-wrapping bug. Basically, if
4747 4760 \001..\002 aren't given in the color escapes, lines get wrapped
4748 4761 weirdly. But giving those screws up old xterms and emacs terms. So
4749 4762 I added some logic for emacs terms to be ok, but I can't identify old
4750 4763 xterms separately ($TERM=='xterm' for many terminals, like konsole).
4751 4764
4752 4765 2002-03-10 Fernando Perez <fperez@colorado.edu>
4753 4766
4754 4767 * IPython/usage.py (__doc__): Various documentation cleanups and
4755 4768 updates, both in usage docstrings and in the manual.
4756 4769
4757 4770 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
4758 4771 handling of caching. Set minimum acceptabe value for having a
4759 4772 cache at 20 values.
4760 4773
4761 4774 * IPython/iplib.py (InteractiveShell.user_setup): moved the
4762 4775 install_first_time function to a method, renamed it and added an
4763 4776 'upgrade' mode. Now people can update their config directory with
4764 4777 a simple command line switch (-upgrade, also new).
4765 4778
4766 4779 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
4767 4780 @file (convenient for automagic users under Python >= 2.2).
4768 4781 Removed @files (it seemed more like a plural than an abbrev. of
4769 4782 'file show').
4770 4783
4771 4784 * IPython/iplib.py (install_first_time): Fixed crash if there were
4772 4785 backup files ('~') in .ipython/ install directory.
4773 4786
4774 4787 * IPython/ipmaker.py (make_IPython): fixes for new prompt
4775 4788 system. Things look fine, but these changes are fairly
4776 4789 intrusive. Test them for a few days.
4777 4790
4778 4791 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
4779 4792 the prompts system. Now all in/out prompt strings are user
4780 4793 controllable. This is particularly useful for embedding, as one
4781 4794 can tag embedded instances with particular prompts.
4782 4795
4783 4796 Also removed global use of sys.ps1/2, which now allows nested
4784 4797 embeddings without any problems. Added command-line options for
4785 4798 the prompt strings.
4786 4799
4787 4800 2002-03-08 Fernando Perez <fperez@colorado.edu>
4788 4801
4789 4802 * IPython/UserConfig/example-embed-short.py (ipshell): added
4790 4803 example file with the bare minimum code for embedding.
4791 4804
4792 4805 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
4793 4806 functionality for the embeddable shell to be activated/deactivated
4794 4807 either globally or at each call.
4795 4808
4796 4809 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
4797 4810 rewriting the prompt with '--->' for auto-inputs with proper
4798 4811 coloring. Now the previous UGLY hack in handle_auto() is gone, and
4799 4812 this is handled by the prompts class itself, as it should.
4800 4813
4801 4814 2002-03-05 Fernando Perez <fperez@colorado.edu>
4802 4815
4803 4816 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
4804 4817 @logstart to avoid name clashes with the math log function.
4805 4818
4806 4819 * Big updates to X/Emacs section of the manual.
4807 4820
4808 4821 * Removed ipython_emacs. Milan explained to me how to pass
4809 4822 arguments to ipython through Emacs. Some day I'm going to end up
4810 4823 learning some lisp...
4811 4824
4812 4825 2002-03-04 Fernando Perez <fperez@colorado.edu>
4813 4826
4814 4827 * IPython/ipython_emacs: Created script to be used as the
4815 4828 py-python-command Emacs variable so we can pass IPython
4816 4829 parameters. I can't figure out how to tell Emacs directly to pass
4817 4830 parameters to IPython, so a dummy shell script will do it.
4818 4831
4819 4832 Other enhancements made for things to work better under Emacs'
4820 4833 various types of terminals. Many thanks to Milan Zamazal
4821 4834 <pdm-AT-zamazal.org> for all the suggestions and pointers.
4822 4835
4823 4836 2002-03-01 Fernando Perez <fperez@colorado.edu>
4824 4837
4825 4838 * IPython/ipmaker.py (make_IPython): added a --readline! option so
4826 4839 that loading of readline is now optional. This gives better
4827 4840 control to emacs users.
4828 4841
4829 4842 * IPython/ultraTB.py (__date__): Modified color escape sequences
4830 4843 and now things work fine under xterm and in Emacs' term buffers
4831 4844 (though not shell ones). Well, in emacs you get colors, but all
4832 4845 seem to be 'light' colors (no difference between dark and light
4833 4846 ones). But the garbage chars are gone, and also in xterms. It
4834 4847 seems that now I'm using 'cleaner' ansi sequences.
4835 4848
4836 4849 2002-02-21 Fernando Perez <fperez@colorado.edu>
4837 4850
4838 4851 * Released 0.2.7 (mainly to publish the scoping fix).
4839 4852
4840 4853 * IPython/Logger.py (Logger.logstate): added. A corresponding
4841 4854 @logstate magic was created.
4842 4855
4843 4856 * IPython/Magic.py: fixed nested scoping problem under Python
4844 4857 2.1.x (automagic wasn't working).
4845 4858
4846 4859 2002-02-20 Fernando Perez <fperez@colorado.edu>
4847 4860
4848 4861 * Released 0.2.6.
4849 4862
4850 4863 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
4851 4864 option so that logs can come out without any headers at all.
4852 4865
4853 4866 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
4854 4867 SciPy.
4855 4868
4856 4869 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
4857 4870 that embedded IPython calls don't require vars() to be explicitly
4858 4871 passed. Now they are extracted from the caller's frame (code
4859 4872 snatched from Eric Jones' weave). Added better documentation to
4860 4873 the section on embedding and the example file.
4861 4874
4862 4875 * IPython/genutils.py (page): Changed so that under emacs, it just
4863 4876 prints the string. You can then page up and down in the emacs
4864 4877 buffer itself. This is how the builtin help() works.
4865 4878
4866 4879 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
4867 4880 macro scoping: macros need to be executed in the user's namespace
4868 4881 to work as if they had been typed by the user.
4869 4882
4870 4883 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
4871 4884 execute automatically (no need to type 'exec...'). They then
4872 4885 behave like 'true macros'. The printing system was also modified
4873 4886 for this to work.
4874 4887
4875 4888 2002-02-19 Fernando Perez <fperez@colorado.edu>
4876 4889
4877 4890 * IPython/genutils.py (page_file): new function for paging files
4878 4891 in an OS-independent way. Also necessary for file viewing to work
4879 4892 well inside Emacs buffers.
4880 4893 (page): Added checks for being in an emacs buffer.
4881 4894 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
4882 4895 same bug in iplib.
4883 4896
4884 4897 2002-02-18 Fernando Perez <fperez@colorado.edu>
4885 4898
4886 4899 * IPython/iplib.py (InteractiveShell.init_readline): modified use
4887 4900 of readline so that IPython can work inside an Emacs buffer.
4888 4901
4889 4902 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
4890 4903 method signatures (they weren't really bugs, but it looks cleaner
4891 4904 and keeps PyChecker happy).
4892 4905
4893 4906 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4894 4907 for implementing various user-defined hooks. Currently only
4895 4908 display is done.
4896 4909
4897 4910 * IPython/Prompts.py (CachedOutput._display): changed display
4898 4911 functions so that they can be dynamically changed by users easily.
4899 4912
4900 4913 * IPython/Extensions/numeric_formats.py (num_display): added an
4901 4914 extension for printing NumPy arrays in flexible manners. It
4902 4915 doesn't do anything yet, but all the structure is in
4903 4916 place. Ultimately the plan is to implement output format control
4904 4917 like in Octave.
4905 4918
4906 4919 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4907 4920 methods are found at run-time by all the automatic machinery.
4908 4921
4909 4922 2002-02-17 Fernando Perez <fperez@colorado.edu>
4910 4923
4911 4924 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4912 4925 whole file a little.
4913 4926
4914 4927 * ToDo: closed this document. Now there's a new_design.lyx
4915 4928 document for all new ideas. Added making a pdf of it for the
4916 4929 end-user distro.
4917 4930
4918 4931 * IPython/Logger.py (Logger.switch_log): Created this to replace
4919 4932 logon() and logoff(). It also fixes a nasty crash reported by
4920 4933 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4921 4934
4922 4935 * IPython/iplib.py (complete): got auto-completion to work with
4923 4936 automagic (I had wanted this for a long time).
4924 4937
4925 4938 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4926 4939 to @file, since file() is now a builtin and clashes with automagic
4927 4940 for @file.
4928 4941
4929 4942 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4930 4943 of this was previously in iplib, which had grown to more than 2000
4931 4944 lines, way too long. No new functionality, but it makes managing
4932 4945 the code a bit easier.
4933 4946
4934 4947 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4935 4948 information to crash reports.
4936 4949
4937 4950 2002-02-12 Fernando Perez <fperez@colorado.edu>
4938 4951
4939 4952 * Released 0.2.5.
4940 4953
4941 4954 2002-02-11 Fernando Perez <fperez@colorado.edu>
4942 4955
4943 4956 * Wrote a relatively complete Windows installer. It puts
4944 4957 everything in place, creates Start Menu entries and fixes the
4945 4958 color issues. Nothing fancy, but it works.
4946 4959
4947 4960 2002-02-10 Fernando Perez <fperez@colorado.edu>
4948 4961
4949 4962 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4950 4963 os.path.expanduser() call so that we can type @run ~/myfile.py and
4951 4964 have thigs work as expected.
4952 4965
4953 4966 * IPython/genutils.py (page): fixed exception handling so things
4954 4967 work both in Unix and Windows correctly. Quitting a pager triggers
4955 4968 an IOError/broken pipe in Unix, and in windows not finding a pager
4956 4969 is also an IOError, so I had to actually look at the return value
4957 4970 of the exception, not just the exception itself. Should be ok now.
4958 4971
4959 4972 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4960 4973 modified to allow case-insensitive color scheme changes.
4961 4974
4962 4975 2002-02-09 Fernando Perez <fperez@colorado.edu>
4963 4976
4964 4977 * IPython/genutils.py (native_line_ends): new function to leave
4965 4978 user config files with os-native line-endings.
4966 4979
4967 4980 * README and manual updates.
4968 4981
4969 4982 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4970 4983 instead of StringType to catch Unicode strings.
4971 4984
4972 4985 * IPython/genutils.py (filefind): fixed bug for paths with
4973 4986 embedded spaces (very common in Windows).
4974 4987
4975 4988 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4976 4989 files under Windows, so that they get automatically associated
4977 4990 with a text editor. Windows makes it a pain to handle
4978 4991 extension-less files.
4979 4992
4980 4993 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4981 4994 warning about readline only occur for Posix. In Windows there's no
4982 4995 way to get readline, so why bother with the warning.
4983 4996
4984 4997 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4985 4998 for __str__ instead of dir(self), since dir() changed in 2.2.
4986 4999
4987 5000 * Ported to Windows! Tested on XP, I suspect it should work fine
4988 5001 on NT/2000, but I don't think it will work on 98 et al. That
4989 5002 series of Windows is such a piece of junk anyway that I won't try
4990 5003 porting it there. The XP port was straightforward, showed a few
4991 5004 bugs here and there (fixed all), in particular some string
4992 5005 handling stuff which required considering Unicode strings (which
4993 5006 Windows uses). This is good, but hasn't been too tested :) No
4994 5007 fancy installer yet, I'll put a note in the manual so people at
4995 5008 least make manually a shortcut.
4996 5009
4997 5010 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4998 5011 into a single one, "colors". This now controls both prompt and
4999 5012 exception color schemes, and can be changed both at startup
5000 5013 (either via command-line switches or via ipythonrc files) and at
5001 5014 runtime, with @colors.
5002 5015 (Magic.magic_run): renamed @prun to @run and removed the old
5003 5016 @run. The two were too similar to warrant keeping both.
5004 5017
5005 5018 2002-02-03 Fernando Perez <fperez@colorado.edu>
5006 5019
5007 5020 * IPython/iplib.py (install_first_time): Added comment on how to
5008 5021 configure the color options for first-time users. Put a <return>
5009 5022 request at the end so that small-terminal users get a chance to
5010 5023 read the startup info.
5011 5024
5012 5025 2002-01-23 Fernando Perez <fperez@colorado.edu>
5013 5026
5014 5027 * IPython/iplib.py (CachedOutput.update): Changed output memory
5015 5028 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
5016 5029 input history we still use _i. Did this b/c these variable are
5017 5030 very commonly used in interactive work, so the less we need to
5018 5031 type the better off we are.
5019 5032 (Magic.magic_prun): updated @prun to better handle the namespaces
5020 5033 the file will run in, including a fix for __name__ not being set
5021 5034 before.
5022 5035
5023 5036 2002-01-20 Fernando Perez <fperez@colorado.edu>
5024 5037
5025 5038 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
5026 5039 extra garbage for Python 2.2. Need to look more carefully into
5027 5040 this later.
5028 5041
5029 5042 2002-01-19 Fernando Perez <fperez@colorado.edu>
5030 5043
5031 5044 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
5032 5045 display SyntaxError exceptions properly formatted when they occur
5033 5046 (they can be triggered by imported code).
5034 5047
5035 5048 2002-01-18 Fernando Perez <fperez@colorado.edu>
5036 5049
5037 5050 * IPython/iplib.py (InteractiveShell.safe_execfile): now
5038 5051 SyntaxError exceptions are reported nicely formatted, instead of
5039 5052 spitting out only offset information as before.
5040 5053 (Magic.magic_prun): Added the @prun function for executing
5041 5054 programs with command line args inside IPython.
5042 5055
5043 5056 2002-01-16 Fernando Perez <fperez@colorado.edu>
5044 5057
5045 5058 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
5046 5059 to *not* include the last item given in a range. This brings their
5047 5060 behavior in line with Python's slicing:
5048 5061 a[n1:n2] -> a[n1]...a[n2-1]
5049 5062 It may be a bit less convenient, but I prefer to stick to Python's
5050 5063 conventions *everywhere*, so users never have to wonder.
5051 5064 (Magic.magic_macro): Added @macro function to ease the creation of
5052 5065 macros.
5053 5066
5054 5067 2002-01-05 Fernando Perez <fperez@colorado.edu>
5055 5068
5056 5069 * Released 0.2.4.
5057 5070
5058 5071 * IPython/iplib.py (Magic.magic_pdef):
5059 5072 (InteractiveShell.safe_execfile): report magic lines and error
5060 5073 lines without line numbers so one can easily copy/paste them for
5061 5074 re-execution.
5062 5075
5063 5076 * Updated manual with recent changes.
5064 5077
5065 5078 * IPython/iplib.py (Magic.magic_oinfo): added constructor
5066 5079 docstring printing when class? is called. Very handy for knowing
5067 5080 how to create class instances (as long as __init__ is well
5068 5081 documented, of course :)
5069 5082 (Magic.magic_doc): print both class and constructor docstrings.
5070 5083 (Magic.magic_pdef): give constructor info if passed a class and
5071 5084 __call__ info for callable object instances.
5072 5085
5073 5086 2002-01-04 Fernando Perez <fperez@colorado.edu>
5074 5087
5075 5088 * Made deep_reload() off by default. It doesn't always work
5076 5089 exactly as intended, so it's probably safer to have it off. It's
5077 5090 still available as dreload() anyway, so nothing is lost.
5078 5091
5079 5092 2002-01-02 Fernando Perez <fperez@colorado.edu>
5080 5093
5081 5094 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
5082 5095 so I wanted an updated release).
5083 5096
5084 5097 2001-12-27 Fernando Perez <fperez@colorado.edu>
5085 5098
5086 5099 * IPython/iplib.py (InteractiveShell.interact): Added the original
5087 5100 code from 'code.py' for this module in order to change the
5088 5101 handling of a KeyboardInterrupt. This was necessary b/c otherwise
5089 5102 the history cache would break when the user hit Ctrl-C, and
5090 5103 interact() offers no way to add any hooks to it.
5091 5104
5092 5105 2001-12-23 Fernando Perez <fperez@colorado.edu>
5093 5106
5094 5107 * setup.py: added check for 'MANIFEST' before trying to remove
5095 5108 it. Thanks to Sean Reifschneider.
5096 5109
5097 5110 2001-12-22 Fernando Perez <fperez@colorado.edu>
5098 5111
5099 5112 * Released 0.2.2.
5100 5113
5101 5114 * Finished (reasonably) writing the manual. Later will add the
5102 5115 python-standard navigation stylesheets, but for the time being
5103 5116 it's fairly complete. Distribution will include html and pdf
5104 5117 versions.
5105 5118
5106 5119 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
5107 5120 (MayaVi author).
5108 5121
5109 5122 2001-12-21 Fernando Perez <fperez@colorado.edu>
5110 5123
5111 5124 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
5112 5125 good public release, I think (with the manual and the distutils
5113 5126 installer). The manual can use some work, but that can go
5114 5127 slowly. Otherwise I think it's quite nice for end users. Next
5115 5128 summer, rewrite the guts of it...
5116 5129
5117 5130 * Changed format of ipythonrc files to use whitespace as the
5118 5131 separator instead of an explicit '='. Cleaner.
5119 5132
5120 5133 2001-12-20 Fernando Perez <fperez@colorado.edu>
5121 5134
5122 5135 * Started a manual in LyX. For now it's just a quick merge of the
5123 5136 various internal docstrings and READMEs. Later it may grow into a
5124 5137 nice, full-blown manual.
5125 5138
5126 5139 * Set up a distutils based installer. Installation should now be
5127 5140 trivially simple for end-users.
5128 5141
5129 5142 2001-12-11 Fernando Perez <fperez@colorado.edu>
5130 5143
5131 5144 * Released 0.2.0. First public release, announced it at
5132 5145 comp.lang.python. From now on, just bugfixes...
5133 5146
5134 5147 * Went through all the files, set copyright/license notices and
5135 5148 cleaned up things. Ready for release.
5136 5149
5137 5150 2001-12-10 Fernando Perez <fperez@colorado.edu>
5138 5151
5139 5152 * Changed the first-time installer not to use tarfiles. It's more
5140 5153 robust now and less unix-dependent. Also makes it easier for
5141 5154 people to later upgrade versions.
5142 5155
5143 5156 * Changed @exit to @abort to reflect the fact that it's pretty
5144 5157 brutal (a sys.exit()). The difference between @abort and Ctrl-D
5145 5158 becomes significant only when IPyhton is embedded: in that case,
5146 5159 C-D closes IPython only, but @abort kills the enclosing program
5147 5160 too (unless it had called IPython inside a try catching
5148 5161 SystemExit).
5149 5162
5150 5163 * Created Shell module which exposes the actuall IPython Shell
5151 5164 classes, currently the normal and the embeddable one. This at
5152 5165 least offers a stable interface we won't need to change when
5153 5166 (later) the internals are rewritten. That rewrite will be confined
5154 5167 to iplib and ipmaker, but the Shell interface should remain as is.
5155 5168
5156 5169 * Added embed module which offers an embeddable IPShell object,
5157 5170 useful to fire up IPython *inside* a running program. Great for
5158 5171 debugging or dynamical data analysis.
5159 5172
5160 5173 2001-12-08 Fernando Perez <fperez@colorado.edu>
5161 5174
5162 5175 * Fixed small bug preventing seeing info from methods of defined
5163 5176 objects (incorrect namespace in _ofind()).
5164 5177
5165 5178 * Documentation cleanup. Moved the main usage docstrings to a
5166 5179 separate file, usage.py (cleaner to maintain, and hopefully in the
5167 5180 future some perlpod-like way of producing interactive, man and
5168 5181 html docs out of it will be found).
5169 5182
5170 5183 * Added @profile to see your profile at any time.
5171 5184
5172 5185 * Added @p as an alias for 'print'. It's especially convenient if
5173 5186 using automagic ('p x' prints x).
5174 5187
5175 5188 * Small cleanups and fixes after a pychecker run.
5176 5189
5177 5190 * Changed the @cd command to handle @cd - and @cd -<n> for
5178 5191 visiting any directory in _dh.
5179 5192
5180 5193 * Introduced _dh, a history of visited directories. @dhist prints
5181 5194 it out with numbers.
5182 5195
5183 5196 2001-12-07 Fernando Perez <fperez@colorado.edu>
5184 5197
5185 5198 * Released 0.1.22
5186 5199
5187 5200 * Made initialization a bit more robust against invalid color
5188 5201 options in user input (exit, not traceback-crash).
5189 5202
5190 5203 * Changed the bug crash reporter to write the report only in the
5191 5204 user's .ipython directory. That way IPython won't litter people's
5192 5205 hard disks with crash files all over the place. Also print on
5193 5206 screen the necessary mail command.
5194 5207
5195 5208 * With the new ultraTB, implemented LightBG color scheme for light
5196 5209 background terminals. A lot of people like white backgrounds, so I
5197 5210 guess we should at least give them something readable.
5198 5211
5199 5212 2001-12-06 Fernando Perez <fperez@colorado.edu>
5200 5213
5201 5214 * Modified the structure of ultraTB. Now there's a proper class
5202 5215 for tables of color schemes which allow adding schemes easily and
5203 5216 switching the active scheme without creating a new instance every
5204 5217 time (which was ridiculous). The syntax for creating new schemes
5205 5218 is also cleaner. I think ultraTB is finally done, with a clean
5206 5219 class structure. Names are also much cleaner (now there's proper
5207 5220 color tables, no need for every variable to also have 'color' in
5208 5221 its name).
5209 5222
5210 5223 * Broke down genutils into separate files. Now genutils only
5211 5224 contains utility functions, and classes have been moved to their
5212 5225 own files (they had enough independent functionality to warrant
5213 5226 it): ConfigLoader, OutputTrap, Struct.
5214 5227
5215 5228 2001-12-05 Fernando Perez <fperez@colorado.edu>
5216 5229
5217 5230 * IPython turns 21! Released version 0.1.21, as a candidate for
5218 5231 public consumption. If all goes well, release in a few days.
5219 5232
5220 5233 * Fixed path bug (files in Extensions/ directory wouldn't be found
5221 5234 unless IPython/ was explicitly in sys.path).
5222 5235
5223 5236 * Extended the FlexCompleter class as MagicCompleter to allow
5224 5237 completion of @-starting lines.
5225 5238
5226 5239 * Created __release__.py file as a central repository for release
5227 5240 info that other files can read from.
5228 5241
5229 5242 * Fixed small bug in logging: when logging was turned on in
5230 5243 mid-session, old lines with special meanings (!@?) were being
5231 5244 logged without the prepended comment, which is necessary since
5232 5245 they are not truly valid python syntax. This should make session
5233 5246 restores produce less errors.
5234 5247
5235 5248 * The namespace cleanup forced me to make a FlexCompleter class
5236 5249 which is nothing but a ripoff of rlcompleter, but with selectable
5237 5250 namespace (rlcompleter only works in __main__.__dict__). I'll try
5238 5251 to submit a note to the authors to see if this change can be
5239 5252 incorporated in future rlcompleter releases (Dec.6: done)
5240 5253
5241 5254 * More fixes to namespace handling. It was a mess! Now all
5242 5255 explicit references to __main__.__dict__ are gone (except when
5243 5256 really needed) and everything is handled through the namespace
5244 5257 dicts in the IPython instance. We seem to be getting somewhere
5245 5258 with this, finally...
5246 5259
5247 5260 * Small documentation updates.
5248 5261
5249 5262 * Created the Extensions directory under IPython (with an
5250 5263 __init__.py). Put the PhysicalQ stuff there. This directory should
5251 5264 be used for all special-purpose extensions.
5252 5265
5253 5266 * File renaming:
5254 5267 ipythonlib --> ipmaker
5255 5268 ipplib --> iplib
5256 5269 This makes a bit more sense in terms of what these files actually do.
5257 5270
5258 5271 * Moved all the classes and functions in ipythonlib to ipplib, so
5259 5272 now ipythonlib only has make_IPython(). This will ease up its
5260 5273 splitting in smaller functional chunks later.
5261 5274
5262 5275 * Cleaned up (done, I think) output of @whos. Better column
5263 5276 formatting, and now shows str(var) for as much as it can, which is
5264 5277 typically what one gets with a 'print var'.
5265 5278
5266 5279 2001-12-04 Fernando Perez <fperez@colorado.edu>
5267 5280
5268 5281 * Fixed namespace problems. Now builtin/IPyhton/user names get
5269 5282 properly reported in their namespace. Internal namespace handling
5270 5283 is finally getting decent (not perfect yet, but much better than
5271 5284 the ad-hoc mess we had).
5272 5285
5273 5286 * Removed -exit option. If people just want to run a python
5274 5287 script, that's what the normal interpreter is for. Less
5275 5288 unnecessary options, less chances for bugs.
5276 5289
5277 5290 * Added a crash handler which generates a complete post-mortem if
5278 5291 IPython crashes. This will help a lot in tracking bugs down the
5279 5292 road.
5280 5293
5281 5294 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
5282 5295 which were boud to functions being reassigned would bypass the
5283 5296 logger, breaking the sync of _il with the prompt counter. This
5284 5297 would then crash IPython later when a new line was logged.
5285 5298
5286 5299 2001-12-02 Fernando Perez <fperez@colorado.edu>
5287 5300
5288 5301 * Made IPython a package. This means people don't have to clutter
5289 5302 their sys.path with yet another directory. Changed the INSTALL
5290 5303 file accordingly.
5291 5304
5292 5305 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
5293 5306 sorts its output (so @who shows it sorted) and @whos formats the
5294 5307 table according to the width of the first column. Nicer, easier to
5295 5308 read. Todo: write a generic table_format() which takes a list of
5296 5309 lists and prints it nicely formatted, with optional row/column
5297 5310 separators and proper padding and justification.
5298 5311
5299 5312 * Released 0.1.20
5300 5313
5301 5314 * Fixed bug in @log which would reverse the inputcache list (a
5302 5315 copy operation was missing).
5303 5316
5304 5317 * Code cleanup. @config was changed to use page(). Better, since
5305 5318 its output is always quite long.
5306 5319
5307 5320 * Itpl is back as a dependency. I was having too many problems
5308 5321 getting the parametric aliases to work reliably, and it's just
5309 5322 easier to code weird string operations with it than playing %()s
5310 5323 games. It's only ~6k, so I don't think it's too big a deal.
5311 5324
5312 5325 * Found (and fixed) a very nasty bug with history. !lines weren't
5313 5326 getting cached, and the out of sync caches would crash
5314 5327 IPython. Fixed it by reorganizing the prefilter/handlers/logger
5315 5328 division of labor a bit better. Bug fixed, cleaner structure.
5316 5329
5317 5330 2001-12-01 Fernando Perez <fperez@colorado.edu>
5318 5331
5319 5332 * Released 0.1.19
5320 5333
5321 5334 * Added option -n to @hist to prevent line number printing. Much
5322 5335 easier to copy/paste code this way.
5323 5336
5324 5337 * Created global _il to hold the input list. Allows easy
5325 5338 re-execution of blocks of code by slicing it (inspired by Janko's
5326 5339 comment on 'macros').
5327 5340
5328 5341 * Small fixes and doc updates.
5329 5342
5330 5343 * Rewrote @history function (was @h). Renamed it to @hist, @h is
5331 5344 much too fragile with automagic. Handles properly multi-line
5332 5345 statements and takes parameters.
5333 5346
5334 5347 2001-11-30 Fernando Perez <fperez@colorado.edu>
5335 5348
5336 5349 * Version 0.1.18 released.
5337 5350
5338 5351 * Fixed nasty namespace bug in initial module imports.
5339 5352
5340 5353 * Added copyright/license notes to all code files (except
5341 5354 DPyGetOpt). For the time being, LGPL. That could change.
5342 5355
5343 5356 * Rewrote a much nicer README, updated INSTALL, cleaned up
5344 5357 ipythonrc-* samples.
5345 5358
5346 5359 * Overall code/documentation cleanup. Basically ready for
5347 5360 release. Only remaining thing: licence decision (LGPL?).
5348 5361
5349 5362 * Converted load_config to a class, ConfigLoader. Now recursion
5350 5363 control is better organized. Doesn't include the same file twice.
5351 5364
5352 5365 2001-11-29 Fernando Perez <fperez@colorado.edu>
5353 5366
5354 5367 * Got input history working. Changed output history variables from
5355 5368 _p to _o so that _i is for input and _o for output. Just cleaner
5356 5369 convention.
5357 5370
5358 5371 * Implemented parametric aliases. This pretty much allows the
5359 5372 alias system to offer full-blown shell convenience, I think.
5360 5373
5361 5374 * Version 0.1.17 released, 0.1.18 opened.
5362 5375
5363 5376 * dot_ipython/ipythonrc (alias): added documentation.
5364 5377 (xcolor): Fixed small bug (xcolors -> xcolor)
5365 5378
5366 5379 * Changed the alias system. Now alias is a magic command to define
5367 5380 aliases just like the shell. Rationale: the builtin magics should
5368 5381 be there for things deeply connected to IPython's
5369 5382 architecture. And this is a much lighter system for what I think
5370 5383 is the really important feature: allowing users to define quickly
5371 5384 magics that will do shell things for them, so they can customize
5372 5385 IPython easily to match their work habits. If someone is really
5373 5386 desperate to have another name for a builtin alias, they can
5374 5387 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
5375 5388 works.
5376 5389
5377 5390 2001-11-28 Fernando Perez <fperez@colorado.edu>
5378 5391
5379 5392 * Changed @file so that it opens the source file at the proper
5380 5393 line. Since it uses less, if your EDITOR environment is
5381 5394 configured, typing v will immediately open your editor of choice
5382 5395 right at the line where the object is defined. Not as quick as
5383 5396 having a direct @edit command, but for all intents and purposes it
5384 5397 works. And I don't have to worry about writing @edit to deal with
5385 5398 all the editors, less does that.
5386 5399
5387 5400 * Version 0.1.16 released, 0.1.17 opened.
5388 5401
5389 5402 * Fixed some nasty bugs in the page/page_dumb combo that could
5390 5403 crash IPython.
5391 5404
5392 5405 2001-11-27 Fernando Perez <fperez@colorado.edu>
5393 5406
5394 5407 * Version 0.1.15 released, 0.1.16 opened.
5395 5408
5396 5409 * Finally got ? and ?? to work for undefined things: now it's
5397 5410 possible to type {}.get? and get information about the get method
5398 5411 of dicts, or os.path? even if only os is defined (so technically
5399 5412 os.path isn't). Works at any level. For example, after import os,
5400 5413 os?, os.path?, os.path.abspath? all work. This is great, took some
5401 5414 work in _ofind.
5402 5415
5403 5416 * Fixed more bugs with logging. The sanest way to do it was to add
5404 5417 to @log a 'mode' parameter. Killed two in one shot (this mode
5405 5418 option was a request of Janko's). I think it's finally clean
5406 5419 (famous last words).
5407 5420
5408 5421 * Added a page_dumb() pager which does a decent job of paging on
5409 5422 screen, if better things (like less) aren't available. One less
5410 5423 unix dependency (someday maybe somebody will port this to
5411 5424 windows).
5412 5425
5413 5426 * Fixed problem in magic_log: would lock of logging out if log
5414 5427 creation failed (because it would still think it had succeeded).
5415 5428
5416 5429 * Improved the page() function using curses to auto-detect screen
5417 5430 size. Now it can make a much better decision on whether to print
5418 5431 or page a string. Option screen_length was modified: a value 0
5419 5432 means auto-detect, and that's the default now.
5420 5433
5421 5434 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
5422 5435 go out. I'll test it for a few days, then talk to Janko about
5423 5436 licences and announce it.
5424 5437
5425 5438 * Fixed the length of the auto-generated ---> prompt which appears
5426 5439 for auto-parens and auto-quotes. Getting this right isn't trivial,
5427 5440 with all the color escapes, different prompt types and optional
5428 5441 separators. But it seems to be working in all the combinations.
5429 5442
5430 5443 2001-11-26 Fernando Perez <fperez@colorado.edu>
5431 5444
5432 5445 * Wrote a regexp filter to get option types from the option names
5433 5446 string. This eliminates the need to manually keep two duplicate
5434 5447 lists.
5435 5448
5436 5449 * Removed the unneeded check_option_names. Now options are handled
5437 5450 in a much saner manner and it's easy to visually check that things
5438 5451 are ok.
5439 5452
5440 5453 * Updated version numbers on all files I modified to carry a
5441 5454 notice so Janko and Nathan have clear version markers.
5442 5455
5443 5456 * Updated docstring for ultraTB with my changes. I should send
5444 5457 this to Nathan.
5445 5458
5446 5459 * Lots of small fixes. Ran everything through pychecker again.
5447 5460
5448 5461 * Made loading of deep_reload an cmd line option. If it's not too
5449 5462 kosher, now people can just disable it. With -nodeep_reload it's
5450 5463 still available as dreload(), it just won't overwrite reload().
5451 5464
5452 5465 * Moved many options to the no| form (-opt and -noopt
5453 5466 accepted). Cleaner.
5454 5467
5455 5468 * Changed magic_log so that if called with no parameters, it uses
5456 5469 'rotate' mode. That way auto-generated logs aren't automatically
5457 5470 over-written. For normal logs, now a backup is made if it exists
5458 5471 (only 1 level of backups). A new 'backup' mode was added to the
5459 5472 Logger class to support this. This was a request by Janko.
5460 5473
5461 5474 * Added @logoff/@logon to stop/restart an active log.
5462 5475
5463 5476 * Fixed a lot of bugs in log saving/replay. It was pretty
5464 5477 broken. Now special lines (!@,/) appear properly in the command
5465 5478 history after a log replay.
5466 5479
5467 5480 * Tried and failed to implement full session saving via pickle. My
5468 5481 idea was to pickle __main__.__dict__, but modules can't be
5469 5482 pickled. This would be a better alternative to replaying logs, but
5470 5483 seems quite tricky to get to work. Changed -session to be called
5471 5484 -logplay, which more accurately reflects what it does. And if we
5472 5485 ever get real session saving working, -session is now available.
5473 5486
5474 5487 * Implemented color schemes for prompts also. As for tracebacks,
5475 5488 currently only NoColor and Linux are supported. But now the
5476 5489 infrastructure is in place, based on a generic ColorScheme
5477 5490 class. So writing and activating new schemes both for the prompts
5478 5491 and the tracebacks should be straightforward.
5479 5492
5480 5493 * Version 0.1.13 released, 0.1.14 opened.
5481 5494
5482 5495 * Changed handling of options for output cache. Now counter is
5483 5496 hardwired starting at 1 and one specifies the maximum number of
5484 5497 entries *in the outcache* (not the max prompt counter). This is
5485 5498 much better, since many statements won't increase the cache
5486 5499 count. It also eliminated some confusing options, now there's only
5487 5500 one: cache_size.
5488 5501
5489 5502 * Added 'alias' magic function and magic_alias option in the
5490 5503 ipythonrc file. Now the user can easily define whatever names he
5491 5504 wants for the magic functions without having to play weird
5492 5505 namespace games. This gives IPython a real shell-like feel.
5493 5506
5494 5507 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
5495 5508 @ or not).
5496 5509
5497 5510 This was one of the last remaining 'visible' bugs (that I know
5498 5511 of). I think if I can clean up the session loading so it works
5499 5512 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
5500 5513 about licensing).
5501 5514
5502 5515 2001-11-25 Fernando Perez <fperez@colorado.edu>
5503 5516
5504 5517 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
5505 5518 there's a cleaner distinction between what ? and ?? show.
5506 5519
5507 5520 * Added screen_length option. Now the user can define his own
5508 5521 screen size for page() operations.
5509 5522
5510 5523 * Implemented magic shell-like functions with automatic code
5511 5524 generation. Now adding another function is just a matter of adding
5512 5525 an entry to a dict, and the function is dynamically generated at
5513 5526 run-time. Python has some really cool features!
5514 5527
5515 5528 * Renamed many options to cleanup conventions a little. Now all
5516 5529 are lowercase, and only underscores where needed. Also in the code
5517 5530 option name tables are clearer.
5518 5531
5519 5532 * Changed prompts a little. Now input is 'In [n]:' instead of
5520 5533 'In[n]:='. This allows it the numbers to be aligned with the
5521 5534 Out[n] numbers, and removes usage of ':=' which doesn't exist in
5522 5535 Python (it was a Mathematica thing). The '...' continuation prompt
5523 5536 was also changed a little to align better.
5524 5537
5525 5538 * Fixed bug when flushing output cache. Not all _p<n> variables
5526 5539 exist, so their deletion needs to be wrapped in a try:
5527 5540
5528 5541 * Figured out how to properly use inspect.formatargspec() (it
5529 5542 requires the args preceded by *). So I removed all the code from
5530 5543 _get_pdef in Magic, which was just replicating that.
5531 5544
5532 5545 * Added test to prefilter to allow redefining magic function names
5533 5546 as variables. This is ok, since the @ form is always available,
5534 5547 but whe should allow the user to define a variable called 'ls' if
5535 5548 he needs it.
5536 5549
5537 5550 * Moved the ToDo information from README into a separate ToDo.
5538 5551
5539 5552 * General code cleanup and small bugfixes. I think it's close to a
5540 5553 state where it can be released, obviously with a big 'beta'
5541 5554 warning on it.
5542 5555
5543 5556 * Got the magic function split to work. Now all magics are defined
5544 5557 in a separate class. It just organizes things a bit, and now
5545 5558 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
5546 5559 was too long).
5547 5560
5548 5561 * Changed @clear to @reset to avoid potential confusions with
5549 5562 the shell command clear. Also renamed @cl to @clear, which does
5550 5563 exactly what people expect it to from their shell experience.
5551 5564
5552 5565 Added a check to the @reset command (since it's so
5553 5566 destructive, it's probably a good idea to ask for confirmation).
5554 5567 But now reset only works for full namespace resetting. Since the
5555 5568 del keyword is already there for deleting a few specific
5556 5569 variables, I don't see the point of having a redundant magic
5557 5570 function for the same task.
5558 5571
5559 5572 2001-11-24 Fernando Perez <fperez@colorado.edu>
5560 5573
5561 5574 * Updated the builtin docs (esp. the ? ones).
5562 5575
5563 5576 * Ran all the code through pychecker. Not terribly impressed with
5564 5577 it: lots of spurious warnings and didn't really find anything of
5565 5578 substance (just a few modules being imported and not used).
5566 5579
5567 5580 * Implemented the new ultraTB functionality into IPython. New
5568 5581 option: xcolors. This chooses color scheme. xmode now only selects
5569 5582 between Plain and Verbose. Better orthogonality.
5570 5583
5571 5584 * Large rewrite of ultraTB. Much cleaner now, with a separation of
5572 5585 mode and color scheme for the exception handlers. Now it's
5573 5586 possible to have the verbose traceback with no coloring.
5574 5587
5575 5588 2001-11-23 Fernando Perez <fperez@colorado.edu>
5576 5589
5577 5590 * Version 0.1.12 released, 0.1.13 opened.
5578 5591
5579 5592 * Removed option to set auto-quote and auto-paren escapes by
5580 5593 user. The chances of breaking valid syntax are just too high. If
5581 5594 someone *really* wants, they can always dig into the code.
5582 5595
5583 5596 * Made prompt separators configurable.
5584 5597
5585 5598 2001-11-22 Fernando Perez <fperez@colorado.edu>
5586 5599
5587 5600 * Small bugfixes in many places.
5588 5601
5589 5602 * Removed the MyCompleter class from ipplib. It seemed redundant
5590 5603 with the C-p,C-n history search functionality. Less code to
5591 5604 maintain.
5592 5605
5593 5606 * Moved all the original ipython.py code into ipythonlib.py. Right
5594 5607 now it's just one big dump into a function called make_IPython, so
5595 5608 no real modularity has been gained. But at least it makes the
5596 5609 wrapper script tiny, and since ipythonlib is a module, it gets
5597 5610 compiled and startup is much faster.
5598 5611
5599 5612 This is a reasobably 'deep' change, so we should test it for a
5600 5613 while without messing too much more with the code.
5601 5614
5602 5615 2001-11-21 Fernando Perez <fperez@colorado.edu>
5603 5616
5604 5617 * Version 0.1.11 released, 0.1.12 opened for further work.
5605 5618
5606 5619 * Removed dependency on Itpl. It was only needed in one place. It
5607 5620 would be nice if this became part of python, though. It makes life
5608 5621 *a lot* easier in some cases.
5609 5622
5610 5623 * Simplified the prefilter code a bit. Now all handlers are
5611 5624 expected to explicitly return a value (at least a blank string).
5612 5625
5613 5626 * Heavy edits in ipplib. Removed the help system altogether. Now
5614 5627 obj?/?? is used for inspecting objects, a magic @doc prints
5615 5628 docstrings, and full-blown Python help is accessed via the 'help'
5616 5629 keyword. This cleans up a lot of code (less to maintain) and does
5617 5630 the job. Since 'help' is now a standard Python component, might as
5618 5631 well use it and remove duplicate functionality.
5619 5632
5620 5633 Also removed the option to use ipplib as a standalone program. By
5621 5634 now it's too dependent on other parts of IPython to function alone.
5622 5635
5623 5636 * Fixed bug in genutils.pager. It would crash if the pager was
5624 5637 exited immediately after opening (broken pipe).
5625 5638
5626 5639 * Trimmed down the VerboseTB reporting a little. The header is
5627 5640 much shorter now and the repeated exception arguments at the end
5628 5641 have been removed. For interactive use the old header seemed a bit
5629 5642 excessive.
5630 5643
5631 5644 * Fixed small bug in output of @whos for variables with multi-word
5632 5645 types (only first word was displayed).
5633 5646
5634 5647 2001-11-17 Fernando Perez <fperez@colorado.edu>
5635 5648
5636 5649 * Version 0.1.10 released, 0.1.11 opened for further work.
5637 5650
5638 5651 * Modified dirs and friends. dirs now *returns* the stack (not
5639 5652 prints), so one can manipulate it as a variable. Convenient to
5640 5653 travel along many directories.
5641 5654
5642 5655 * Fixed bug in magic_pdef: would only work with functions with
5643 5656 arguments with default values.
5644 5657
5645 5658 2001-11-14 Fernando Perez <fperez@colorado.edu>
5646 5659
5647 5660 * Added the PhysicsInput stuff to dot_ipython so it ships as an
5648 5661 example with IPython. Various other minor fixes and cleanups.
5649 5662
5650 5663 * Version 0.1.9 released, 0.1.10 opened for further work.
5651 5664
5652 5665 * Added sys.path to the list of directories searched in the
5653 5666 execfile= option. It used to be the current directory and the
5654 5667 user's IPYTHONDIR only.
5655 5668
5656 5669 2001-11-13 Fernando Perez <fperez@colorado.edu>
5657 5670
5658 5671 * Reinstated the raw_input/prefilter separation that Janko had
5659 5672 initially. This gives a more convenient setup for extending the
5660 5673 pre-processor from the outside: raw_input always gets a string,
5661 5674 and prefilter has to process it. We can then redefine prefilter
5662 5675 from the outside and implement extensions for special
5663 5676 purposes.
5664 5677
5665 5678 Today I got one for inputting PhysicalQuantity objects
5666 5679 (from Scientific) without needing any function calls at
5667 5680 all. Extremely convenient, and it's all done as a user-level
5668 5681 extension (no IPython code was touched). Now instead of:
5669 5682 a = PhysicalQuantity(4.2,'m/s**2')
5670 5683 one can simply say
5671 5684 a = 4.2 m/s**2
5672 5685 or even
5673 5686 a = 4.2 m/s^2
5674 5687
5675 5688 I use this, but it's also a proof of concept: IPython really is
5676 5689 fully user-extensible, even at the level of the parsing of the
5677 5690 command line. It's not trivial, but it's perfectly doable.
5678 5691
5679 5692 * Added 'add_flip' method to inclusion conflict resolver. Fixes
5680 5693 the problem of modules being loaded in the inverse order in which
5681 5694 they were defined in
5682 5695
5683 5696 * Version 0.1.8 released, 0.1.9 opened for further work.
5684 5697
5685 5698 * Added magics pdef, source and file. They respectively show the
5686 5699 definition line ('prototype' in C), source code and full python
5687 5700 file for any callable object. The object inspector oinfo uses
5688 5701 these to show the same information.
5689 5702
5690 5703 * Version 0.1.7 released, 0.1.8 opened for further work.
5691 5704
5692 5705 * Separated all the magic functions into a class called Magic. The
5693 5706 InteractiveShell class was becoming too big for Xemacs to handle
5694 5707 (de-indenting a line would lock it up for 10 seconds while it
5695 5708 backtracked on the whole class!)
5696 5709
5697 5710 FIXME: didn't work. It can be done, but right now namespaces are
5698 5711 all messed up. Do it later (reverted it for now, so at least
5699 5712 everything works as before).
5700 5713
5701 5714 * Got the object introspection system (magic_oinfo) working! I
5702 5715 think this is pretty much ready for release to Janko, so he can
5703 5716 test it for a while and then announce it. Pretty much 100% of what
5704 5717 I wanted for the 'phase 1' release is ready. Happy, tired.
5705 5718
5706 5719 2001-11-12 Fernando Perez <fperez@colorado.edu>
5707 5720
5708 5721 * Version 0.1.6 released, 0.1.7 opened for further work.
5709 5722
5710 5723 * Fixed bug in printing: it used to test for truth before
5711 5724 printing, so 0 wouldn't print. Now checks for None.
5712 5725
5713 5726 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
5714 5727 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
5715 5728 reaches by hand into the outputcache. Think of a better way to do
5716 5729 this later.
5717 5730
5718 5731 * Various small fixes thanks to Nathan's comments.
5719 5732
5720 5733 * Changed magic_pprint to magic_Pprint. This way it doesn't
5721 5734 collide with pprint() and the name is consistent with the command
5722 5735 line option.
5723 5736
5724 5737 * Changed prompt counter behavior to be fully like
5725 5738 Mathematica's. That is, even input that doesn't return a result
5726 5739 raises the prompt counter. The old behavior was kind of confusing
5727 5740 (getting the same prompt number several times if the operation
5728 5741 didn't return a result).
5729 5742
5730 5743 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
5731 5744
5732 5745 * Fixed -Classic mode (wasn't working anymore).
5733 5746
5734 5747 * Added colored prompts using Nathan's new code. Colors are
5735 5748 currently hardwired, they can be user-configurable. For
5736 5749 developers, they can be chosen in file ipythonlib.py, at the
5737 5750 beginning of the CachedOutput class def.
5738 5751
5739 5752 2001-11-11 Fernando Perez <fperez@colorado.edu>
5740 5753
5741 5754 * Version 0.1.5 released, 0.1.6 opened for further work.
5742 5755
5743 5756 * Changed magic_env to *return* the environment as a dict (not to
5744 5757 print it). This way it prints, but it can also be processed.
5745 5758
5746 5759 * Added Verbose exception reporting to interactive
5747 5760 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
5748 5761 traceback. Had to make some changes to the ultraTB file. This is
5749 5762 probably the last 'big' thing in my mental todo list. This ties
5750 5763 in with the next entry:
5751 5764
5752 5765 * Changed -Xi and -Xf to a single -xmode option. Now all the user
5753 5766 has to specify is Plain, Color or Verbose for all exception
5754 5767 handling.
5755 5768
5756 5769 * Removed ShellServices option. All this can really be done via
5757 5770 the magic system. It's easier to extend, cleaner and has automatic
5758 5771 namespace protection and documentation.
5759 5772
5760 5773 2001-11-09 Fernando Perez <fperez@colorado.edu>
5761 5774
5762 5775 * Fixed bug in output cache flushing (missing parameter to
5763 5776 __init__). Other small bugs fixed (found using pychecker).
5764 5777
5765 5778 * Version 0.1.4 opened for bugfixing.
5766 5779
5767 5780 2001-11-07 Fernando Perez <fperez@colorado.edu>
5768 5781
5769 5782 * Version 0.1.3 released, mainly because of the raw_input bug.
5770 5783
5771 5784 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
5772 5785 and when testing for whether things were callable, a call could
5773 5786 actually be made to certain functions. They would get called again
5774 5787 once 'really' executed, with a resulting double call. A disaster
5775 5788 in many cases (list.reverse() would never work!).
5776 5789
5777 5790 * Removed prefilter() function, moved its code to raw_input (which
5778 5791 after all was just a near-empty caller for prefilter). This saves
5779 5792 a function call on every prompt, and simplifies the class a tiny bit.
5780 5793
5781 5794 * Fix _ip to __ip name in magic example file.
5782 5795
5783 5796 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
5784 5797 work with non-gnu versions of tar.
5785 5798
5786 5799 2001-11-06 Fernando Perez <fperez@colorado.edu>
5787 5800
5788 5801 * Version 0.1.2. Just to keep track of the recent changes.
5789 5802
5790 5803 * Fixed nasty bug in output prompt routine. It used to check 'if
5791 5804 arg != None...'. Problem is, this fails if arg implements a
5792 5805 special comparison (__cmp__) which disallows comparing to
5793 5806 None. Found it when trying to use the PhysicalQuantity module from
5794 5807 ScientificPython.
5795 5808
5796 5809 2001-11-05 Fernando Perez <fperez@colorado.edu>
5797 5810
5798 5811 * Also added dirs. Now the pushd/popd/dirs family functions
5799 5812 basically like the shell, with the added convenience of going home
5800 5813 when called with no args.
5801 5814
5802 5815 * pushd/popd slightly modified to mimic shell behavior more
5803 5816 closely.
5804 5817
5805 5818 * Added env,pushd,popd from ShellServices as magic functions. I
5806 5819 think the cleanest will be to port all desired functions from
5807 5820 ShellServices as magics and remove ShellServices altogether. This
5808 5821 will provide a single, clean way of adding functionality
5809 5822 (shell-type or otherwise) to IP.
5810 5823
5811 5824 2001-11-04 Fernando Perez <fperez@colorado.edu>
5812 5825
5813 5826 * Added .ipython/ directory to sys.path. This way users can keep
5814 5827 customizations there and access them via import.
5815 5828
5816 5829 2001-11-03 Fernando Perez <fperez@colorado.edu>
5817 5830
5818 5831 * Opened version 0.1.1 for new changes.
5819 5832
5820 5833 * Changed version number to 0.1.0: first 'public' release, sent to
5821 5834 Nathan and Janko.
5822 5835
5823 5836 * Lots of small fixes and tweaks.
5824 5837
5825 5838 * Minor changes to whos format. Now strings are shown, snipped if
5826 5839 too long.
5827 5840
5828 5841 * Changed ShellServices to work on __main__ so they show up in @who
5829 5842
5830 5843 * Help also works with ? at the end of a line:
5831 5844 ?sin and sin?
5832 5845 both produce the same effect. This is nice, as often I use the
5833 5846 tab-complete to find the name of a method, but I used to then have
5834 5847 to go to the beginning of the line to put a ? if I wanted more
5835 5848 info. Now I can just add the ? and hit return. Convenient.
5836 5849
5837 5850 2001-11-02 Fernando Perez <fperez@colorado.edu>
5838 5851
5839 5852 * Python version check (>=2.1) added.
5840 5853
5841 5854 * Added LazyPython documentation. At this point the docs are quite
5842 5855 a mess. A cleanup is in order.
5843 5856
5844 5857 * Auto-installer created. For some bizarre reason, the zipfiles
5845 5858 module isn't working on my system. So I made a tar version
5846 5859 (hopefully the command line options in various systems won't kill
5847 5860 me).
5848 5861
5849 5862 * Fixes to Struct in genutils. Now all dictionary-like methods are
5850 5863 protected (reasonably).
5851 5864
5852 5865 * Added pager function to genutils and changed ? to print usage
5853 5866 note through it (it was too long).
5854 5867
5855 5868 * Added the LazyPython functionality. Works great! I changed the
5856 5869 auto-quote escape to ';', it's on home row and next to '. But
5857 5870 both auto-quote and auto-paren (still /) escapes are command-line
5858 5871 parameters.
5859 5872
5860 5873
5861 5874 2001-11-01 Fernando Perez <fperez@colorado.edu>
5862 5875
5863 5876 * Version changed to 0.0.7. Fairly large change: configuration now
5864 5877 is all stored in a directory, by default .ipython. There, all
5865 5878 config files have normal looking names (not .names)
5866 5879
5867 5880 * Version 0.0.6 Released first to Lucas and Archie as a test
5868 5881 run. Since it's the first 'semi-public' release, change version to
5869 5882 > 0.0.6 for any changes now.
5870 5883
5871 5884 * Stuff I had put in the ipplib.py changelog:
5872 5885
5873 5886 Changes to InteractiveShell:
5874 5887
5875 5888 - Made the usage message a parameter.
5876 5889
5877 5890 - Require the name of the shell variable to be given. It's a bit
5878 5891 of a hack, but allows the name 'shell' not to be hardwired in the
5879 5892 magic (@) handler, which is problematic b/c it requires
5880 5893 polluting the global namespace with 'shell'. This in turn is
5881 5894 fragile: if a user redefines a variable called shell, things
5882 5895 break.
5883 5896
5884 5897 - magic @: all functions available through @ need to be defined
5885 5898 as magic_<name>, even though they can be called simply as
5886 5899 @<name>. This allows the special command @magic to gather
5887 5900 information automatically about all existing magic functions,
5888 5901 even if they are run-time user extensions, by parsing the shell
5889 5902 instance __dict__ looking for special magic_ names.
5890 5903
5891 5904 - mainloop: added *two* local namespace parameters. This allows
5892 5905 the class to differentiate between parameters which were there
5893 5906 before and after command line initialization was processed. This
5894 5907 way, later @who can show things loaded at startup by the
5895 5908 user. This trick was necessary to make session saving/reloading
5896 5909 really work: ideally after saving/exiting/reloading a session,
5897 5910 *everything* should look the same, including the output of @who. I
5898 5911 was only able to make this work with this double namespace
5899 5912 trick.
5900 5913
5901 5914 - added a header to the logfile which allows (almost) full
5902 5915 session restoring.
5903 5916
5904 5917 - prepend lines beginning with @ or !, with a and log
5905 5918 them. Why? !lines: may be useful to know what you did @lines:
5906 5919 they may affect session state. So when restoring a session, at
5907 5920 least inform the user of their presence. I couldn't quite get
5908 5921 them to properly re-execute, but at least the user is warned.
5909 5922
5910 5923 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now