##// END OF EJS Templates
- Add autocall 'smart' mode....
fperez -
Show More
@@ -1,2706 +1,2707 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 988 2006-01-02 21:21:47Z fperez $"""
4 $Id: Magic.py 990 2006-01-04 06:59:02Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import bdb
25 25 import inspect
26 26 import os
27 27 import pdb
28 28 import pydoc
29 29 import sys
30 30 import re
31 31 import tempfile
32 32 import time
33 33 import cPickle as pickle
34 34 from cStringIO import StringIO
35 35 from getopt import getopt
36 36 from pprint import pprint, pformat
37 37
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 # Homebrewed
45 45 from IPython import Debugger, OInspect, wildcard
46 46 from IPython.FakeModule import FakeModule
47 47 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 48 from IPython.PyColorize import Parser
49 49 from IPython.Struct import Struct
50 50 from IPython.macro import Macro
51 51 from IPython.genutils import *
52 52
53 53 #***************************************************************************
54 54 # Utility functions
55 55 def on_off(tag):
56 56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
57 57 return ['OFF','ON'][tag]
58 58
59 59
60 60 #***************************************************************************
61 61 # Main class implementing Magic functionality
62 62 class Magic:
63 63 """Magic functions for InteractiveShell.
64 64
65 65 Shell functions which can be reached as %function_name. All magic
66 66 functions should accept a string, which they can parse for their own
67 67 needs. This can make some functions easier to type, eg `%cd ../`
68 68 vs. `%cd("../")`
69 69
70 70 ALL definitions MUST begin with the prefix magic_. The user won't need it
71 71 at the command line, but it is is needed in the definition. """
72 72
73 73 # class globals
74 74 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
75 75 'Automagic is ON, % prefix NOT needed for magic functions.']
76 76
77 77 #......................................................................
78 78 # some utility functions
79 79
80 80 def __init__(self,shell):
81 81
82 82 self.options_table = {}
83 83 if profile is None:
84 84 self.magic_prun = self.profile_missing_notice
85 85 self.shell = shell
86 86
87 87 def profile_missing_notice(self, *args, **kwargs):
88 88 error("""\
89 89 The profile module could not be found. If you are a Debian user,
90 90 it has been removed from the standard Debian package because of its non-free
91 91 license. To use profiling, please install"python2.3-profiler" from non-free.""")
92 92
93 93 def default_option(self,fn,optstr):
94 94 """Make an entry in the options_table for fn, with value optstr"""
95 95
96 96 if fn not in self.lsmagic():
97 97 error("%s is not a magic function" % fn)
98 98 self.options_table[fn] = optstr
99 99
100 100 def lsmagic(self):
101 101 """Return a list of currently available magic functions.
102 102
103 103 Gives a list of the bare names after mangling (['ls','cd', ...], not
104 104 ['magic_ls','magic_cd',...]"""
105 105
106 106 # FIXME. This needs a cleanup, in the way the magics list is built.
107 107
108 108 # magics in class definition
109 109 class_magic = lambda fn: fn.startswith('magic_') and \
110 110 callable(Magic.__dict__[fn])
111 111 # in instance namespace (run-time user additions)
112 112 inst_magic = lambda fn: fn.startswith('magic_') and \
113 113 callable(self.__dict__[fn])
114 114 # and bound magics by user (so they can access self):
115 115 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
116 116 callable(self.__class__.__dict__[fn])
117 117 magics = filter(class_magic,Magic.__dict__.keys()) + \
118 118 filter(inst_magic,self.__dict__.keys()) + \
119 119 filter(inst_bound_magic,self.__class__.__dict__.keys())
120 120 out = []
121 121 for fn in magics:
122 122 out.append(fn.replace('magic_','',1))
123 123 out.sort()
124 124 return out
125 125
126 126 def extract_input_slices(self,slices):
127 127 """Return as a string a set of input history slices.
128 128
129 129 The set of slices is given as a list of strings (like ['1','4:8','9'],
130 130 since this function is for use by magic functions which get their
131 131 arguments as strings.
132 132
133 133 Note that slices can be called with two notations:
134 134
135 135 N:M -> standard python form, means including items N...(M-1).
136 136
137 137 N-M -> include items N..M (closed endpoint)."""
138 138
139 139 cmds = []
140 140 for chunk in slices:
141 141 if ':' in chunk:
142 142 ini,fin = map(int,chunk.split(':'))
143 143 elif '-' in chunk:
144 144 ini,fin = map(int,chunk.split('-'))
145 145 fin += 1
146 146 else:
147 147 ini = int(chunk)
148 148 fin = ini+1
149 149 cmds.append(self.shell.input_hist[ini:fin])
150 150 return cmds
151 151
152 152 def _ofind(self,oname):
153 153 """Find an object in the available namespaces.
154 154
155 155 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
156 156
157 157 Has special code to detect magic functions.
158 158 """
159 159
160 160 oname = oname.strip()
161 161
162 162 # Namespaces to search in:
163 163 user_ns = self.shell.user_ns
164 164 internal_ns = self.shell.internal_ns
165 165 builtin_ns = __builtin__.__dict__
166 166 alias_ns = self.shell.alias_table
167 167
168 168 # Put them in a list. The order is important so that we find things in
169 169 # the same order that Python finds them.
170 170 namespaces = [ ('Interactive',user_ns),
171 171 ('IPython internal',internal_ns),
172 172 ('Python builtin',builtin_ns),
173 173 ('Alias',alias_ns),
174 174 ]
175 175
176 176 # initialize results to 'null'
177 177 found = 0; obj = None; ospace = None; ds = None;
178 178 ismagic = 0; isalias = 0
179 179
180 180 # Look for the given name by splitting it in parts. If the head is
181 181 # found, then we look for all the remaining parts as members, and only
182 182 # declare success if we can find them all.
183 183 oname_parts = oname.split('.')
184 184 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
185 185 for nsname,ns in namespaces:
186 186 try:
187 187 obj = ns[oname_head]
188 188 except KeyError:
189 189 continue
190 190 else:
191 191 for part in oname_rest:
192 192 try:
193 193 obj = getattr(obj,part)
194 194 except:
195 195 # Blanket except b/c some badly implemented objects
196 196 # allow __getattr__ to raise exceptions other than
197 197 # AttributeError, which then crashes IPython.
198 198 break
199 199 else:
200 200 # If we finish the for loop (no break), we got all members
201 201 found = 1
202 202 ospace = nsname
203 203 if ns == alias_ns:
204 204 isalias = 1
205 205 break # namespace loop
206 206
207 207 # Try to see if it's magic
208 208 if not found:
209 209 if oname.startswith(self.shell.ESC_MAGIC):
210 210 oname = oname[1:]
211 211 obj = getattr(self,'magic_'+oname,None)
212 212 if obj is not None:
213 213 found = 1
214 214 ospace = 'IPython internal'
215 215 ismagic = 1
216 216
217 217 # Last try: special-case some literals like '', [], {}, etc:
218 218 if not found and oname_head in ["''",'""','[]','{}','()']:
219 219 obj = eval(oname_head)
220 220 found = 1
221 221 ospace = 'Interactive'
222 222
223 223 return {'found':found, 'obj':obj, 'namespace':ospace,
224 224 'ismagic':ismagic, 'isalias':isalias}
225 225
226 226 def arg_err(self,func):
227 227 """Print docstring if incorrect arguments were passed"""
228 228 print 'Error in arguments:'
229 229 print OInspect.getdoc(func)
230 230
231 231 def format_latex(self,strng):
232 232 """Format a string for latex inclusion."""
233 233
234 234 # Characters that need to be escaped for latex:
235 235 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
236 236 # Magic command names as headers:
237 237 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
238 238 re.MULTILINE)
239 239 # Magic commands
240 240 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
241 241 re.MULTILINE)
242 242 # Paragraph continue
243 243 par_re = re.compile(r'\\$',re.MULTILINE)
244 244
245 245 # The "\n" symbol
246 246 newline_re = re.compile(r'\\n')
247 247
248 248 # Now build the string for output:
249 249 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
250 250 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
251 251 strng = par_re.sub(r'\\\\',strng)
252 252 strng = escape_re.sub(r'\\\1',strng)
253 253 strng = newline_re.sub(r'\\textbackslash{}n',strng)
254 254 return strng
255 255
256 256 def format_screen(self,strng):
257 257 """Format a string for screen printing.
258 258
259 259 This removes some latex-type format codes."""
260 260 # Paragraph continue
261 261 par_re = re.compile(r'\\$',re.MULTILINE)
262 262 strng = par_re.sub('',strng)
263 263 return strng
264 264
265 265 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
266 266 """Parse options passed to an argument string.
267 267
268 268 The interface is similar to that of getopt(), but it returns back a
269 269 Struct with the options as keys and the stripped argument string still
270 270 as a string.
271 271
272 272 arg_str is quoted as a true sys.argv vector by using shlex.split.
273 273 This allows us to easily expand variables, glob files, quote
274 274 arguments, etc.
275 275
276 276 Options:
277 277 -mode: default 'string'. If given as 'list', the argument string is
278 278 returned as a list (split on whitespace) instead of a string.
279 279
280 280 -list_all: put all option values in lists. Normally only options
281 281 appearing more than once are put in a list."""
282 282
283 283 # inject default options at the beginning of the input line
284 284 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
285 285 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
286 286
287 287 mode = kw.get('mode','string')
288 288 if mode not in ['string','list']:
289 289 raise ValueError,'incorrect mode given: %s' % mode
290 290 # Get options
291 291 list_all = kw.get('list_all',0)
292 292
293 293 # Check if we have more than one argument to warrant extra processing:
294 294 odict = {} # Dictionary with options
295 295 args = arg_str.split()
296 296 if len(args) >= 1:
297 297 # If the list of inputs only has 0 or 1 thing in it, there's no
298 298 # need to look for options
299 299 argv = shlex_split(arg_str)
300 300 # Do regular option processing
301 301 opts,args = getopt(argv,opt_str,*long_opts)
302 302 for o,a in opts:
303 303 if o.startswith('--'):
304 304 o = o[2:]
305 305 else:
306 306 o = o[1:]
307 307 try:
308 308 odict[o].append(a)
309 309 except AttributeError:
310 310 odict[o] = [odict[o],a]
311 311 except KeyError:
312 312 if list_all:
313 313 odict[o] = [a]
314 314 else:
315 315 odict[o] = a
316 316
317 317 # Prepare opts,args for return
318 318 opts = Struct(odict)
319 319 if mode == 'string':
320 320 args = ' '.join(args)
321 321
322 322 return opts,args
323 323
324 324 #......................................................................
325 325 # And now the actual magic functions
326 326
327 327 # Functions for IPython shell work (vars,funcs, config, etc)
328 328 def magic_lsmagic(self, parameter_s = ''):
329 329 """List currently available magic functions."""
330 330 mesc = self.shell.ESC_MAGIC
331 331 print 'Available magic functions:\n'+mesc+\
332 332 (' '+mesc).join(self.lsmagic())
333 333 print '\n' + Magic.auto_status[self.shell.rc.automagic]
334 334 return None
335 335
336 336 def magic_magic(self, parameter_s = ''):
337 337 """Print information about the magic function system."""
338 338
339 339 mode = ''
340 340 try:
341 341 if parameter_s.split()[0] == '-latex':
342 342 mode = 'latex'
343 343 except:
344 344 pass
345 345
346 346 magic_docs = []
347 347 for fname in self.lsmagic():
348 348 mname = 'magic_' + fname
349 349 for space in (Magic,self,self.__class__):
350 350 try:
351 351 fn = space.__dict__[mname]
352 352 except KeyError:
353 353 pass
354 354 else:
355 355 break
356 356 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
357 357 fname,fn.__doc__))
358 358 magic_docs = ''.join(magic_docs)
359 359
360 360 if mode == 'latex':
361 361 print self.format_latex(magic_docs)
362 362 return
363 363 else:
364 364 magic_docs = self.format_screen(magic_docs)
365 365
366 366 outmsg = """
367 367 IPython's 'magic' functions
368 368 ===========================
369 369
370 370 The magic function system provides a series of functions which allow you to
371 371 control the behavior of IPython itself, plus a lot of system-type
372 372 features. All these functions are prefixed with a % character, but parameters
373 373 are given without parentheses or quotes.
374 374
375 375 NOTE: If you have 'automagic' enabled (via the command line option or with the
376 376 %automagic function), you don't need to type in the % explicitly. By default,
377 377 IPython ships with automagic on, so you should only rarely need the % escape.
378 378
379 379 Example: typing '%cd mydir' (without the quotes) changes you working directory
380 380 to 'mydir', if it exists.
381 381
382 382 You can define your own magic functions to extend the system. See the supplied
383 383 ipythonrc and example-magic.py files for details (in your ipython
384 384 configuration directory, typically $HOME/.ipython/).
385 385
386 386 You can also define your own aliased names for magic functions. In your
387 387 ipythonrc file, placing a line like:
388 388
389 389 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
390 390
391 391 will define %pf as a new name for %profile.
392 392
393 393 You can also call magics in code using the ipmagic() function, which IPython
394 394 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
395 395
396 396 For a list of the available magic functions, use %lsmagic. For a description
397 397 of any of them, type %magic_name?, e.g. '%cd?'.
398 398
399 399 Currently the magic system has the following functions:\n"""
400 400
401 401 mesc = self.shell.ESC_MAGIC
402 402 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
403 403 "\n\n%s%s\n\n%s" % (outmsg,
404 404 magic_docs,mesc,mesc,
405 405 (' '+mesc).join(self.lsmagic()),
406 406 Magic.auto_status[self.shell.rc.automagic] ) )
407 407
408 408 page(outmsg,screen_lines=self.shell.rc.screen_length)
409 409
410 410 def magic_automagic(self, parameter_s = ''):
411 411 """Make magic functions callable without having to type the initial %.
412 412
413 413 Toggles on/off (when off, you must call it as %automagic, of
414 414 course). Note that magic functions have lowest priority, so if there's
415 415 a variable whose name collides with that of a magic fn, automagic
416 416 won't work for that function (you get the variable instead). However,
417 417 if you delete the variable (del var), the previously shadowed magic
418 418 function becomes visible to automagic again."""
419 419
420 420 rc = self.shell.rc
421 421 rc.automagic = not rc.automagic
422 422 print '\n' + Magic.auto_status[rc.automagic]
423 423
424 424 def magic_autocall(self, parameter_s = ''):
425 425 """Make functions callable without having to type parentheses.
426 426
427 This toggles the autocall command line option on and off."""
427 This cycles the autocall command line through its three valid values
428 (0->Off, 1->Smart, 2->Full)"""
428 429
429 430 rc = self.shell.rc
430 431 rc.autocall = not rc.autocall
431 print "Automatic calling is:",['OFF','ON'][rc.autocall]
432 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
432 433
433 434 def magic_autoindent(self, parameter_s = ''):
434 435 """Toggle autoindent on/off (if available)."""
435 436
436 437 self.shell.set_autoindent()
437 438 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
438 439
439 440 def magic_system_verbose(self, parameter_s = ''):
440 441 """Toggle verbose printing of system calls on/off."""
441 442
442 443 self.shell.rc_set_toggle('system_verbose')
443 444 print "System verbose printing is:",\
444 445 ['OFF','ON'][self.shell.rc.system_verbose]
445 446
446 447 def magic_history(self, parameter_s = ''):
447 448 """Print input history (_i<n> variables), with most recent last.
448 449
449 450 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
450 451 %history [-n] n -> print at most n inputs\\
451 452 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
452 453
453 454 Each input's number <n> is shown, and is accessible as the
454 455 automatically generated variable _i<n>. Multi-line statements are
455 456 printed starting at a new line for easy copy/paste.
456 457
457 458 If option -n is used, input numbers are not printed. This is useful if
458 459 you want to get a printout of many lines which can be directly pasted
459 460 into a text editor.
460 461
461 462 This feature is only available if numbered prompts are in use."""
462 463
463 464 shell = self.shell
464 465 if not shell.outputcache.do_full_cache:
465 466 print 'This feature is only available if numbered prompts are in use.'
466 467 return
467 468 opts,args = self.parse_options(parameter_s,'n',mode='list')
468 469
469 470 input_hist = shell.input_hist
470 471 default_length = 40
471 472 if len(args) == 0:
472 473 final = len(input_hist)
473 474 init = max(1,final-default_length)
474 475 elif len(args) == 1:
475 476 final = len(input_hist)
476 477 init = max(1,final-int(args[0]))
477 478 elif len(args) == 2:
478 479 init,final = map(int,args)
479 480 else:
480 481 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
481 482 print self.magic_hist.__doc__
482 483 return
483 484 width = len(str(final))
484 485 line_sep = ['','\n']
485 486 print_nums = not opts.has_key('n')
486 487 for in_num in range(init,final):
487 488 inline = input_hist[in_num]
488 489 multiline = int(inline.count('\n') > 1)
489 490 if print_nums:
490 491 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
491 492 print inline,
492 493
493 494 def magic_hist(self, parameter_s=''):
494 495 """Alternate name for %history."""
495 496 return self.magic_history(parameter_s)
496 497
497 498 def magic_p(self, parameter_s=''):
498 499 """Just a short alias for Python's 'print'."""
499 500 exec 'print ' + parameter_s in self.shell.user_ns
500 501
501 502 def magic_r(self, parameter_s=''):
502 503 """Repeat previous input.
503 504
504 505 If given an argument, repeats the previous command which starts with
505 506 the same string, otherwise it just repeats the previous input.
506 507
507 508 Shell escaped commands (with ! as first character) are not recognized
508 509 by this system, only pure python code and magic commands.
509 510 """
510 511
511 512 start = parameter_s.strip()
512 513 esc_magic = self.shell.ESC_MAGIC
513 514 # Identify magic commands even if automagic is on (which means
514 515 # the in-memory version is different from that typed by the user).
515 516 if self.shell.rc.automagic:
516 517 start_magic = esc_magic+start
517 518 else:
518 519 start_magic = start
519 520 # Look through the input history in reverse
520 521 for n in range(len(self.shell.input_hist)-2,0,-1):
521 522 input = self.shell.input_hist[n]
522 523 # skip plain 'r' lines so we don't recurse to infinity
523 524 if input != 'ipmagic("r")\n' and \
524 525 (input.startswith(start) or input.startswith(start_magic)):
525 526 #print 'match',`input` # dbg
526 527 print 'Executing:',input,
527 528 self.shell.runlines(input)
528 529 return
529 530 print 'No previous input matching `%s` found.' % start
530 531
531 532 def magic_page(self, parameter_s=''):
532 533 """Pretty print the object and display it through a pager.
533 534
534 535 If no parameter is given, use _ (last output)."""
535 536 # After a function contributed by Olivier Aubert, slightly modified.
536 537
537 538 oname = parameter_s and parameter_s or '_'
538 539 info = self._ofind(oname)
539 540 if info['found']:
540 541 page(pformat(info['obj']))
541 542 else:
542 543 print 'Object `%s` not found' % oname
543 544
544 545 def magic_profile(self, parameter_s=''):
545 546 """Print your currently active IPyhton profile."""
546 547 if self.shell.rc.profile:
547 548 printpl('Current IPython profile: $self.shell.rc.profile.')
548 549 else:
549 550 print 'No profile active.'
550 551
551 552 def _inspect(self,meth,oname,**kw):
552 553 """Generic interface to the inspector system.
553 554
554 555 This function is meant to be called by pdef, pdoc & friends."""
555 556
556 557 oname = oname.strip()
557 558 info = Struct(self._ofind(oname))
558 559 if info.found:
559 560 pmethod = getattr(self.shell.inspector,meth)
560 561 formatter = info.ismagic and self.format_screen or None
561 562 if meth == 'pdoc':
562 563 pmethod(info.obj,oname,formatter)
563 564 elif meth == 'pinfo':
564 565 pmethod(info.obj,oname,formatter,info,**kw)
565 566 else:
566 567 pmethod(info.obj,oname)
567 568 else:
568 569 print 'Object `%s` not found.' % oname
569 570 return 'not found' # so callers can take other action
570 571
571 572 def magic_pdef(self, parameter_s=''):
572 573 """Print the definition header for any callable object.
573 574
574 575 If the object is a class, print the constructor information."""
575 576 self._inspect('pdef',parameter_s)
576 577
577 578 def magic_pdoc(self, parameter_s=''):
578 579 """Print the docstring for an object.
579 580
580 581 If the given object is a class, it will print both the class and the
581 582 constructor docstrings."""
582 583 self._inspect('pdoc',parameter_s)
583 584
584 585 def magic_psource(self, parameter_s=''):
585 586 """Print (or run through pager) the source code for an object."""
586 587 self._inspect('psource',parameter_s)
587 588
588 589 def magic_pfile(self, parameter_s=''):
589 590 """Print (or run through pager) the file where an object is defined.
590 591
591 592 The file opens at the line where the object definition begins. IPython
592 593 will honor the environment variable PAGER if set, and otherwise will
593 594 do its best to print the file in a convenient form.
594 595
595 596 If the given argument is not an object currently defined, IPython will
596 597 try to interpret it as a filename (automatically adding a .py extension
597 598 if needed). You can thus use %pfile as a syntax highlighting code
598 599 viewer."""
599 600
600 601 # first interpret argument as an object name
601 602 out = self._inspect('pfile',parameter_s)
602 603 # if not, try the input as a filename
603 604 if out == 'not found':
604 605 try:
605 606 filename = get_py_filename(parameter_s)
606 607 except IOError,msg:
607 608 print msg
608 609 return
609 610 page(self.shell.inspector.format(file(filename).read()))
610 611
611 612 def magic_pinfo(self, parameter_s=''):
612 613 """Provide detailed information about an object.
613 614
614 615 '%pinfo object' is just a synonym for object? or ?object."""
615 616
616 617 #print 'pinfo par: <%s>' % parameter_s # dbg
617 618
618 619 # detail_level: 0 -> obj? , 1 -> obj??
619 620 detail_level = 0
620 621 # We need to detect if we got called as 'pinfo pinfo foo', which can
621 622 # happen if the user types 'pinfo foo?' at the cmd line.
622 623 pinfo,qmark1,oname,qmark2 = \
623 624 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
624 625 if pinfo or qmark1 or qmark2:
625 626 detail_level = 1
626 627 if "*" in oname:
627 628 self.magic_psearch(oname)
628 629 else:
629 630 self._inspect('pinfo',oname,detail_level=detail_level)
630 631
631 632 def magic_psearch(self, parameter_s=''):
632 633 """Search for object in namespaces by wildcard.
633 634
634 635 %psearch [options] PATTERN [OBJECT TYPE]
635 636
636 637 Note: ? can be used as a synonym for %psearch, at the beginning or at
637 638 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
638 639 rest of the command line must be unchanged (options come first), so
639 640 for example the following forms are equivalent
640 641
641 642 %psearch -i a* function
642 643 -i a* function?
643 644 ?-i a* function
644 645
645 646 Arguments:
646 647
647 648 PATTERN
648 649
649 650 where PATTERN is a string containing * as a wildcard similar to its
650 651 use in a shell. The pattern is matched in all namespaces on the
651 652 search path. By default objects starting with a single _ are not
652 653 matched, many IPython generated objects have a single
653 654 underscore. The default is case insensitive matching. Matching is
654 655 also done on the attributes of objects and not only on the objects
655 656 in a module.
656 657
657 658 [OBJECT TYPE]
658 659
659 660 Is the name of a python type from the types module. The name is
660 661 given in lowercase without the ending type, ex. StringType is
661 662 written string. By adding a type here only objects matching the
662 663 given type are matched. Using all here makes the pattern match all
663 664 types (this is the default).
664 665
665 666 Options:
666 667
667 668 -a: makes the pattern match even objects whose names start with a
668 669 single underscore. These names are normally ommitted from the
669 670 search.
670 671
671 672 -i/-c: make the pattern case insensitive/sensitive. If neither of
672 673 these options is given, the default is read from your ipythonrc
673 674 file. The option name which sets this value is
674 675 'wildcards_case_sensitive'. If this option is not specified in your
675 676 ipythonrc file, IPython's internal default is to do a case sensitive
676 677 search.
677 678
678 679 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
679 680 specifiy can be searched in any of the following namespaces:
680 681 'builtin', 'user', 'user_global','internal', 'alias', where
681 682 'builtin' and 'user' are the search defaults. Note that you should
682 683 not use quotes when specifying namespaces.
683 684
684 685 'Builtin' contains the python module builtin, 'user' contains all
685 686 user data, 'alias' only contain the shell aliases and no python
686 687 objects, 'internal' contains objects used by IPython. The
687 688 'user_global' namespace is only used by embedded IPython instances,
688 689 and it contains module-level globals. You can add namespaces to the
689 690 search with -s or exclude them with -e (these options can be given
690 691 more than once).
691 692
692 693 Examples:
693 694
694 695 %psearch a* -> objects beginning with an a
695 696 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
696 697 %psearch a* function -> all functions beginning with an a
697 698 %psearch re.e* -> objects beginning with an e in module re
698 699 %psearch r*.e* -> objects that start with e in modules starting in r
699 700 %psearch r*.* string -> all strings in modules beginning with r
700 701
701 702 Case sensitve search:
702 703
703 704 %psearch -c a* list all object beginning with lower case a
704 705
705 706 Show objects beginning with a single _:
706 707
707 708 %psearch -a _* list objects beginning with a single underscore"""
708 709
709 710 # default namespaces to be searched
710 711 def_search = ['user','builtin']
711 712
712 713 # Process options/args
713 714 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
714 715 opt = opts.get
715 716 shell = self.shell
716 717 psearch = shell.inspector.psearch
717 718
718 719 # select case options
719 720 if opts.has_key('i'):
720 721 ignore_case = True
721 722 elif opts.has_key('c'):
722 723 ignore_case = False
723 724 else:
724 725 ignore_case = not shell.rc.wildcards_case_sensitive
725 726
726 727 # Build list of namespaces to search from user options
727 728 def_search.extend(opt('s',[]))
728 729 ns_exclude = ns_exclude=opt('e',[])
729 730 ns_search = [nm for nm in def_search if nm not in ns_exclude]
730 731
731 732 # Call the actual search
732 733 try:
733 734 psearch(args,shell.ns_table,ns_search,
734 735 show_all=opt('a'),ignore_case=ignore_case)
735 736 except:
736 737 shell.showtraceback()
737 738
738 739 def magic_who_ls(self, parameter_s=''):
739 740 """Return a sorted list of all interactive variables.
740 741
741 742 If arguments are given, only variables of types matching these
742 743 arguments are returned."""
743 744
744 745 user_ns = self.shell.user_ns
745 746 internal_ns = self.shell.internal_ns
746 747 user_config_ns = self.shell.user_config_ns
747 748 out = []
748 749 typelist = parameter_s.split()
749 750
750 751 for i in user_ns:
751 752 if not (i.startswith('_') or i.startswith('_i')) \
752 753 and not (i in internal_ns or i in user_config_ns):
753 754 if typelist:
754 755 if type(user_ns[i]).__name__ in typelist:
755 756 out.append(i)
756 757 else:
757 758 out.append(i)
758 759 out.sort()
759 760 return out
760 761
761 762 def magic_who(self, parameter_s=''):
762 763 """Print all interactive variables, with some minimal formatting.
763 764
764 765 If any arguments are given, only variables whose type matches one of
765 766 these are printed. For example:
766 767
767 768 %who function str
768 769
769 770 will only list functions and strings, excluding all other types of
770 771 variables. To find the proper type names, simply use type(var) at a
771 772 command line to see how python prints type names. For example:
772 773
773 774 In [1]: type('hello')\\
774 775 Out[1]: <type 'str'>
775 776
776 777 indicates that the type name for strings is 'str'.
777 778
778 779 %who always excludes executed names loaded through your configuration
779 780 file and things which are internal to IPython.
780 781
781 782 This is deliberate, as typically you may load many modules and the
782 783 purpose of %who is to show you only what you've manually defined."""
783 784
784 785 varlist = self.magic_who_ls(parameter_s)
785 786 if not varlist:
786 787 print 'Interactive namespace is empty.'
787 788 return
788 789
789 790 # if we have variables, move on...
790 791
791 792 # stupid flushing problem: when prompts have no separators, stdout is
792 793 # getting lost. I'm starting to think this is a python bug. I'm having
793 794 # to force a flush with a print because even a sys.stdout.flush
794 795 # doesn't seem to do anything!
795 796
796 797 count = 0
797 798 for i in varlist:
798 799 print i+'\t',
799 800 count += 1
800 801 if count > 8:
801 802 count = 0
802 803 print
803 804 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
804 805
805 806 print # well, this does force a flush at the expense of an extra \n
806 807
807 808 def magic_whos(self, parameter_s=''):
808 809 """Like %who, but gives some extra information about each variable.
809 810
810 811 The same type filtering of %who can be applied here.
811 812
812 813 For all variables, the type is printed. Additionally it prints:
813 814
814 815 - For {},[],(): their length.
815 816
816 817 - For Numeric arrays, a summary with shape, number of elements,
817 818 typecode and size in memory.
818 819
819 820 - Everything else: a string representation, snipping their middle if
820 821 too long."""
821 822
822 823 varnames = self.magic_who_ls(parameter_s)
823 824 if not varnames:
824 825 print 'Interactive namespace is empty.'
825 826 return
826 827
827 828 # if we have variables, move on...
828 829
829 830 # for these types, show len() instead of data:
830 831 seq_types = [types.DictType,types.ListType,types.TupleType]
831 832
832 833 # for Numeric arrays, display summary info
833 834 try:
834 835 import Numeric
835 836 except ImportError:
836 837 array_type = None
837 838 else:
838 839 array_type = Numeric.ArrayType.__name__
839 840
840 841 # Find all variable names and types so we can figure out column sizes
841 842 get_vars = lambda i: self.shell.user_ns[i]
842 843 type_name = lambda v: type(v).__name__
843 844 varlist = map(get_vars,varnames)
844 845
845 846 typelist = []
846 847 for vv in varlist:
847 848 tt = type_name(vv)
848 849 if tt=='instance':
849 850 typelist.append(str(vv.__class__))
850 851 else:
851 852 typelist.append(tt)
852 853
853 854 # column labels and # of spaces as separator
854 855 varlabel = 'Variable'
855 856 typelabel = 'Type'
856 857 datalabel = 'Data/Info'
857 858 colsep = 3
858 859 # variable format strings
859 860 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
860 861 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
861 862 aformat = "%s: %s elems, type `%s`, %s bytes"
862 863 # find the size of the columns to format the output nicely
863 864 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
864 865 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
865 866 # table header
866 867 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
867 868 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
868 869 # and the table itself
869 870 kb = 1024
870 871 Mb = 1048576 # kb**2
871 872 for vname,var,vtype in zip(varnames,varlist,typelist):
872 873 print itpl(vformat),
873 874 if vtype in seq_types:
874 875 print len(var)
875 876 elif vtype==array_type:
876 877 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
877 878 vsize = Numeric.size(var)
878 879 vbytes = vsize*var.itemsize()
879 880 if vbytes < 100000:
880 881 print aformat % (vshape,vsize,var.typecode(),vbytes)
881 882 else:
882 883 print aformat % (vshape,vsize,var.typecode(),vbytes),
883 884 if vbytes < Mb:
884 885 print '(%s kb)' % (vbytes/kb,)
885 886 else:
886 887 print '(%s Mb)' % (vbytes/Mb,)
887 888 else:
888 889 vstr = str(var).replace('\n','\\n')
889 890 if len(vstr) < 50:
890 891 print vstr
891 892 else:
892 893 printpl(vfmt_short)
893 894
894 895 def magic_reset(self, parameter_s=''):
895 896 """Resets the namespace by removing all names defined by the user.
896 897
897 898 Input/Output history are left around in case you need them."""
898 899
899 900 ans = raw_input(
900 901 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
901 902 if not ans.lower() == 'y':
902 903 print 'Nothing done.'
903 904 return
904 905 user_ns = self.shell.user_ns
905 906 for i in self.magic_who_ls():
906 907 del(user_ns[i])
907 908
908 909 def magic_config(self,parameter_s=''):
909 910 """Show IPython's internal configuration."""
910 911
911 912 page('Current configuration structure:\n'+
912 913 pformat(self.shell.rc.dict()))
913 914
914 915 def magic_logstart(self,parameter_s=''):
915 916 """Start logging anywhere in a session.
916 917
917 918 %logstart [-o|-t] [log_name [log_mode]]
918 919
919 920 If no name is given, it defaults to a file named 'ipython_log.py' in your
920 921 current directory, in 'rotate' mode (see below).
921 922
922 923 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
923 924 history up to that point and then continues logging.
924 925
925 926 %logstart takes a second optional parameter: logging mode. This can be one
926 927 of (note that the modes are given unquoted):\\
927 928 append: well, that says it.\\
928 929 backup: rename (if exists) to name~ and start name.\\
929 930 global: single logfile in your home dir, appended to.\\
930 931 over : overwrite existing log.\\
931 932 rotate: create rotating logs name.1~, name.2~, etc.
932 933
933 934 Options:
934 935
935 936 -o: log also IPython's output. In this mode, all commands which
936 937 generate an Out[NN] prompt are recorded to the logfile, right after
937 938 their corresponding input line. The output lines are always
938 939 prepended with a '#[Out]# ' marker, so that the log remains valid
939 940 Python code.
940 941
941 942 Since this marker is always the same, filtering only the output from
942 943 a log is very easy, using for example a simple awk call:
943 944
944 945 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
945 946
946 947 -t: put timestamps before each input line logged (these are put in
947 948 comments)."""
948 949
949 950 opts,par = self.parse_options(parameter_s,'ot')
950 951 log_output = 'o' in opts
951 952 timestamp = 't' in opts
952 953
953 954 rc = self.shell.rc
954 955 logger = self.shell.logger
955 956
956 957 # if no args are given, the defaults set in the logger constructor by
957 958 # ipytohn remain valid
958 959 if par:
959 960 try:
960 961 logfname,logmode = par.split()
961 962 except:
962 963 logfname = par
963 964 logmode = 'backup'
964 965 else:
965 966 logfname = logger.logfname
966 967 logmode = logger.logmode
967 968 # put logfname into rc struct as if it had been called on the command
968 969 # line, so it ends up saved in the log header Save it in case we need
969 970 # to restore it...
970 971 old_logfile = rc.opts.get('logfile','')
971 972 if logfname:
972 973 logfname = os.path.expanduser(logfname)
973 974 rc.opts.logfile = logfname
974 975 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
975 976 try:
976 977 started = logger.logstart(logfname,loghead,logmode,
977 978 log_output,timestamp)
978 979 except:
979 980 rc.opts.logfile = old_logfile
980 981 warn("Couldn't start log: %s" % sys.exc_info()[1])
981 982 else:
982 983 # log input history up to this point, optionally interleaving
983 984 # output if requested
984 985
985 986 if timestamp:
986 987 # disable timestamping for the previous history, since we've
987 988 # lost those already (no time machine here).
988 989 logger.timestamp = False
989 990 if log_output:
990 991 log_write = logger.log_write
991 992 input_hist = self.shell.input_hist
992 993 output_hist = self.shell.output_hist
993 994 for n in range(1,len(input_hist)-1):
994 995 log_write(input_hist[n].rstrip())
995 996 if n in output_hist:
996 997 log_write(repr(output_hist[n]),'output')
997 998 else:
998 999 logger.log_write(self.shell.input_hist[1:])
999 1000 if timestamp:
1000 1001 # re-enable timestamping
1001 1002 logger.timestamp = True
1002 1003
1003 1004 print ('Activating auto-logging. '
1004 1005 'Current session state plus future input saved.')
1005 1006 logger.logstate()
1006 1007
1007 1008 def magic_logoff(self,parameter_s=''):
1008 1009 """Temporarily stop logging.
1009 1010
1010 1011 You must have previously started logging."""
1011 1012 self.shell.logger.switch_log(0)
1012 1013
1013 1014 def magic_logon(self,parameter_s=''):
1014 1015 """Restart logging.
1015 1016
1016 1017 This function is for restarting logging which you've temporarily
1017 1018 stopped with %logoff. For starting logging for the first time, you
1018 1019 must use the %logstart function, which allows you to specify an
1019 1020 optional log filename."""
1020 1021
1021 1022 self.shell.logger.switch_log(1)
1022 1023
1023 1024 def magic_logstate(self,parameter_s=''):
1024 1025 """Print the status of the logging system."""
1025 1026
1026 1027 self.shell.logger.logstate()
1027 1028
1028 1029 def magic_pdb(self, parameter_s=''):
1029 1030 """Control the calling of the pdb interactive debugger.
1030 1031
1031 1032 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1032 1033 argument it works as a toggle.
1033 1034
1034 1035 When an exception is triggered, IPython can optionally call the
1035 1036 interactive pdb debugger after the traceback printout. %pdb toggles
1036 1037 this feature on and off."""
1037 1038
1038 1039 par = parameter_s.strip().lower()
1039 1040
1040 1041 if par:
1041 1042 try:
1042 1043 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1043 1044 except KeyError:
1044 1045 print ('Incorrect argument. Use on/1, off/0, '
1045 1046 'or nothing for a toggle.')
1046 1047 return
1047 1048 else:
1048 1049 # toggle
1049 1050 new_pdb = not self.shell.InteractiveTB.call_pdb
1050 1051
1051 1052 # set on the shell
1052 1053 self.shell.call_pdb = new_pdb
1053 1054 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1054 1055
1055 1056 def magic_prun(self, parameter_s ='',user_mode=1,
1056 1057 opts=None,arg_lst=None,prog_ns=None):
1057 1058
1058 1059 """Run a statement through the python code profiler.
1059 1060
1060 1061 Usage:\\
1061 1062 %prun [options] statement
1062 1063
1063 1064 The given statement (which doesn't require quote marks) is run via the
1064 1065 python profiler in a manner similar to the profile.run() function.
1065 1066 Namespaces are internally managed to work correctly; profile.run
1066 1067 cannot be used in IPython because it makes certain assumptions about
1067 1068 namespaces which do not hold under IPython.
1068 1069
1069 1070 Options:
1070 1071
1071 1072 -l <limit>: you can place restrictions on what or how much of the
1072 1073 profile gets printed. The limit value can be:
1073 1074
1074 1075 * A string: only information for function names containing this string
1075 1076 is printed.
1076 1077
1077 1078 * An integer: only these many lines are printed.
1078 1079
1079 1080 * A float (between 0 and 1): this fraction of the report is printed
1080 1081 (for example, use a limit of 0.4 to see the topmost 40% only).
1081 1082
1082 1083 You can combine several limits with repeated use of the option. For
1083 1084 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1084 1085 information about class constructors.
1085 1086
1086 1087 -r: return the pstats.Stats object generated by the profiling. This
1087 1088 object has all the information about the profile in it, and you can
1088 1089 later use it for further analysis or in other functions.
1089 1090
1090 1091 Since magic functions have a particular form of calling which prevents
1091 1092 you from writing something like:\\
1092 1093 In [1]: p = %prun -r print 4 # invalid!\\
1093 1094 you must instead use IPython's automatic variables to assign this:\\
1094 1095 In [1]: %prun -r print 4 \\
1095 1096 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1096 1097 In [2]: stats = _
1097 1098
1098 1099 If you really need to assign this value via an explicit function call,
1099 1100 you can always tap directly into the true name of the magic function
1100 1101 by using the ipmagic function (which IPython automatically adds to the
1101 1102 builtins):\\
1102 1103 In [3]: stats = ipmagic('prun','-r print 4')
1103 1104
1104 1105 You can type ipmagic? for more details on ipmagic.
1105 1106
1106 1107 -s <key>: sort profile by given key. You can provide more than one key
1107 1108 by using the option several times: '-s key1 -s key2 -s key3...'. The
1108 1109 default sorting key is 'time'.
1109 1110
1110 1111 The following is copied verbatim from the profile documentation
1111 1112 referenced below:
1112 1113
1113 1114 When more than one key is provided, additional keys are used as
1114 1115 secondary criteria when the there is equality in all keys selected
1115 1116 before them.
1116 1117
1117 1118 Abbreviations can be used for any key names, as long as the
1118 1119 abbreviation is unambiguous. The following are the keys currently
1119 1120 defined:
1120 1121
1121 1122 Valid Arg Meaning\\
1122 1123 "calls" call count\\
1123 1124 "cumulative" cumulative time\\
1124 1125 "file" file name\\
1125 1126 "module" file name\\
1126 1127 "pcalls" primitive call count\\
1127 1128 "line" line number\\
1128 1129 "name" function name\\
1129 1130 "nfl" name/file/line\\
1130 1131 "stdname" standard name\\
1131 1132 "time" internal time
1132 1133
1133 1134 Note that all sorts on statistics are in descending order (placing
1134 1135 most time consuming items first), where as name, file, and line number
1135 1136 searches are in ascending order (i.e., alphabetical). The subtle
1136 1137 distinction between "nfl" and "stdname" is that the standard name is a
1137 1138 sort of the name as printed, which means that the embedded line
1138 1139 numbers get compared in an odd way. For example, lines 3, 20, and 40
1139 1140 would (if the file names were the same) appear in the string order
1140 1141 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1141 1142 line numbers. In fact, sort_stats("nfl") is the same as
1142 1143 sort_stats("name", "file", "line").
1143 1144
1144 1145 -T <filename>: save profile results as shown on screen to a text
1145 1146 file. The profile is still shown on screen.
1146 1147
1147 1148 -D <filename>: save (via dump_stats) profile statistics to given
1148 1149 filename. This data is in a format understod by the pstats module, and
1149 1150 is generated by a call to the dump_stats() method of profile
1150 1151 objects. The profile is still shown on screen.
1151 1152
1152 1153 If you want to run complete programs under the profiler's control, use
1153 1154 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1154 1155 contains profiler specific options as described here.
1155 1156
1156 1157 You can read the complete documentation for the profile module with:\\
1157 1158 In [1]: import profile; profile.help() """
1158 1159
1159 1160 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1160 1161 # protect user quote marks
1161 1162 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1162 1163
1163 1164 if user_mode: # regular user call
1164 1165 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1165 1166 list_all=1)
1166 1167 namespace = self.shell.user_ns
1167 1168 else: # called to run a program by %run -p
1168 1169 try:
1169 1170 filename = get_py_filename(arg_lst[0])
1170 1171 except IOError,msg:
1171 1172 error(msg)
1172 1173 return
1173 1174
1174 1175 arg_str = 'execfile(filename,prog_ns)'
1175 1176 namespace = locals()
1176 1177
1177 1178 opts.merge(opts_def)
1178 1179
1179 1180 prof = profile.Profile()
1180 1181 try:
1181 1182 prof = prof.runctx(arg_str,namespace,namespace)
1182 1183 sys_exit = ''
1183 1184 except SystemExit:
1184 1185 sys_exit = """*** SystemExit exception caught in code being profiled."""
1185 1186
1186 1187 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1187 1188
1188 1189 lims = opts.l
1189 1190 if lims:
1190 1191 lims = [] # rebuild lims with ints/floats/strings
1191 1192 for lim in opts.l:
1192 1193 try:
1193 1194 lims.append(int(lim))
1194 1195 except ValueError:
1195 1196 try:
1196 1197 lims.append(float(lim))
1197 1198 except ValueError:
1198 1199 lims.append(lim)
1199 1200
1200 1201 # trap output
1201 1202 sys_stdout = sys.stdout
1202 1203 stdout_trap = StringIO()
1203 1204 try:
1204 1205 sys.stdout = stdout_trap
1205 1206 stats.print_stats(*lims)
1206 1207 finally:
1207 1208 sys.stdout = sys_stdout
1208 1209 output = stdout_trap.getvalue()
1209 1210 output = output.rstrip()
1210 1211
1211 1212 page(output,screen_lines=self.shell.rc.screen_length)
1212 1213 print sys_exit,
1213 1214
1214 1215 dump_file = opts.D[0]
1215 1216 text_file = opts.T[0]
1216 1217 if dump_file:
1217 1218 prof.dump_stats(dump_file)
1218 1219 print '\n*** Profile stats marshalled to file',\
1219 1220 `dump_file`+'.',sys_exit
1220 1221 if text_file:
1221 1222 file(text_file,'w').write(output)
1222 1223 print '\n*** Profile printout saved to text file',\
1223 1224 `text_file`+'.',sys_exit
1224 1225
1225 1226 if opts.has_key('r'):
1226 1227 return stats
1227 1228 else:
1228 1229 return None
1229 1230
1230 1231 def magic_run(self, parameter_s ='',runner=None):
1231 1232 """Run the named file inside IPython as a program.
1232 1233
1233 1234 Usage:\\
1234 1235 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1235 1236
1236 1237 Parameters after the filename are passed as command-line arguments to
1237 1238 the program (put in sys.argv). Then, control returns to IPython's
1238 1239 prompt.
1239 1240
1240 1241 This is similar to running at a system prompt:\\
1241 1242 $ python file args\\
1242 1243 but with the advantage of giving you IPython's tracebacks, and of
1243 1244 loading all variables into your interactive namespace for further use
1244 1245 (unless -p is used, see below).
1245 1246
1246 1247 The file is executed in a namespace initially consisting only of
1247 1248 __name__=='__main__' and sys.argv constructed as indicated. It thus
1248 1249 sees its environment as if it were being run as a stand-alone
1249 1250 program. But after execution, the IPython interactive namespace gets
1250 1251 updated with all variables defined in the program (except for __name__
1251 1252 and sys.argv). This allows for very convenient loading of code for
1252 1253 interactive work, while giving each program a 'clean sheet' to run in.
1253 1254
1254 1255 Options:
1255 1256
1256 1257 -n: __name__ is NOT set to '__main__', but to the running file's name
1257 1258 without extension (as python does under import). This allows running
1258 1259 scripts and reloading the definitions in them without calling code
1259 1260 protected by an ' if __name__ == "__main__" ' clause.
1260 1261
1261 1262 -i: run the file in IPython's namespace instead of an empty one. This
1262 1263 is useful if you are experimenting with code written in a text editor
1263 1264 which depends on variables defined interactively.
1264 1265
1265 1266 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1266 1267 being run. This is particularly useful if IPython is being used to
1267 1268 run unittests, which always exit with a sys.exit() call. In such
1268 1269 cases you are interested in the output of the test results, not in
1269 1270 seeing a traceback of the unittest module.
1270 1271
1271 1272 -t: print timing information at the end of the run. IPython will give
1272 1273 you an estimated CPU time consumption for your script, which under
1273 1274 Unix uses the resource module to avoid the wraparound problems of
1274 1275 time.clock(). Under Unix, an estimate of time spent on system tasks
1275 1276 is also given (for Windows platforms this is reported as 0.0).
1276 1277
1277 1278 If -t is given, an additional -N<N> option can be given, where <N>
1278 1279 must be an integer indicating how many times you want the script to
1279 1280 run. The final timing report will include total and per run results.
1280 1281
1281 1282 For example (testing the script uniq_stable.py):
1282 1283
1283 1284 In [1]: run -t uniq_stable
1284 1285
1285 1286 IPython CPU timings (estimated):\\
1286 1287 User : 0.19597 s.\\
1287 1288 System: 0.0 s.\\
1288 1289
1289 1290 In [2]: run -t -N5 uniq_stable
1290 1291
1291 1292 IPython CPU timings (estimated):\\
1292 1293 Total runs performed: 5\\
1293 1294 Times : Total Per run\\
1294 1295 User : 0.910862 s, 0.1821724 s.\\
1295 1296 System: 0.0 s, 0.0 s.
1296 1297
1297 1298 -d: run your program under the control of pdb, the Python debugger.
1298 1299 This allows you to execute your program step by step, watch variables,
1299 1300 etc. Internally, what IPython does is similar to calling:
1300 1301
1301 1302 pdb.run('execfile("YOURFILENAME")')
1302 1303
1303 1304 with a breakpoint set on line 1 of your file. You can change the line
1304 1305 number for this automatic breakpoint to be <N> by using the -bN option
1305 1306 (where N must be an integer). For example:
1306 1307
1307 1308 %run -d -b40 myscript
1308 1309
1309 1310 will set the first breakpoint at line 40 in myscript.py. Note that
1310 1311 the first breakpoint must be set on a line which actually does
1311 1312 something (not a comment or docstring) for it to stop execution.
1312 1313
1313 1314 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1314 1315 first enter 'c' (without qoutes) to start execution up to the first
1315 1316 breakpoint.
1316 1317
1317 1318 Entering 'help' gives information about the use of the debugger. You
1318 1319 can easily see pdb's full documentation with "import pdb;pdb.help()"
1319 1320 at a prompt.
1320 1321
1321 1322 -p: run program under the control of the Python profiler module (which
1322 1323 prints a detailed report of execution times, function calls, etc).
1323 1324
1324 1325 You can pass other options after -p which affect the behavior of the
1325 1326 profiler itself. See the docs for %prun for details.
1326 1327
1327 1328 In this mode, the program's variables do NOT propagate back to the
1328 1329 IPython interactive namespace (because they remain in the namespace
1329 1330 where the profiler executes them).
1330 1331
1331 1332 Internally this triggers a call to %prun, see its documentation for
1332 1333 details on the options available specifically for profiling."""
1333 1334
1334 1335 # get arguments and set sys.argv for program to be run.
1335 1336 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1336 1337 mode='list',list_all=1)
1337 1338
1338 1339 try:
1339 1340 filename = get_py_filename(arg_lst[0])
1340 1341 except IndexError:
1341 1342 warn('you must provide at least a filename.')
1342 1343 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1343 1344 return
1344 1345 except IOError,msg:
1345 1346 error(msg)
1346 1347 return
1347 1348
1348 1349 # Control the response to exit() calls made by the script being run
1349 1350 exit_ignore = opts.has_key('e')
1350 1351
1351 1352 # Make sure that the running script gets a proper sys.argv as if it
1352 1353 # were run from a system shell.
1353 1354 save_argv = sys.argv # save it for later restoring
1354 1355 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1355 1356
1356 1357 if opts.has_key('i'):
1357 1358 prog_ns = self.shell.user_ns
1358 1359 __name__save = self.shell.user_ns['__name__']
1359 1360 prog_ns['__name__'] = '__main__'
1360 1361 else:
1361 1362 if opts.has_key('n'):
1362 1363 name = os.path.splitext(os.path.basename(filename))[0]
1363 1364 else:
1364 1365 name = '__main__'
1365 1366 prog_ns = {'__name__':name}
1366 1367
1367 1368 # pickle fix. See iplib for an explanation. But we need to make sure
1368 1369 # that, if we overwrite __main__, we replace it at the end
1369 1370 if prog_ns['__name__'] == '__main__':
1370 1371 restore_main = sys.modules['__main__']
1371 1372 else:
1372 1373 restore_main = False
1373 1374
1374 1375 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1375 1376
1376 1377 stats = None
1377 1378 try:
1378 1379 if opts.has_key('p'):
1379 1380 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1380 1381 else:
1381 1382 if opts.has_key('d'):
1382 1383 deb = Debugger.Pdb(self.shell.rc.colors)
1383 1384 # reset Breakpoint state, which is moronically kept
1384 1385 # in a class
1385 1386 bdb.Breakpoint.next = 1
1386 1387 bdb.Breakpoint.bplist = {}
1387 1388 bdb.Breakpoint.bpbynumber = [None]
1388 1389 # Set an initial breakpoint to stop execution
1389 1390 maxtries = 10
1390 1391 bp = int(opts.get('b',[1])[0])
1391 1392 checkline = deb.checkline(filename,bp)
1392 1393 if not checkline:
1393 1394 for bp in range(bp+1,bp+maxtries+1):
1394 1395 if deb.checkline(filename,bp):
1395 1396 break
1396 1397 else:
1397 1398 msg = ("\nI failed to find a valid line to set "
1398 1399 "a breakpoint\n"
1399 1400 "after trying up to line: %s.\n"
1400 1401 "Please set a valid breakpoint manually "
1401 1402 "with the -b option." % bp)
1402 1403 error(msg)
1403 1404 return
1404 1405 # if we find a good linenumber, set the breakpoint
1405 1406 deb.do_break('%s:%s' % (filename,bp))
1406 1407 # Start file run
1407 1408 print "NOTE: Enter 'c' at the",
1408 1409 print "ipdb> prompt to start your script."
1409 1410 try:
1410 1411 deb.run('execfile("%s")' % filename,prog_ns)
1411 1412 except:
1412 1413 etype, value, tb = sys.exc_info()
1413 1414 # Skip three frames in the traceback: the %run one,
1414 1415 # one inside bdb.py, and the command-line typed by the
1415 1416 # user (run by exec in pdb itself).
1416 1417 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1417 1418 else:
1418 1419 if runner is None:
1419 1420 runner = self.shell.safe_execfile
1420 1421 if opts.has_key('t'):
1421 1422 try:
1422 1423 nruns = int(opts['N'][0])
1423 1424 if nruns < 1:
1424 1425 error('Number of runs must be >=1')
1425 1426 return
1426 1427 except (KeyError):
1427 1428 nruns = 1
1428 1429 if nruns == 1:
1429 1430 t0 = clock2()
1430 1431 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1431 1432 t1 = clock2()
1432 1433 t_usr = t1[0]-t0[0]
1433 1434 t_sys = t1[1]-t1[1]
1434 1435 print "\nIPython CPU timings (estimated):"
1435 1436 print " User : %10s s." % t_usr
1436 1437 print " System: %10s s." % t_sys
1437 1438 else:
1438 1439 runs = range(nruns)
1439 1440 t0 = clock2()
1440 1441 for nr in runs:
1441 1442 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1442 1443 t1 = clock2()
1443 1444 t_usr = t1[0]-t0[0]
1444 1445 t_sys = t1[1]-t1[1]
1445 1446 print "\nIPython CPU timings (estimated):"
1446 1447 print "Total runs performed:",nruns
1447 1448 print " Times : %10s %10s" % ('Total','Per run')
1448 1449 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1449 1450 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1450 1451
1451 1452 else:
1452 1453 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1453 1454 if opts.has_key('i'):
1454 1455 self.shell.user_ns['__name__'] = __name__save
1455 1456 else:
1456 1457 # update IPython interactive namespace
1457 1458 del prog_ns['__name__']
1458 1459 self.shell.user_ns.update(prog_ns)
1459 1460 finally:
1460 1461 sys.argv = save_argv
1461 1462 if restore_main:
1462 1463 sys.modules['__main__'] = restore_main
1463 1464 return stats
1464 1465
1465 1466 def magic_runlog(self, parameter_s =''):
1466 1467 """Run files as logs.
1467 1468
1468 1469 Usage:\\
1469 1470 %runlog file1 file2 ...
1470 1471
1471 1472 Run the named files (treating them as log files) in sequence inside
1472 1473 the interpreter, and return to the prompt. This is much slower than
1473 1474 %run because each line is executed in a try/except block, but it
1474 1475 allows running files with syntax errors in them.
1475 1476
1476 1477 Normally IPython will guess when a file is one of its own logfiles, so
1477 1478 you can typically use %run even for logs. This shorthand allows you to
1478 1479 force any file to be treated as a log file."""
1479 1480
1480 1481 for f in parameter_s.split():
1481 1482 self.shell.safe_execfile(f,self.shell.user_ns,
1482 1483 self.shell.user_ns,islog=1)
1483 1484
1484 1485 def magic_time(self,parameter_s = ''):
1485 1486 """Time execution of a Python statement or expression.
1486 1487
1487 1488 The CPU and wall clock times are printed, and the value of the
1488 1489 expression (if any) is returned. Note that under Win32, system time
1489 1490 is always reported as 0, since it can not be measured.
1490 1491
1491 1492 This function provides very basic timing functionality. In Python
1492 1493 2.3, the timeit module offers more control and sophistication, but for
1493 1494 now IPython supports Python 2.2, so we can not rely on timeit being
1494 1495 present.
1495 1496
1496 1497 Some examples:
1497 1498
1498 1499 In [1]: time 2**128
1499 1500 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1500 1501 Wall time: 0.00
1501 1502 Out[1]: 340282366920938463463374607431768211456L
1502 1503
1503 1504 In [2]: n = 1000000
1504 1505
1505 1506 In [3]: time sum(range(n))
1506 1507 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1507 1508 Wall time: 1.37
1508 1509 Out[3]: 499999500000L
1509 1510
1510 1511 In [4]: time print 'hello world'
1511 1512 hello world
1512 1513 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1513 1514 Wall time: 0.00
1514 1515 """
1515 1516
1516 1517 # fail immediately if the given expression can't be compiled
1517 1518 try:
1518 1519 mode = 'eval'
1519 1520 code = compile(parameter_s,'<timed eval>',mode)
1520 1521 except SyntaxError:
1521 1522 mode = 'exec'
1522 1523 code = compile(parameter_s,'<timed exec>',mode)
1523 1524 # skew measurement as little as possible
1524 1525 glob = self.shell.user_ns
1525 1526 clk = clock2
1526 1527 wtime = time.time
1527 1528 # time execution
1528 1529 wall_st = wtime()
1529 1530 if mode=='eval':
1530 1531 st = clk()
1531 1532 out = eval(code,glob)
1532 1533 end = clk()
1533 1534 else:
1534 1535 st = clk()
1535 1536 exec code in glob
1536 1537 end = clk()
1537 1538 out = None
1538 1539 wall_end = wtime()
1539 1540 # Compute actual times and report
1540 1541 wall_time = wall_end-wall_st
1541 1542 cpu_user = end[0]-st[0]
1542 1543 cpu_sys = end[1]-st[1]
1543 1544 cpu_tot = cpu_user+cpu_sys
1544 1545 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1545 1546 (cpu_user,cpu_sys,cpu_tot)
1546 1547 print "Wall time: %.2f" % wall_time
1547 1548 return out
1548 1549
1549 1550 def magic_macro(self,parameter_s = ''):
1550 1551 """Define a set of input lines as a macro for future re-execution.
1551 1552
1552 1553 Usage:\\
1553 1554 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1554 1555
1555 1556 This will define a global variable called `name` which is a string
1556 1557 made of joining the slices and lines you specify (n1,n2,... numbers
1557 1558 above) from your input history into a single string. This variable
1558 1559 acts like an automatic function which re-executes those lines as if
1559 1560 you had typed them. You just type 'name' at the prompt and the code
1560 1561 executes.
1561 1562
1562 1563 The notation for indicating number ranges is: n1-n2 means 'use line
1563 1564 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1564 1565 using the lines numbered 5,6 and 7.
1565 1566
1566 1567 Note: as a 'hidden' feature, you can also use traditional python slice
1567 1568 notation, where N:M means numbers N through M-1.
1568 1569
1569 1570 For example, if your history contains (%hist prints it):
1570 1571
1571 1572 44: x=1\\
1572 1573 45: y=3\\
1573 1574 46: z=x+y\\
1574 1575 47: print x\\
1575 1576 48: a=5\\
1576 1577 49: print 'x',x,'y',y\\
1577 1578
1578 1579 you can create a macro with lines 44 through 47 (included) and line 49
1579 1580 called my_macro with:
1580 1581
1581 1582 In [51]: %macro my_macro 44-47 49
1582 1583
1583 1584 Now, typing `my_macro` (without quotes) will re-execute all this code
1584 1585 in one pass.
1585 1586
1586 1587 You don't need to give the line-numbers in order, and any given line
1587 1588 number can appear multiple times. You can assemble macros with any
1588 1589 lines from your input history in any order.
1589 1590
1590 1591 The macro is a simple object which holds its value in an attribute,
1591 1592 but IPython's display system checks for macros and executes them as
1592 1593 code instead of printing them when you type their name.
1593 1594
1594 1595 You can view a macro's contents by explicitly printing it with:
1595 1596
1596 1597 'print macro_name'.
1597 1598
1598 1599 For one-off cases which DON'T contain magic function calls in them you
1599 1600 can obtain similar results by explicitly executing slices from your
1600 1601 input history with:
1601 1602
1602 1603 In [60]: exec In[44:48]+In[49]"""
1603 1604
1604 1605 args = parameter_s.split()
1605 1606 name,ranges = args[0], args[1:]
1606 1607 #print 'rng',ranges # dbg
1607 1608 lines = self.extract_input_slices(ranges)
1608 1609 macro = Macro(lines)
1609 1610 self.shell.user_ns.update({name:macro})
1610 1611 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1611 1612 print 'Macro contents:'
1612 1613 print macro,
1613 1614
1614 1615 def magic_save(self,parameter_s = ''):
1615 1616 """Save a set of lines to a given filename.
1616 1617
1617 1618 Usage:\\
1618 1619 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1619 1620
1620 1621 This function uses the same syntax as %macro for line extraction, but
1621 1622 instead of creating a macro it saves the resulting string to the
1622 1623 filename you specify.
1623 1624
1624 1625 It adds a '.py' extension to the file if you don't do so yourself, and
1625 1626 it asks for confirmation before overwriting existing files."""
1626 1627
1627 1628 args = parameter_s.split()
1628 1629 fname,ranges = args[0], args[1:]
1629 1630 if not fname.endswith('.py'):
1630 1631 fname += '.py'
1631 1632 if os.path.isfile(fname):
1632 1633 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1633 1634 if ans.lower() not in ['y','yes']:
1634 1635 print 'Operation cancelled.'
1635 1636 return
1636 1637 cmds = ''.join(self.extract_input_slices(ranges))
1637 1638 f = file(fname,'w')
1638 1639 f.write(cmds)
1639 1640 f.close()
1640 1641 print 'The following commands were written to file `%s`:' % fname
1641 1642 print cmds
1642 1643
1643 1644 def _edit_macro(self,mname,macro):
1644 1645 """open an editor with the macro data in a file"""
1645 1646 filename = self.shell.mktempfile(macro.value)
1646 1647 self.shell.hooks.editor(filename)
1647 1648
1648 1649 # and make a new macro object, to replace the old one
1649 1650 mfile = open(filename)
1650 1651 mvalue = mfile.read()
1651 1652 mfile.close()
1652 1653 self.shell.user_ns[mname] = Macro(mvalue)
1653 1654
1654 1655 def magic_ed(self,parameter_s=''):
1655 1656 """Alias to %edit."""
1656 1657 return self.magic_edit(parameter_s)
1657 1658
1658 1659 def magic_edit(self,parameter_s='',last_call=['','']):
1659 1660 """Bring up an editor and execute the resulting code.
1660 1661
1661 1662 Usage:
1662 1663 %edit [options] [args]
1663 1664
1664 1665 %edit runs IPython's editor hook. The default version of this hook is
1665 1666 set to call the __IPYTHON__.rc.editor command. This is read from your
1666 1667 environment variable $EDITOR. If this isn't found, it will default to
1667 1668 vi under Linux/Unix and to notepad under Windows. See the end of this
1668 1669 docstring for how to change the editor hook.
1669 1670
1670 1671 You can also set the value of this editor via the command line option
1671 1672 '-editor' or in your ipythonrc file. This is useful if you wish to use
1672 1673 specifically for IPython an editor different from your typical default
1673 1674 (and for Windows users who typically don't set environment variables).
1674 1675
1675 1676 This command allows you to conveniently edit multi-line code right in
1676 1677 your IPython session.
1677 1678
1678 1679 If called without arguments, %edit opens up an empty editor with a
1679 1680 temporary file and will execute the contents of this file when you
1680 1681 close it (don't forget to save it!).
1681 1682
1682 1683 Options:
1683 1684
1684 1685 -p: this will call the editor with the same data as the previous time
1685 1686 it was used, regardless of how long ago (in your current session) it
1686 1687 was.
1687 1688
1688 1689 -x: do not execute the edited code immediately upon exit. This is
1689 1690 mainly useful if you are editing programs which need to be called with
1690 1691 command line arguments, which you can then do using %run.
1691 1692
1692 1693 Arguments:
1693 1694
1694 1695 If arguments are given, the following possibilites exist:
1695 1696
1696 1697 - The arguments are numbers or pairs of colon-separated numbers (like
1697 1698 1 4:8 9). These are interpreted as lines of previous input to be
1698 1699 loaded into the editor. The syntax is the same of the %macro command.
1699 1700
1700 1701 - If the argument doesn't start with a number, it is evaluated as a
1701 1702 variable and its contents loaded into the editor. You can thus edit
1702 1703 any string which contains python code (including the result of
1703 1704 previous edits).
1704 1705
1705 1706 - If the argument is the name of an object (other than a string),
1706 1707 IPython will try to locate the file where it was defined and open the
1707 1708 editor at the point where it is defined. You can use `%edit function`
1708 1709 to load an editor exactly at the point where 'function' is defined,
1709 1710 edit it and have the file be executed automatically.
1710 1711
1711 1712 If the object is a macro (see %macro for details), this opens up your
1712 1713 specified editor with a temporary file containing the macro's data.
1713 1714 Upon exit, the macro is reloaded with the contents of the file.
1714 1715
1715 1716 Note: opening at an exact line is only supported under Unix, and some
1716 1717 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1717 1718 '+NUMBER' parameter necessary for this feature. Good editors like
1718 1719 (X)Emacs, vi, jed, pico and joe all do.
1719 1720
1720 1721 - If the argument is not found as a variable, IPython will look for a
1721 1722 file with that name (adding .py if necessary) and load it into the
1722 1723 editor. It will execute its contents with execfile() when you exit,
1723 1724 loading any code in the file into your interactive namespace.
1724 1725
1725 1726 After executing your code, %edit will return as output the code you
1726 1727 typed in the editor (except when it was an existing file). This way
1727 1728 you can reload the code in further invocations of %edit as a variable,
1728 1729 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1729 1730 the output.
1730 1731
1731 1732 Note that %edit is also available through the alias %ed.
1732 1733
1733 1734 This is an example of creating a simple function inside the editor and
1734 1735 then modifying it. First, start up the editor:
1735 1736
1736 1737 In [1]: ed\\
1737 1738 Editing... done. Executing edited code...\\
1738 1739 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1739 1740
1740 1741 We can then call the function foo():
1741 1742
1742 1743 In [2]: foo()\\
1743 1744 foo() was defined in an editing session
1744 1745
1745 1746 Now we edit foo. IPython automatically loads the editor with the
1746 1747 (temporary) file where foo() was previously defined:
1747 1748
1748 1749 In [3]: ed foo\\
1749 1750 Editing... done. Executing edited code...
1750 1751
1751 1752 And if we call foo() again we get the modified version:
1752 1753
1753 1754 In [4]: foo()\\
1754 1755 foo() has now been changed!
1755 1756
1756 1757 Here is an example of how to edit a code snippet successive
1757 1758 times. First we call the editor:
1758 1759
1759 1760 In [8]: ed\\
1760 1761 Editing... done. Executing edited code...\\
1761 1762 hello\\
1762 1763 Out[8]: "print 'hello'\\n"
1763 1764
1764 1765 Now we call it again with the previous output (stored in _):
1765 1766
1766 1767 In [9]: ed _\\
1767 1768 Editing... done. Executing edited code...\\
1768 1769 hello world\\
1769 1770 Out[9]: "print 'hello world'\\n"
1770 1771
1771 1772 Now we call it with the output #8 (stored in _8, also as Out[8]):
1772 1773
1773 1774 In [10]: ed _8\\
1774 1775 Editing... done. Executing edited code...\\
1775 1776 hello again\\
1776 1777 Out[10]: "print 'hello again'\\n"
1777 1778
1778 1779
1779 1780 Changing the default editor hook:
1780 1781
1781 1782 If you wish to write your own editor hook, you can put it in a
1782 1783 configuration file which you load at startup time. The default hook
1783 1784 is defined in the IPython.hooks module, and you can use that as a
1784 1785 starting example for further modifications. That file also has
1785 1786 general instructions on how to set a new hook for use once you've
1786 1787 defined it."""
1787 1788
1788 1789 # FIXME: This function has become a convoluted mess. It needs a
1789 1790 # ground-up rewrite with clean, simple logic.
1790 1791
1791 1792 def make_filename(arg):
1792 1793 "Make a filename from the given args"
1793 1794 try:
1794 1795 filename = get_py_filename(arg)
1795 1796 except IOError:
1796 1797 if args.endswith('.py'):
1797 1798 filename = arg
1798 1799 else:
1799 1800 filename = None
1800 1801 return filename
1801 1802
1802 1803 # custom exceptions
1803 1804 class DataIsObject(Exception): pass
1804 1805
1805 1806 opts,args = self.parse_options(parameter_s,'px')
1806 1807
1807 1808 # Default line number value
1808 1809 lineno = None
1809 1810 if opts.has_key('p'):
1810 1811 args = '_%s' % last_call[0]
1811 1812 if not self.shell.user_ns.has_key(args):
1812 1813 args = last_call[1]
1813 1814
1814 1815 # use last_call to remember the state of the previous call, but don't
1815 1816 # let it be clobbered by successive '-p' calls.
1816 1817 try:
1817 1818 last_call[0] = self.shell.outputcache.prompt_count
1818 1819 if not opts.has_key('p'):
1819 1820 last_call[1] = parameter_s
1820 1821 except:
1821 1822 pass
1822 1823
1823 1824 # by default this is done with temp files, except when the given
1824 1825 # arg is a filename
1825 1826 use_temp = 1
1826 1827
1827 1828 if re.match(r'\d',args):
1828 1829 # Mode where user specifies ranges of lines, like in %macro.
1829 1830 # This means that you can't edit files whose names begin with
1830 1831 # numbers this way. Tough.
1831 1832 ranges = args.split()
1832 1833 data = ''.join(self.extract_input_slices(ranges))
1833 1834 elif args.endswith('.py'):
1834 1835 filename = make_filename(args)
1835 1836 data = ''
1836 1837 use_temp = 0
1837 1838 elif args:
1838 1839 try:
1839 1840 # Load the parameter given as a variable. If not a string,
1840 1841 # process it as an object instead (below)
1841 1842
1842 1843 #print '*** args',args,'type',type(args) # dbg
1843 1844 data = eval(args,self.shell.user_ns)
1844 1845 if not type(data) in StringTypes:
1845 1846 raise DataIsObject
1846 1847
1847 1848 except (NameError,SyntaxError):
1848 1849 # given argument is not a variable, try as a filename
1849 1850 filename = make_filename(args)
1850 1851 if filename is None:
1851 1852 warn("Argument given (%s) can't be found as a variable "
1852 1853 "or as a filename." % args)
1853 1854 return
1854 1855
1855 1856 data = ''
1856 1857 use_temp = 0
1857 1858 except DataIsObject:
1858 1859
1859 1860 # macros have a special edit function
1860 1861 if isinstance(data,Macro):
1861 1862 self._edit_macro(args,data)
1862 1863 return
1863 1864
1864 1865 # For objects, try to edit the file where they are defined
1865 1866 try:
1866 1867 filename = inspect.getabsfile(data)
1867 1868 datafile = 1
1868 1869 except TypeError:
1869 1870 filename = make_filename(args)
1870 1871 datafile = 1
1871 1872 warn('Could not find file where `%s` is defined.\n'
1872 1873 'Opening a file named `%s`' % (args,filename))
1873 1874 # Now, make sure we can actually read the source (if it was in
1874 1875 # a temp file it's gone by now).
1875 1876 if datafile:
1876 1877 try:
1877 1878 lineno = inspect.getsourcelines(data)[1]
1878 1879 except IOError:
1879 1880 filename = make_filename(args)
1880 1881 if filename is None:
1881 1882 warn('The file `%s` where `%s` was defined cannot '
1882 1883 'be read.' % (filename,data))
1883 1884 return
1884 1885 use_temp = 0
1885 1886 else:
1886 1887 data = ''
1887 1888
1888 1889 if use_temp:
1889 1890 filename = self.shell.mktempfile(data)
1890 1891
1891 1892 # do actual editing here
1892 1893 print 'Editing...',
1893 1894 sys.stdout.flush()
1894 1895 self.shell.hooks.editor(filename,lineno)
1895 1896 if opts.has_key('x'): # -x prevents actual execution
1896 1897 print
1897 1898 else:
1898 1899 print 'done. Executing edited code...'
1899 1900 try:
1900 1901 self.shell.safe_execfile(filename,self.shell.user_ns)
1901 1902 except IOError,msg:
1902 1903 if msg.filename == filename:
1903 1904 warn('File not found. Did you forget to save?')
1904 1905 return
1905 1906 else:
1906 1907 self.shell.showtraceback()
1907 1908 except:
1908 1909 self.shell.showtraceback()
1909 1910
1910 1911 def magic_xmode(self,parameter_s = ''):
1911 1912 """Switch modes for the exception handlers.
1912 1913
1913 1914 Valid modes: Plain, Context and Verbose.
1914 1915
1915 1916 If called without arguments, acts as a toggle."""
1916 1917
1917 1918 def xmode_switch_err(name):
1918 1919 warn('Error changing %s exception modes.\n%s' %
1919 1920 (name,sys.exc_info()[1]))
1920 1921
1921 1922 shell = self.shell
1922 1923 new_mode = parameter_s.strip().capitalize()
1923 1924 try:
1924 1925 shell.InteractiveTB.set_mode(mode=new_mode)
1925 1926 print 'Exception reporting mode:',shell.InteractiveTB.mode
1926 1927 except:
1927 1928 xmode_switch_err('user')
1928 1929
1929 1930 # threaded shells use a special handler in sys.excepthook
1930 1931 if shell.isthreaded:
1931 1932 try:
1932 1933 shell.sys_excepthook.set_mode(mode=new_mode)
1933 1934 except:
1934 1935 xmode_switch_err('threaded')
1935 1936
1936 1937 def magic_colors(self,parameter_s = ''):
1937 1938 """Switch color scheme for prompts, info system and exception handlers.
1938 1939
1939 1940 Currently implemented schemes: NoColor, Linux, LightBG.
1940 1941
1941 1942 Color scheme names are not case-sensitive."""
1942 1943
1943 1944 def color_switch_err(name):
1944 1945 warn('Error changing %s color schemes.\n%s' %
1945 1946 (name,sys.exc_info()[1]))
1946 1947
1947 1948
1948 1949 new_scheme = parameter_s.strip()
1949 1950 if not new_scheme:
1950 1951 print 'You must specify a color scheme.'
1951 1952 return
1952 1953 # Under Windows, check for Gary Bishop's readline, which is necessary
1953 1954 # for ANSI coloring
1954 1955 if os.name in ['nt','dos']:
1955 1956 try:
1956 1957 import readline
1957 1958 except ImportError:
1958 1959 has_readline = 0
1959 1960 else:
1960 1961 try:
1961 1962 readline.GetOutputFile()
1962 1963 except AttributeError:
1963 1964 has_readline = 0
1964 1965 else:
1965 1966 has_readline = 1
1966 1967 if not has_readline:
1967 1968 msg = """\
1968 1969 Proper color support under MS Windows requires Gary Bishop's readline library.
1969 1970 You can find it at:
1970 1971 http://sourceforge.net/projects/uncpythontools
1971 1972 Gary's readline needs the ctypes module, from:
1972 1973 http://starship.python.net/crew/theller/ctypes
1973 1974
1974 1975 Defaulting color scheme to 'NoColor'"""
1975 1976 new_scheme = 'NoColor'
1976 1977 warn(msg)
1977 1978 # local shortcut
1978 1979 shell = self.shell
1979 1980
1980 1981 # Set prompt colors
1981 1982 try:
1982 1983 shell.outputcache.set_colors(new_scheme)
1983 1984 except:
1984 1985 color_switch_err('prompt')
1985 1986 else:
1986 1987 shell.rc.colors = \
1987 1988 shell.outputcache.color_table.active_scheme_name
1988 1989 # Set exception colors
1989 1990 try:
1990 1991 shell.InteractiveTB.set_colors(scheme = new_scheme)
1991 1992 shell.SyntaxTB.set_colors(scheme = new_scheme)
1992 1993 except:
1993 1994 color_switch_err('exception')
1994 1995
1995 1996 # threaded shells use a verbose traceback in sys.excepthook
1996 1997 if shell.isthreaded:
1997 1998 try:
1998 1999 shell.sys_excepthook.set_colors(scheme=new_scheme)
1999 2000 except:
2000 2001 color_switch_err('system exception handler')
2001 2002
2002 2003 # Set info (for 'object?') colors
2003 2004 if shell.rc.color_info:
2004 2005 try:
2005 2006 shell.inspector.set_active_scheme(new_scheme)
2006 2007 except:
2007 2008 color_switch_err('object inspector')
2008 2009 else:
2009 2010 shell.inspector.set_active_scheme('NoColor')
2010 2011
2011 2012 def magic_color_info(self,parameter_s = ''):
2012 2013 """Toggle color_info.
2013 2014
2014 2015 The color_info configuration parameter controls whether colors are
2015 2016 used for displaying object details (by things like %psource, %pfile or
2016 2017 the '?' system). This function toggles this value with each call.
2017 2018
2018 2019 Note that unless you have a fairly recent pager (less works better
2019 2020 than more) in your system, using colored object information displays
2020 2021 will not work properly. Test it and see."""
2021 2022
2022 2023 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2023 2024 self.magic_colors(self.shell.rc.colors)
2024 2025 print 'Object introspection functions have now coloring:',
2025 2026 print ['OFF','ON'][self.shell.rc.color_info]
2026 2027
2027 2028 def magic_Pprint(self, parameter_s=''):
2028 2029 """Toggle pretty printing on/off."""
2029 2030
2030 2031 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2031 2032 print 'Pretty printing has been turned', \
2032 2033 ['OFF','ON'][self.shell.outputcache.Pprint]
2033 2034
2034 2035 def magic_exit(self, parameter_s=''):
2035 2036 """Exit IPython, confirming if configured to do so.
2036 2037
2037 2038 You can configure whether IPython asks for confirmation upon exit by
2038 2039 setting the confirm_exit flag in the ipythonrc file."""
2039 2040
2040 2041 self.shell.exit()
2041 2042
2042 2043 def magic_quit(self, parameter_s=''):
2043 2044 """Exit IPython, confirming if configured to do so (like %exit)"""
2044 2045
2045 2046 self.shell.exit()
2046 2047
2047 2048 def magic_Exit(self, parameter_s=''):
2048 2049 """Exit IPython without confirmation."""
2049 2050
2050 2051 self.shell.exit_now = True
2051 2052
2052 2053 def magic_Quit(self, parameter_s=''):
2053 2054 """Exit IPython without confirmation (like %Exit)."""
2054 2055
2055 2056 self.shell.exit_now = True
2056 2057
2057 2058 #......................................................................
2058 2059 # Functions to implement unix shell-type things
2059 2060
2060 2061 def magic_alias(self, parameter_s = ''):
2061 2062 """Define an alias for a system command.
2062 2063
2063 2064 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2064 2065
2065 2066 Then, typing 'alias_name params' will execute the system command 'cmd
2066 2067 params' (from your underlying operating system).
2067 2068
2068 2069 Aliases have lower precedence than magic functions and Python normal
2069 2070 variables, so if 'foo' is both a Python variable and an alias, the
2070 2071 alias can not be executed until 'del foo' removes the Python variable.
2071 2072
2072 2073 You can use the %l specifier in an alias definition to represent the
2073 2074 whole line when the alias is called. For example:
2074 2075
2075 2076 In [2]: alias all echo "Input in brackets: <%l>"\\
2076 2077 In [3]: all hello world\\
2077 2078 Input in brackets: <hello world>
2078 2079
2079 2080 You can also define aliases with parameters using %s specifiers (one
2080 2081 per parameter):
2081 2082
2082 2083 In [1]: alias parts echo first %s second %s\\
2083 2084 In [2]: %parts A B\\
2084 2085 first A second B\\
2085 2086 In [3]: %parts A\\
2086 2087 Incorrect number of arguments: 2 expected.\\
2087 2088 parts is an alias to: 'echo first %s second %s'
2088 2089
2089 2090 Note that %l and %s are mutually exclusive. You can only use one or
2090 2091 the other in your aliases.
2091 2092
2092 2093 Aliases expand Python variables just like system calls using ! or !!
2093 2094 do: all expressions prefixed with '$' get expanded. For details of
2094 2095 the semantic rules, see PEP-215:
2095 2096 http://www.python.org/peps/pep-0215.html. This is the library used by
2096 2097 IPython for variable expansion. If you want to access a true shell
2097 2098 variable, an extra $ is necessary to prevent its expansion by IPython:
2098 2099
2099 2100 In [6]: alias show echo\\
2100 2101 In [7]: PATH='A Python string'\\
2101 2102 In [8]: show $PATH\\
2102 2103 A Python string\\
2103 2104 In [9]: show $$PATH\\
2104 2105 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2105 2106
2106 2107 You can use the alias facility to acess all of $PATH. See the %rehash
2107 2108 and %rehashx functions, which automatically create aliases for the
2108 2109 contents of your $PATH.
2109 2110
2110 2111 If called with no parameters, %alias prints the current alias table."""
2111 2112
2112 2113 par = parameter_s.strip()
2113 2114 if not par:
2114 2115 if self.shell.rc.automagic:
2115 2116 prechar = ''
2116 2117 else:
2117 2118 prechar = self.shell.ESC_MAGIC
2118 2119 print 'Alias\t\tSystem Command\n'+'-'*30
2119 2120 atab = self.shell.alias_table
2120 2121 aliases = atab.keys()
2121 2122 aliases.sort()
2122 2123 for alias in aliases:
2123 2124 print prechar+alias+'\t\t'+atab[alias][1]
2124 2125 print '-'*30+'\nTotal number of aliases:',len(aliases)
2125 2126 return
2126 2127 try:
2127 2128 alias,cmd = par.split(None,1)
2128 2129 except:
2129 2130 print OInspect.getdoc(self.magic_alias)
2130 2131 else:
2131 2132 nargs = cmd.count('%s')
2132 2133 if nargs>0 and cmd.find('%l')>=0:
2133 2134 error('The %s and %l specifiers are mutually exclusive '
2134 2135 'in alias definitions.')
2135 2136 else: # all looks OK
2136 2137 self.shell.alias_table[alias] = (nargs,cmd)
2137 2138 self.shell.alias_table_validate(verbose=1)
2138 2139 # end magic_alias
2139 2140
2140 2141 def magic_unalias(self, parameter_s = ''):
2141 2142 """Remove an alias"""
2142 2143
2143 2144 aname = parameter_s.strip()
2144 2145 if aname in self.shell.alias_table:
2145 2146 del self.shell.alias_table[aname]
2146 2147
2147 2148 def magic_rehash(self, parameter_s = ''):
2148 2149 """Update the alias table with all entries in $PATH.
2149 2150
2150 2151 This version does no checks on execute permissions or whether the
2151 2152 contents of $PATH are truly files (instead of directories or something
2152 2153 else). For such a safer (but slower) version, use %rehashx."""
2153 2154
2154 2155 # This function (and rehashx) manipulate the alias_table directly
2155 2156 # rather than calling magic_alias, for speed reasons. A rehash on a
2156 2157 # typical Linux box involves several thousand entries, so efficiency
2157 2158 # here is a top concern.
2158 2159
2159 2160 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2160 2161 alias_table = self.shell.alias_table
2161 2162 for pdir in path:
2162 2163 for ff in os.listdir(pdir):
2163 2164 # each entry in the alias table must be (N,name), where
2164 2165 # N is the number of positional arguments of the alias.
2165 2166 alias_table[ff] = (0,ff)
2166 2167 # Make sure the alias table doesn't contain keywords or builtins
2167 2168 self.shell.alias_table_validate()
2168 2169 # Call again init_auto_alias() so we get 'rm -i' and other modified
2169 2170 # aliases since %rehash will probably clobber them
2170 2171 self.shell.init_auto_alias()
2171 2172
2172 2173 def magic_rehashx(self, parameter_s = ''):
2173 2174 """Update the alias table with all executable files in $PATH.
2174 2175
2175 2176 This version explicitly checks that every entry in $PATH is a file
2176 2177 with execute access (os.X_OK), so it is much slower than %rehash.
2177 2178
2178 2179 Under Windows, it checks executability as a match agains a
2179 2180 '|'-separated string of extensions, stored in the IPython config
2180 2181 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2181 2182
2182 2183 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2183 2184 alias_table = self.shell.alias_table
2184 2185
2185 2186 if os.name == 'posix':
2186 2187 isexec = lambda fname:os.path.isfile(fname) and \
2187 2188 os.access(fname,os.X_OK)
2188 2189 else:
2189 2190
2190 2191 try:
2191 2192 winext = os.environ['pathext'].replace(';','|').replace('.','')
2192 2193 except KeyError:
2193 2194 winext = 'exe|com|bat'
2194 2195
2195 2196 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2196 2197 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2197 2198 savedir = os.getcwd()
2198 2199 try:
2199 2200 # write the whole loop for posix/Windows so we don't have an if in
2200 2201 # the innermost part
2201 2202 if os.name == 'posix':
2202 2203 for pdir in path:
2203 2204 os.chdir(pdir)
2204 2205 for ff in os.listdir(pdir):
2205 2206 if isexec(ff):
2206 2207 # each entry in the alias table must be (N,name),
2207 2208 # where N is the number of positional arguments of the
2208 2209 # alias.
2209 2210 alias_table[ff] = (0,ff)
2210 2211 else:
2211 2212 for pdir in path:
2212 2213 os.chdir(pdir)
2213 2214 for ff in os.listdir(pdir):
2214 2215 if isexec(ff):
2215 2216 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2216 2217 # Make sure the alias table doesn't contain keywords or builtins
2217 2218 self.shell.alias_table_validate()
2218 2219 # Call again init_auto_alias() so we get 'rm -i' and other
2219 2220 # modified aliases since %rehashx will probably clobber them
2220 2221 self.shell.init_auto_alias()
2221 2222 finally:
2222 2223 os.chdir(savedir)
2223 2224
2224 2225 def magic_pwd(self, parameter_s = ''):
2225 2226 """Return the current working directory path."""
2226 2227 return os.getcwd()
2227 2228
2228 2229 def magic_cd(self, parameter_s=''):
2229 2230 """Change the current working directory.
2230 2231
2231 2232 This command automatically maintains an internal list of directories
2232 2233 you visit during your IPython session, in the variable _dh. The
2233 2234 command %dhist shows this history nicely formatted.
2234 2235
2235 2236 Usage:
2236 2237
2237 2238 cd 'dir': changes to directory 'dir'.
2238 2239
2239 2240 cd -: changes to the last visited directory.
2240 2241
2241 2242 cd -<n>: changes to the n-th directory in the directory history.
2242 2243
2243 2244 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2244 2245 (note: cd <bookmark_name> is enough if there is no
2245 2246 directory <bookmark_name>, but a bookmark with the name exists.)
2246 2247
2247 2248 Options:
2248 2249
2249 2250 -q: quiet. Do not print the working directory after the cd command is
2250 2251 executed. By default IPython's cd command does print this directory,
2251 2252 since the default prompts do not display path information.
2252 2253
2253 2254 Note that !cd doesn't work for this purpose because the shell where
2254 2255 !command runs is immediately discarded after executing 'command'."""
2255 2256
2256 2257 parameter_s = parameter_s.strip()
2257 2258 bkms = self.shell.persist.get("bookmarks",{})
2258 2259
2259 2260 numcd = re.match(r'(-)(\d+)$',parameter_s)
2260 2261 # jump in directory history by number
2261 2262 if numcd:
2262 2263 nn = int(numcd.group(2))
2263 2264 try:
2264 2265 ps = self.shell.user_ns['_dh'][nn]
2265 2266 except IndexError:
2266 2267 print 'The requested directory does not exist in history.'
2267 2268 return
2268 2269 else:
2269 2270 opts = {}
2270 2271 else:
2271 2272 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2272 2273 # jump to previous
2273 2274 if ps == '-':
2274 2275 try:
2275 2276 ps = self.shell.user_ns['_dh'][-2]
2276 2277 except IndexError:
2277 2278 print 'No previous directory to change to.'
2278 2279 return
2279 2280 # jump to bookmark
2280 2281 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2281 2282 if bkms.has_key(ps):
2282 2283 target = bkms[ps]
2283 2284 print '(bookmark:%s) -> %s' % (ps,target)
2284 2285 ps = target
2285 2286 else:
2286 2287 if bkms:
2287 2288 error("Bookmark '%s' not found. "
2288 2289 "Use '%bookmark -l' to see your bookmarks." % ps)
2289 2290 else:
2290 2291 print "Bookmarks not set - use %bookmark <bookmarkname>"
2291 2292 return
2292 2293
2293 2294 # at this point ps should point to the target dir
2294 2295 if ps:
2295 2296 try:
2296 2297 os.chdir(os.path.expanduser(ps))
2297 2298 except OSError:
2298 2299 print sys.exc_info()[1]
2299 2300 else:
2300 2301 self.shell.user_ns['_dh'].append(os.getcwd())
2301 2302 else:
2302 2303 os.chdir(self.shell.home_dir)
2303 2304 self.shell.user_ns['_dh'].append(os.getcwd())
2304 2305 if not 'q' in opts:
2305 2306 print self.shell.user_ns['_dh'][-1]
2306 2307
2307 2308 def magic_dhist(self, parameter_s=''):
2308 2309 """Print your history of visited directories.
2309 2310
2310 2311 %dhist -> print full history\\
2311 2312 %dhist n -> print last n entries only\\
2312 2313 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2313 2314
2314 2315 This history is automatically maintained by the %cd command, and
2315 2316 always available as the global list variable _dh. You can use %cd -<n>
2316 2317 to go to directory number <n>."""
2317 2318
2318 2319 dh = self.shell.user_ns['_dh']
2319 2320 if parameter_s:
2320 2321 try:
2321 2322 args = map(int,parameter_s.split())
2322 2323 except:
2323 2324 self.arg_err(Magic.magic_dhist)
2324 2325 return
2325 2326 if len(args) == 1:
2326 2327 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2327 2328 elif len(args) == 2:
2328 2329 ini,fin = args
2329 2330 else:
2330 2331 self.arg_err(Magic.magic_dhist)
2331 2332 return
2332 2333 else:
2333 2334 ini,fin = 0,len(dh)
2334 2335 nlprint(dh,
2335 2336 header = 'Directory history (kept in _dh)',
2336 2337 start=ini,stop=fin)
2337 2338
2338 2339 def magic_env(self, parameter_s=''):
2339 2340 """List environment variables."""
2340 2341
2341 2342 return os.environ.data
2342 2343
2343 2344 def magic_pushd(self, parameter_s=''):
2344 2345 """Place the current dir on stack and change directory.
2345 2346
2346 2347 Usage:\\
2347 2348 %pushd ['dirname']
2348 2349
2349 2350 %pushd with no arguments does a %pushd to your home directory.
2350 2351 """
2351 2352 if parameter_s == '': parameter_s = '~'
2352 2353 dir_s = self.shell.dir_stack
2353 2354 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2354 2355 os.path.expanduser(self.shell.dir_stack[0]):
2355 2356 try:
2356 2357 self.magic_cd(parameter_s)
2357 2358 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2358 2359 self.magic_dirs()
2359 2360 except:
2360 2361 print 'Invalid directory'
2361 2362 else:
2362 2363 print 'You are already there!'
2363 2364
2364 2365 def magic_popd(self, parameter_s=''):
2365 2366 """Change to directory popped off the top of the stack.
2366 2367 """
2367 2368 if len (self.shell.dir_stack) > 1:
2368 2369 self.shell.dir_stack.pop(0)
2369 2370 self.magic_cd(self.shell.dir_stack[0])
2370 2371 print self.shell.dir_stack[0]
2371 2372 else:
2372 2373 print "You can't remove the starting directory from the stack:",\
2373 2374 self.shell.dir_stack
2374 2375
2375 2376 def magic_dirs(self, parameter_s=''):
2376 2377 """Return the current directory stack."""
2377 2378
2378 2379 return self.shell.dir_stack[:]
2379 2380
2380 2381 def magic_sc(self, parameter_s=''):
2381 2382 """Shell capture - execute a shell command and capture its output.
2382 2383
2383 2384 %sc [options] varname=command
2384 2385
2385 2386 IPython will run the given command using commands.getoutput(), and
2386 2387 will then update the user's interactive namespace with a variable
2387 2388 called varname, containing the value of the call. Your command can
2388 2389 contain shell wildcards, pipes, etc.
2389 2390
2390 2391 The '=' sign in the syntax is mandatory, and the variable name you
2391 2392 supply must follow Python's standard conventions for valid names.
2392 2393
2393 2394 Options:
2394 2395
2395 2396 -l: list output. Split the output on newlines into a list before
2396 2397 assigning it to the given variable. By default the output is stored
2397 2398 as a single string.
2398 2399
2399 2400 -v: verbose. Print the contents of the variable.
2400 2401
2401 2402 In most cases you should not need to split as a list, because the
2402 2403 returned value is a special type of string which can automatically
2403 2404 provide its contents either as a list (split on newlines) or as a
2404 2405 space-separated string. These are convenient, respectively, either
2405 2406 for sequential processing or to be passed to a shell command.
2406 2407
2407 2408 For example:
2408 2409
2409 2410 # Capture into variable a
2410 2411 In [9]: sc a=ls *py
2411 2412
2412 2413 # a is a string with embedded newlines
2413 2414 In [10]: a
2414 2415 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2415 2416
2416 2417 # which can be seen as a list:
2417 2418 In [11]: a.l
2418 2419 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2419 2420
2420 2421 # or as a whitespace-separated string:
2421 2422 In [12]: a.s
2422 2423 Out[12]: 'setup.py win32_manual_post_install.py'
2423 2424
2424 2425 # a.s is useful to pass as a single command line:
2425 2426 In [13]: !wc -l $a.s
2426 2427 146 setup.py
2427 2428 130 win32_manual_post_install.py
2428 2429 276 total
2429 2430
2430 2431 # while the list form is useful to loop over:
2431 2432 In [14]: for f in a.l:
2432 2433 ....: !wc -l $f
2433 2434 ....:
2434 2435 146 setup.py
2435 2436 130 win32_manual_post_install.py
2436 2437
2437 2438 Similiarly, the lists returned by the -l option are also special, in
2438 2439 the sense that you can equally invoke the .s attribute on them to
2439 2440 automatically get a whitespace-separated string from their contents:
2440 2441
2441 2442 In [1]: sc -l b=ls *py
2442 2443
2443 2444 In [2]: b
2444 2445 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2445 2446
2446 2447 In [3]: b.s
2447 2448 Out[3]: 'setup.py win32_manual_post_install.py'
2448 2449
2449 2450 In summary, both the lists and strings used for ouptut capture have
2450 2451 the following special attributes:
2451 2452
2452 2453 .l (or .list) : value as list.
2453 2454 .n (or .nlstr): value as newline-separated string.
2454 2455 .s (or .spstr): value as space-separated string.
2455 2456 """
2456 2457
2457 2458 opts,args = self.parse_options(parameter_s,'lv')
2458 2459 # Try to get a variable name and command to run
2459 2460 try:
2460 2461 # the variable name must be obtained from the parse_options
2461 2462 # output, which uses shlex.split to strip options out.
2462 2463 var,_ = args.split('=',1)
2463 2464 var = var.strip()
2464 2465 # But the the command has to be extracted from the original input
2465 2466 # parameter_s, not on what parse_options returns, to avoid the
2466 2467 # quote stripping which shlex.split performs on it.
2467 2468 _,cmd = parameter_s.split('=',1)
2468 2469 except ValueError:
2469 2470 var,cmd = '',''
2470 2471 if not var:
2471 2472 error('you must specify a variable to assign the command to.')
2472 2473 return
2473 2474 # If all looks ok, proceed
2474 2475 out,err = self.shell.getoutputerror(cmd)
2475 2476 if err:
2476 2477 print >> Term.cerr,err
2477 2478 if opts.has_key('l'):
2478 2479 out = SList(out.split('\n'))
2479 2480 else:
2480 2481 out = LSString(out)
2481 2482 if opts.has_key('v'):
2482 2483 print '%s ==\n%s' % (var,pformat(out))
2483 2484 self.shell.user_ns.update({var:out})
2484 2485
2485 2486 def magic_sx(self, parameter_s=''):
2486 2487 """Shell execute - run a shell command and capture its output.
2487 2488
2488 2489 %sx command
2489 2490
2490 2491 IPython will run the given command using commands.getoutput(), and
2491 2492 return the result formatted as a list (split on '\\n'). Since the
2492 2493 output is _returned_, it will be stored in ipython's regular output
2493 2494 cache Out[N] and in the '_N' automatic variables.
2494 2495
2495 2496 Notes:
2496 2497
2497 2498 1) If an input line begins with '!!', then %sx is automatically
2498 2499 invoked. That is, while:
2499 2500 !ls
2500 2501 causes ipython to simply issue system('ls'), typing
2501 2502 !!ls
2502 2503 is a shorthand equivalent to:
2503 2504 %sx ls
2504 2505
2505 2506 2) %sx differs from %sc in that %sx automatically splits into a list,
2506 2507 like '%sc -l'. The reason for this is to make it as easy as possible
2507 2508 to process line-oriented shell output via further python commands.
2508 2509 %sc is meant to provide much finer control, but requires more
2509 2510 typing.
2510 2511
2511 2512 3) Just like %sc -l, this is a list with special attributes:
2512 2513
2513 2514 .l (or .list) : value as list.
2514 2515 .n (or .nlstr): value as newline-separated string.
2515 2516 .s (or .spstr): value as whitespace-separated string.
2516 2517
2517 2518 This is very useful when trying to use such lists as arguments to
2518 2519 system commands."""
2519 2520
2520 2521 if parameter_s:
2521 2522 out,err = self.shell.getoutputerror(parameter_s)
2522 2523 if err:
2523 2524 print >> Term.cerr,err
2524 2525 return SList(out.split('\n'))
2525 2526
2526 2527 def magic_bg(self, parameter_s=''):
2527 2528 """Run a job in the background, in a separate thread.
2528 2529
2529 2530 For example,
2530 2531
2531 2532 %bg myfunc(x,y,z=1)
2532 2533
2533 2534 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2534 2535 execution starts, a message will be printed indicating the job
2535 2536 number. If your job number is 5, you can use
2536 2537
2537 2538 myvar = jobs.result(5) or myvar = jobs[5].result
2538 2539
2539 2540 to assign this result to variable 'myvar'.
2540 2541
2541 2542 IPython has a job manager, accessible via the 'jobs' object. You can
2542 2543 type jobs? to get more information about it, and use jobs.<TAB> to see
2543 2544 its attributes. All attributes not starting with an underscore are
2544 2545 meant for public use.
2545 2546
2546 2547 In particular, look at the jobs.new() method, which is used to create
2547 2548 new jobs. This magic %bg function is just a convenience wrapper
2548 2549 around jobs.new(), for expression-based jobs. If you want to create a
2549 2550 new job with an explicit function object and arguments, you must call
2550 2551 jobs.new() directly.
2551 2552
2552 2553 The jobs.new docstring also describes in detail several important
2553 2554 caveats associated with a thread-based model for background job
2554 2555 execution. Type jobs.new? for details.
2555 2556
2556 2557 You can check the status of all jobs with jobs.status().
2557 2558
2558 2559 The jobs variable is set by IPython into the Python builtin namespace.
2559 2560 If you ever declare a variable named 'jobs', you will shadow this
2560 2561 name. You can either delete your global jobs variable to regain
2561 2562 access to the job manager, or make a new name and assign it manually
2562 2563 to the manager (stored in IPython's namespace). For example, to
2563 2564 assign the job manager to the Jobs name, use:
2564 2565
2565 2566 Jobs = __builtins__.jobs"""
2566 2567
2567 2568 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2568 2569
2569 2570 def magic_store(self, parameter_s=''):
2570 2571 """Lightweight persistence for python variables.
2571 2572
2572 2573 Example:
2573 2574
2574 2575 ville@badger[~]|1> A = ['hello',10,'world']\\
2575 2576 ville@badger[~]|2> %store A\\
2576 2577 ville@badger[~]|3> Exit
2577 2578
2578 2579 (IPython session is closed and started again...)
2579 2580
2580 2581 ville@badger:~$ ipython -p pysh\\
2581 2582 ville@badger[~]|1> print A
2582 2583
2583 2584 ['hello', 10, 'world']
2584 2585
2585 2586 Usage:
2586 2587
2587 2588 %store - Show list of all variables and their current values\\
2588 2589 %store <var> - Store the *current* value of the variable to disk\\
2589 2590 %store -d <var> - Remove the variable and its value from storage\\
2590 2591 %store -r - Remove all variables from storage
2591 2592
2592 2593 It should be noted that if you change the value of a variable, you
2593 2594 need to %store it again if you want to persist the new value.
2594 2595
2595 2596 Note also that the variables will need to be pickleable; most basic
2596 2597 python types can be safely %stored.
2597 2598 """
2598 2599
2599 2600 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2600 2601 # delete
2601 2602 if opts.has_key('d'):
2602 2603 try:
2603 2604 todel = args[0]
2604 2605 except IndexError:
2605 2606 error('You must provide the variable to forget')
2606 2607 else:
2607 2608 try:
2608 2609 del self.shell.persist['S:' + todel]
2609 2610 except:
2610 2611 error("Can't delete variable '%s'" % todel)
2611 2612 # reset
2612 2613 elif opts.has_key('r'):
2613 2614 for k in self.shell.persist.keys():
2614 2615 if k.startswith('S:'):
2615 2616 del self.shell.persist[k]
2616 2617
2617 2618 # run without arguments -> list variables & values
2618 2619 elif not args:
2619 2620 vars = [v[2:] for v in self.shell.persist.keys()
2620 2621 if v.startswith('S:')]
2621 2622 vars.sort()
2622 2623 if vars:
2623 2624 size = max(map(len,vars))
2624 2625 else:
2625 2626 size = 0
2626 2627
2627 2628 print 'Stored variables and their in-memory values:'
2628 2629 fmt = '%-'+str(size)+'s -> %s'
2629 2630 get = self.shell.user_ns.get
2630 2631 for var in vars:
2631 2632 # print 30 first characters from every var
2632 2633 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2633 2634
2634 2635 # default action - store the variable
2635 2636 else:
2636 2637 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2637 2638 self.shell.persist[ 'S:' + args[0] ] = pickled
2638 2639 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2639 2640
2640 2641 def magic_bookmark(self, parameter_s=''):
2641 2642 """Manage IPython's bookmark system.
2642 2643
2643 2644 %bookmark <name> - set bookmark to current dir
2644 2645 %bookmark <name> <dir> - set bookmark to <dir>
2645 2646 %bookmark -l - list all bookmarks
2646 2647 %bookmark -d <name> - remove bookmark
2647 2648 %bookmark -r - remove all bookmarks
2648 2649
2649 2650 You can later on access a bookmarked folder with:
2650 2651 %cd -b <name>
2651 2652 or simply '%cd <name>' if there is no directory called <name> AND
2652 2653 there is such a bookmark defined.
2653 2654
2654 2655 Your bookmarks persist through IPython sessions, but they are
2655 2656 associated with each profile."""
2656 2657
2657 2658 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2658 2659 if len(args) > 2:
2659 2660 error('You can only give at most two arguments')
2660 2661 return
2661 2662
2662 2663 bkms = self.shell.persist.get('bookmarks',{})
2663 2664
2664 2665 if opts.has_key('d'):
2665 2666 try:
2666 2667 todel = args[0]
2667 2668 except IndexError:
2668 2669 error('You must provide a bookmark to delete')
2669 2670 else:
2670 2671 try:
2671 2672 del bkms[todel]
2672 2673 except:
2673 2674 error("Can't delete bookmark '%s'" % todel)
2674 2675 elif opts.has_key('r'):
2675 2676 bkms = {}
2676 2677 elif opts.has_key('l'):
2677 2678 bks = bkms.keys()
2678 2679 bks.sort()
2679 2680 if bks:
2680 2681 size = max(map(len,bks))
2681 2682 else:
2682 2683 size = 0
2683 2684 fmt = '%-'+str(size)+'s -> %s'
2684 2685 print 'Current bookmarks:'
2685 2686 for bk in bks:
2686 2687 print fmt % (bk,bkms[bk])
2687 2688 else:
2688 2689 if not args:
2689 2690 error("You must specify the bookmark name")
2690 2691 elif len(args)==1:
2691 2692 bkms[args[0]] = os.getcwd()
2692 2693 elif len(args)==2:
2693 2694 bkms[args[0]] = args[1]
2694 2695 self.shell.persist['bookmarks'] = bkms
2695 2696
2696 2697 def magic_pycat(self, parameter_s=''):
2697 2698 """Show a syntax-highlighted file through a pager.
2698 2699
2699 2700 This magic is similar to the cat utility, but it will assume the file
2700 2701 to be Python source and will show it with syntax highlighting. """
2701 2702
2702 2703 filename = get_py_filename(parameter_s)
2703 2704 page(self.shell.colorize(file_read(filename)),
2704 2705 screen_lines=self.shell.rc.screen_length)
2705 2706
2706 2707 # end Magic
@@ -1,565 +1,587 b''
1 1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 963 2005-12-28 19:21:29Z fperez $
2 # $Id: ipythonrc 990 2006-01-04 06:59:02Z fperez $
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 # Automatic calling of callable objects. If set to true, callable objects are
41 # automatically called when invoked at the command line, even if you don't
40
41 # Automatic calling of callable objects. If set to 1 or 2, callable objects
42 # are automatically called when invoked at the command line, even if you don't
42 43 # type parentheses. IPython adds the parentheses for you. For example:
43 44
44 45 #In [1]: str 45
45 46 #------> str(45)
46 47 #Out[1]: '45'
47 48
48 49 # IPython reprints your line with '---->' indicating that it added
49 50 # parentheses. While this option is very convenient for interactive use, it
50 51 # may occasionally cause problems with objects which have side-effects if
51 # called unexpectedly. Set it to 0 if you want to disable it.
52 # called unexpectedly.
53
54 # The valid values for autocall are:
55
56 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
57
58 # autocall 1 -> active, but do not apply if there are no arguments on the line.
59
60 # In this mode, you get:
61
62 #In [1]: callable
63 #Out[1]: <built-in function callable>
64
65 #In [2]: callable 'hello'
66 #------> callable('hello')
67 #Out[2]: False
68
69 # 2 -> Active always. Even if no arguments are present, the callable object
70 # is called:
71
72 #In [4]: callable
73 #------> callable()
52 74
53 75 # Note that even with autocall off, you can still use '/' at the start of a
54 76 # line to treat the first argument on the command line as a function and add
55 77 # parentheses to it:
56 78
57 79 #In [8]: /str 43
58 80 #------> str(43)
59 81 #Out[8]: '43'
60 82
61 83 autocall 1
62 84
63 85 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
64 86 # source code (see the 'editor' variable below), it is possible that you save
65 87 # a file with syntax errors in it. If this variable is true, IPython will ask
66 88 # you whether to re-open the editor immediately to correct such an error.
67 89
68 90 autoedit_syntax 1
69 91
70 92 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
71 93 # line, while also un-indenting automatically after 'raise' or 'return'.
72 94
73 95 # This feature uses the readline library, so it will honor your ~/.inputrc
74 96 # configuration (or whatever file your INPUTRC variable points to). Adding
75 97 # the following lines to your .inputrc file can make indent/unindenting more
76 98 # convenient (M-i indents, M-u unindents):
77 99
78 100 # $if Python
79 101 # "\M-i": " "
80 102 # "\M-u": "\d\d\d\d"
81 103 # $endif
82 104
83 105 # The feature is potentially a bit dangerous, because it can cause problems
84 106 # with pasting of indented code (the pasted code gets re-indented on each
85 107 # line). But it's a huge time-saver when working interactively. The magic
86 108 # function @autoindent allows you to toggle it on/off at runtime.
87 109
88 110 autoindent 1
89 111
90 112 # Auto-magic. This gives you access to all the magic functions without having
91 113 # to prepend them with an @ sign. If you define a variable with the same name
92 114 # as a magic function (say who=1), you will need to access the magic function
93 115 # with @ (@who in this example). However, if later you delete your variable
94 116 # (del who), you'll recover the automagic calling form.
95 117
96 118 # Considering that many magic functions provide a lot of shell-like
97 119 # functionality, automagic gives you something close to a full Python+system
98 120 # shell environment (and you can extend it further if you want).
99 121
100 122 automagic 1
101 123
102 124 # Size of the output cache. After this many entries are stored, the cache will
103 125 # get flushed. Depending on the size of your intermediate calculations, you
104 126 # may have memory problems if you make it too big, since keeping things in the
105 127 # cache prevents Python from reclaiming the memory for old results. Experiment
106 128 # with a value that works well for you.
107 129
108 130 # If you choose cache_size 0 IPython will revert to python's regular >>>
109 131 # unnumbered prompt. You will still have _, __ and ___ for your last three
110 132 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
111 133 # you are running on a slow machine or with very limited memory, this may
112 134 # help.
113 135
114 136 cache_size 1000
115 137
116 138 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
117 139 # but that's your choice! Classic 1 -> same as IPython -classic.
118 140 # Note that this is _not_ the normal python interpreter, it's simply
119 141 # IPython emulating most of the classic interpreter's behavior.
120 142 classic 0
121 143
122 144 # colors - Coloring option for prompts and traceback printouts.
123 145
124 146 # Currently available schemes: NoColor, Linux, LightBG.
125 147
126 148 # This option allows coloring the prompts and traceback printouts. This
127 149 # requires a terminal which can properly handle color escape sequences. If you
128 150 # are having problems with this, use the NoColor scheme (uses no color escapes
129 151 # at all).
130 152
131 153 # The Linux option works well in linux console type environments: dark
132 154 # background with light fonts.
133 155
134 156 # LightBG is similar to Linux but swaps dark/light colors to be more readable
135 157 # in light background terminals.
136 158
137 159 # keep uncommented only the one you want:
138 160 colors Linux
139 161 #colors LightBG
140 162 #colors NoColor
141 163
142 164 ########################
143 165 # Note to Windows users
144 166 #
145 167 # Color and readline support is avaialble to Windows users via Gary Bishop's
146 168 # readline library. You can find Gary's tools at
147 169 # http://sourceforge.net/projects/uncpythontools.
148 170 # Note that his readline module requires in turn the ctypes library, available
149 171 # at http://starship.python.net/crew/theller/ctypes.
150 172 ########################
151 173
152 174 # color_info: IPython can display information about objects via a set of
153 175 # functions, and optionally can use colors for this, syntax highlighting
154 176 # source code and various other elements. This information is passed through a
155 177 # pager (it defaults to 'less' if $PAGER is not set).
156 178
157 179 # If your pager has problems, try to setting it to properly handle escapes
158 180 # (see the less manpage for detail), or disable this option. The magic
159 181 # function @color_info allows you to toggle this interactively for testing.
160 182
161 183 color_info 1
162 184
163 185 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
164 186 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
165 187 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
166 188 # any confirmation.
167 189
168 190 confirm_exit 1
169 191
170 192 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
171 193 # still available as dreload() and appears as a builtin.
172 194
173 195 deep_reload 0
174 196
175 197 # Which editor to use with the @edit command. If you leave this at 0, IPython
176 198 # will honor your EDITOR environment variable. Since this editor is invoked on
177 199 # the fly by ipython and is meant for editing small code snippets, you may
178 200 # want to use a small, lightweight editor here.
179 201
180 202 # For Emacs users, setting up your Emacs server properly as described in the
181 203 # manual is a good idea. An alternative is to use jed, a very light editor
182 204 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
183 205
184 206 editor 0
185 207
186 208 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
187 209 log 0
188 210
189 211 # Same as ipython -Logfile YourLogfileName.
190 212 # Don't use with log 1 (use one or the other)
191 213 logfile ''
192 214
193 215 # banner 0 -> same as ipython -nobanner
194 216 banner 1
195 217
196 218 # messages 0 -> same as ipython -nomessages
197 219 messages 1
198 220
199 221 # Automatically call the pdb debugger after every uncaught exception. If you
200 222 # are used to debugging using pdb, this puts you automatically inside of it
201 223 # after any call (either in IPython or in code called by it) which triggers an
202 224 # exception which goes uncaught.
203 225 pdb 0
204 226
205 227 # Enable the pprint module for printing. pprint tends to give a more readable
206 228 # display (than print) for complex nested data structures.
207 229 pprint 1
208 230
209 231 # Prompt strings
210 232
211 233 # Most bash-like escapes can be used to customize IPython's prompts, as well as
212 234 # a few additional ones which are IPython-specific. All valid prompt escapes
213 235 # are described in detail in the Customization section of the IPython HTML/PDF
214 236 # manual.
215 237
216 238 # Use \# to represent the current prompt number, and quote them to protect
217 239 # spaces.
218 240 prompt_in1 'In [\#]: '
219 241
220 242 # \D is replaced by as many dots as there are digits in the
221 243 # current value of \#.
222 244 prompt_in2 ' .\D.: '
223 245
224 246 prompt_out 'Out[\#]: '
225 247
226 248 # Select whether to left-pad the output prompts to match the length of the
227 249 # input ones. This allows you for example to use a simple '>' as an output
228 250 # prompt, and yet have the output line up with the input. If set to false,
229 251 # the output prompts will be unpadded (flush left).
230 252 prompts_pad_left 1
231 253
232 254 # quick 1 -> same as ipython -quick
233 255 quick 0
234 256
235 257 # Use the readline library (1) or not (0). Most users will want this on, but
236 258 # if you experience strange problems with line management (mainly when using
237 259 # IPython inside Emacs buffers) you may try disabling it. Not having it on
238 260 # prevents you from getting command history with the arrow keys, searching and
239 261 # name completion using TAB.
240 262
241 263 readline 1
242 264
243 265 # Screen Length: number of lines of your screen. This is used to control
244 266 # printing of very long strings. Strings longer than this number of lines will
245 267 # be paged with the less command instead of directly printed.
246 268
247 269 # The default value for this is 0, which means IPython will auto-detect your
248 270 # screen size every time it needs to print. If for some reason this isn't
249 271 # working well (it needs curses support), specify it yourself. Otherwise don't
250 272 # change the default.
251 273
252 274 screen_length 0
253 275
254 276 # Prompt separators for input and output.
255 277 # Use \n for newline explicitly, without quotes.
256 278 # Use 0 (like at the cmd line) to turn off a given separator.
257 279
258 280 # The structure of prompt printing is:
259 281 # (SeparateIn)Input....
260 282 # (SeparateOut)Output...
261 283 # (SeparateOut2), # that is, no newline is printed after Out2
262 284 # By choosing these you can organize your output any way you want.
263 285
264 286 separate_in \n
265 287 separate_out 0
266 288 separate_out2 0
267 289
268 290 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
269 291 # Simply removes all input/output separators, overriding the choices above.
270 292 nosep 0
271 293
272 294 # Wildcard searches - IPython has a system for searching names using
273 295 # shell-like wildcards; type %psearch? for details. This variables sets
274 296 # whether by default such searches should be case sensitive or not. You can
275 297 # always override the default at the system command line or the IPython
276 298 # prompt.
277 299
278 300 wildcards_case_sensitive 1
279 301
280 302 # xmode - Exception reporting mode.
281 303
282 304 # Valid modes: Plain, Context and Verbose.
283 305
284 306 # Plain: similar to python's normal traceback printing.
285 307
286 308 # Context: prints 5 lines of context source code around each line in the
287 309 # traceback.
288 310
289 311 # Verbose: similar to Context, but additionally prints the variables currently
290 312 # visible where the exception happened (shortening their strings if too
291 313 # long). This can potentially be very slow, if you happen to have a huge data
292 314 # structure whose string representation is complex to compute. Your computer
293 315 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
294 316 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
295 317
296 318 #xmode Plain
297 319 xmode Context
298 320 #xmode Verbose
299 321
300 322 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
301 323 # !cmd) to be used in multi-line input (like for loops). For example, if you
302 324 # have this active, the following is valid in IPython:
303 325 #
304 326 #In [17]: for i in range(3):
305 327 # ....: mkdir $i
306 328 # ....: !touch $i/hello
307 329 # ....: ls -l $i
308 330
309 331 multi_line_specials 1
310 332
311 333 #---------------------------------------------------------------------------
312 334 # Section: Readline configuration (readline is not available for MS-Windows)
313 335
314 336 # This is done via the following options:
315 337
316 338 # (i) readline_parse_and_bind: this option can appear as many times as you
317 339 # want, each time defining a string to be executed via a
318 340 # readline.parse_and_bind() command. The syntax for valid commands of this
319 341 # kind can be found by reading the documentation for the GNU readline library,
320 342 # as these commands are of the kind which readline accepts in its
321 343 # configuration file.
322 344
323 345 # The TAB key can be used to complete names at the command line in one of two
324 346 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
325 347 # completes as much as possible while 'menu-complete' cycles through all
326 348 # possible completions. Leave the one you prefer uncommented.
327 349
328 350 readline_parse_and_bind tab: complete
329 351 #readline_parse_and_bind tab: menu-complete
330 352
331 353 # This binds Control-l to printing the list of all possible completions when
332 354 # there is more than one (what 'complete' does when hitting TAB twice, or at
333 355 # the first TAB if show-all-if-ambiguous is on)
334 356 readline_parse_and_bind "\C-l": possible-completions
335 357
336 358 # This forces readline to automatically print the above list when tab
337 359 # completion is set to 'complete'. You can still get this list manually by
338 360 # using the key bound to 'possible-completions' (Control-l by default) or by
339 361 # hitting TAB twice. Turning this on makes the printing happen at the first
340 362 # TAB.
341 363 readline_parse_and_bind set show-all-if-ambiguous on
342 364
343 365 # If you have TAB set to complete names, you can rebind any key (Control-o by
344 366 # default) to insert a true TAB character.
345 367 readline_parse_and_bind "\C-o": tab-insert
346 368
347 369 # These commands allow you to indent/unindent easily, with the 4-space
348 370 # convention of the Python coding standards. Since IPython's internal
349 371 # auto-indent system also uses 4 spaces, you should not change the number of
350 372 # spaces in the code below.
351 373 readline_parse_and_bind "\M-i": " "
352 374 readline_parse_and_bind "\M-o": "\d\d\d\d"
353 375 readline_parse_and_bind "\M-I": "\d\d\d\d"
354 376
355 377 # Bindings for incremental searches in the history. These searches use the
356 378 # string typed so far on the command line and search anything in the previous
357 379 # input history containing them.
358 380 readline_parse_and_bind "\C-r": reverse-search-history
359 381 readline_parse_and_bind "\C-s": forward-search-history
360 382
361 383 # Bindings for completing the current line in the history of previous
362 384 # commands. This allows you to recall any previous command by typing its first
363 385 # few letters and hitting Control-p, bypassing all intermediate commands which
364 386 # may be in the history (much faster than hitting up-arrow 50 times!)
365 387 readline_parse_and_bind "\C-p": history-search-backward
366 388 readline_parse_and_bind "\C-n": history-search-forward
367 389
368 390 # I also like to have the same functionality on the plain arrow keys. If you'd
369 391 # rather have the arrows use all the history (and not just match what you've
370 392 # typed so far), comment out or delete the next two lines.
371 393 readline_parse_and_bind "\e[A": history-search-backward
372 394 readline_parse_and_bind "\e[B": history-search-forward
373 395
374 396 # These are typically on by default under *nix, but not win32.
375 397 readline_parse_and_bind "\C-k": kill-line
376 398 readline_parse_and_bind "\C-u": unix-line-discard
377 399
378 400 # (ii) readline_remove_delims: a string of characters to be removed from the
379 401 # default word-delimiters list used by readline, so that completions may be
380 402 # performed on strings which contain them.
381 403
382 404 readline_remove_delims -/~
383 405
384 406 # (iii) readline_merge_completions: whether to merge the result of all
385 407 # possible completions or not. If true, IPython will complete filenames,
386 408 # python names and aliases and return all possible completions. If you set it
387 409 # to false, each completer is used at a time, and only if it doesn't return
388 410 # any completions is the next one used.
389 411
390 412 # The default order is: [python_matches, file_matches, alias_matches]
391 413
392 414 readline_merge_completions 1
393 415
394 416 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
395 417 # will complete all attributes of an object, including all the special methods
396 418 # whose names start with single or double underscores (like __getitem__ or
397 419 # __class__).
398 420
399 421 # This variable allows you to control this completion behavior:
400 422
401 423 # readline_omit__names 1 -> completion will omit showing any names starting
402 424 # with two __, but it will still show names starting with one _.
403 425
404 426 # readline_omit__names 2 -> completion will omit all names beginning with one
405 427 # _ (which obviously means filtering out the double __ ones).
406 428
407 429 # Even when this option is set, you can still see those names by explicitly
408 430 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
409 431 # complete attribute names starting with '_'.
410 432
411 433 # This option is off by default so that new users see all attributes of any
412 434 # objects they are dealing with.
413 435
414 436 readline_omit__names 0
415 437
416 438 #---------------------------------------------------------------------------
417 439 # Section: modules to be loaded with 'import ...'
418 440
419 441 # List, separated by spaces, the names of the modules you want to import
420 442
421 443 # Example:
422 444 # import_mod sys os
423 445 # will produce internally the statements
424 446 # import sys
425 447 # import os
426 448
427 449 # Each import is executed in its own try/except block, so if one module
428 450 # fails to load the others will still be ok.
429 451
430 452 import_mod
431 453
432 454 #---------------------------------------------------------------------------
433 455 # Section: modules to import some functions from: 'from ... import ...'
434 456
435 457 # List, one per line, the modules for which you want only to import some
436 458 # functions. Give the module name first and then the name of functions to be
437 459 # imported from that module.
438 460
439 461 # Example:
440 462
441 463 # import_some IPython.genutils timing timings
442 464 # will produce internally the statement
443 465 # from IPython.genutils import timing, timings
444 466
445 467 # timing() and timings() are two IPython utilities for timing the execution of
446 468 # your own functions, which you may find useful. Just commment out the above
447 469 # line if you want to test them.
448 470
449 471 # If you have more than one modules_some line, each gets its own try/except
450 472 # block (like modules, see above).
451 473
452 474 import_some
453 475
454 476 #---------------------------------------------------------------------------
455 477 # Section: modules to import all from : 'from ... import *'
456 478
457 479 # List (same syntax as import_mod above) those modules for which you want to
458 480 # import all functions. Remember, this is a potentially dangerous thing to do,
459 481 # since it is very easy to overwrite names of things you need. Use with
460 482 # caution.
461 483
462 484 # Example:
463 485 # import_all sys os
464 486 # will produce internally the statements
465 487 # from sys import *
466 488 # from os import *
467 489
468 490 # As before, each will be called in a separate try/except block.
469 491
470 492 import_all
471 493
472 494 #---------------------------------------------------------------------------
473 495 # Section: Python code to execute.
474 496
475 497 # Put here code to be explicitly executed (keep it simple!)
476 498 # Put one line of python code per line. All whitespace is removed (this is a
477 499 # feature, not a bug), so don't get fancy building loops here.
478 500 # This is just for quick convenient creation of things you want available.
479 501
480 502 # Example:
481 503 # execute x = 1
482 504 # execute print 'hello world'; y = z = 'a'
483 505 # will produce internally
484 506 # x = 1
485 507 # print 'hello world'; y = z = 'a'
486 508 # and each *line* (not each statement, we don't do python syntax parsing) is
487 509 # executed in its own try/except block.
488 510
489 511 execute
490 512
491 513 # Note for the adventurous: you can use this to define your own names for the
492 514 # magic functions, by playing some namespace tricks:
493 515
494 516 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
495 517
496 518 # defines @pf as a new name for @profile.
497 519
498 520 #---------------------------------------------------------------------------
499 521 # Section: Pyhton files to load and execute.
500 522
501 523 # Put here the full names of files you want executed with execfile(file). If
502 524 # you want complicated initialization, just write whatever you want in a
503 525 # regular python file and load it from here.
504 526
505 527 # Filenames defined here (which *must* include the extension) are searched for
506 528 # through all of sys.path. Since IPython adds your .ipython directory to
507 529 # sys.path, they can also be placed in your .ipython dir and will be
508 530 # found. Otherwise (if you want to execute things not in .ipyton nor in
509 531 # sys.path) give a full path (you can use ~, it gets expanded)
510 532
511 533 # Example:
512 534 # execfile file1.py ~/file2.py
513 535 # will generate
514 536 # execfile('file1.py')
515 537 # execfile('_path_to_your_home/file2.py')
516 538
517 539 # As before, each file gets its own try/except block.
518 540
519 541 execfile
520 542
521 543 # If you are feeling adventurous, you can even add functionality to IPython
522 544 # through here. IPython works through a global variable called __ip which
523 545 # exists at the time when these files are read. If you know what you are doing
524 546 # (read the source) you can add functions to __ip in files loaded here.
525 547
526 548 # The file example-magic.py contains a simple but correct example. Try it:
527 549
528 550 # execfile example-magic.py
529 551
530 552 # Look at the examples in IPython/iplib.py for more details on how these magic
531 553 # functions need to process their arguments.
532 554
533 555 #---------------------------------------------------------------------------
534 556 # Section: aliases for system shell commands
535 557
536 558 # Here you can define your own names for system commands. The syntax is
537 559 # similar to that of the builtin @alias function:
538 560
539 561 # alias alias_name command_string
540 562
541 563 # The resulting aliases are auto-generated magic functions (hence usable as
542 564 # @alias_name)
543 565
544 566 # For example:
545 567
546 568 # alias myls ls -la
547 569
548 570 # will define 'myls' as an alias for executing the system command 'ls -la'.
549 571 # This allows you to customize IPython's environment to have the same aliases
550 572 # you are accustomed to from your own shell.
551 573
552 574 # You can also define aliases with parameters using %s specifiers (one per
553 575 # parameter):
554 576
555 577 # alias parts echo first %s second %s
556 578
557 579 # will give you in IPython:
558 580 # >>> @parts A B
559 581 # first A second B
560 582
561 583 # Use one 'alias' statement per alias you wish to define.
562 584
563 585 # alias
564 586
565 587 #************************* end of file <ipythonrc> ************************
@@ -1,539 +1,556 b''
1 1 """Word completion for IPython.
2 2
3 3 This module is a fork of the rlcompleter module in the Python standard
4 4 library. The original enhancements made to rlcompleter have been sent
5 5 upstream and were accepted as of Python 2.3, but we need a lot more
6 6 functionality specific to IPython, so this module will continue to live as an
7 7 IPython-specific utility.
8 8
9 9 ---------------------------------------------------------------------------
10 10 Original rlcompleter documentation:
11 11
12 12 This requires the latest extension to the readline module (the
13 13 completes keywords, built-ins and globals in __main__; when completing
14 14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 15 completes its attributes.
16 16
17 17 It's very cool to do "import string" type "string.", hit the
18 18 completion key (twice), and see the list of names defined by the
19 19 string module!
20 20
21 21 Tip: to use the tab key as the completion key, call
22 22
23 23 readline.parse_and_bind("tab: complete")
24 24
25 25 Notes:
26 26
27 27 - Exceptions raised by the completer function are *ignored* (and
28 28 generally cause the completion to fail). This is a feature -- since
29 29 readline sets the tty device in raw (or cbreak) mode, printing a
30 30 traceback wouldn't work well without some complicated hoopla to save,
31 31 reset and restore the tty state.
32 32
33 33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 34 application defined code to be executed if an object with a
35 35 __getattr__ hook is found. Since it is the responsibility of the
36 36 application (or the user) to enable this feature, I consider this an
37 37 acceptable risk. More complicated expressions (e.g. function calls or
38 38 indexing operations) are *not* evaluated.
39 39
40 40 - GNU readline is also used by the built-in functions input() and
41 41 raw_input(), and thus these also benefit/suffer from the completer
42 42 features. Clearly an interactive application can benefit by
43 43 specifying its own completer function and using raw_input() for all
44 44 its input.
45 45
46 46 - When the original stdin is not a tty device, GNU readline is never
47 47 used, and this module (and the readline module) are silently inactive.
48 48
49 49 """
50 50
51 51 #*****************************************************************************
52 52 #
53 53 # Since this file is essentially a minimally modified copy of the rlcompleter
54 54 # module which is part of the standard Python distribution, I assume that the
55 55 # proper procedure is to maintain its copyright as belonging to the Python
56 56 # Software Foundation (in addition to my own, for all new code).
57 57 #
58 58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 59 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
60 60 #
61 61 # Distributed under the terms of the BSD License. The full license is in
62 62 # the file COPYING, distributed as part of this software.
63 63 #
64 64 #*****************************************************************************
65 65
66 66 import __builtin__
67 67 import __main__
68 68 import glob
69 69 import keyword
70 70 import os
71 71 import re
72 72 import readline
73 73 import sys
74 74 import types
75 75
76 # Python 2.4 offers sets as a builtin
77 try:
78 set([1,2])
79 except NameError:
80 from sets import Set as set
81
82
76 83 from IPython.genutils import shlex_split
77 84
78 85 __all__ = ['Completer','IPCompleter']
79 86
80 87 def get_class_members(cls):
81 88 ret = dir(cls)
82 89 if hasattr(cls,'__bases__'):
83 90 for base in cls.__bases__:
84 91 ret.extend(get_class_members(base))
85 92 return ret
86 93
87 94 class Completer:
88 95 def __init__(self,namespace=None,global_namespace=None):
89 96 """Create a new completer for the command line.
90 97
91 98 Completer([namespace,global_namespace]) -> completer instance.
92 99
93 100 If unspecified, the default namespace where completions are performed
94 101 is __main__ (technically, __main__.__dict__). Namespaces should be
95 102 given as dictionaries.
96 103
97 104 An optional second namespace can be given. This allows the completer
98 105 to handle cases where both the local and global scopes need to be
99 106 distinguished.
100 107
101 108 Completer instances should be used as the completion mechanism of
102 109 readline via the set_completer() call:
103 110
104 111 readline.set_completer(Completer(my_namespace).complete)
105 112 """
106 113
107 114 # some minimal strict typechecks. For some core data structures, I
108 115 # want actual basic python types, not just anything that looks like
109 116 # one. This is especially true for namespaces.
110 117 for ns in (namespace,global_namespace):
111 118 if ns is not None and type(ns) != types.DictType:
112 119 raise TypeError,'namespace must be a dictionary'
113 120
114 121 # Don't bind to namespace quite yet, but flag whether the user wants a
115 122 # specific namespace or to use __main__.__dict__. This will allow us
116 123 # to bind to __main__.__dict__ at completion time, not now.
117 124 if namespace is None:
118 125 self.use_main_ns = 1
119 126 else:
120 127 self.use_main_ns = 0
121 128 self.namespace = namespace
122 129
123 130 # The global namespace, if given, can be bound directly
124 131 if global_namespace is None:
125 132 self.global_namespace = {}
126 133 else:
127 134 self.global_namespace = global_namespace
128 135
129 136 def complete(self, text, state):
130 137 """Return the next possible completion for 'text'.
131 138
132 139 This is called successively with state == 0, 1, 2, ... until it
133 140 returns None. The completion should begin with 'text'.
134 141
135 142 """
136 143 if self.use_main_ns:
137 144 self.namespace = __main__.__dict__
138 145
139 146 if state == 0:
140 147 if "." in text:
141 148 self.matches = self.attr_matches(text)
142 149 else:
143 150 self.matches = self.global_matches(text)
144 151 try:
145 152 return self.matches[state]
146 153 except IndexError:
147 154 return None
148 155
149 156 def global_matches(self, text):
150 157 """Compute matches when text is a simple name.
151 158
152 159 Return a list of all keywords, built-in functions and names currently
153 160 defined in self.namespace or self.global_namespace that match.
154 161
155 162 """
156 163 matches = []
157 164 match_append = matches.append
158 165 n = len(text)
159 166 for lst in [keyword.kwlist,
160 167 __builtin__.__dict__.keys(),
161 168 self.namespace.keys(),
162 169 self.global_namespace.keys()]:
163 170 for word in lst:
164 171 if word[:n] == text and word != "__builtins__":
165 172 match_append(word)
166 173 return matches
167 174
168 175 def attr_matches(self, text):
169 176 """Compute matches when text contains a dot.
170 177
171 178 Assuming the text is of the form NAME.NAME....[NAME], and is
172 179 evaluatable in self.namespace or self.global_namespace, it will be
173 180 evaluated and its attributes (as revealed by dir()) are used as
174 181 possible completions. (For class instances, class members are are
175 182 also considered.)
176 183
177 184 WARNING: this can still invoke arbitrary C code, if an object
178 185 with a __getattr__ hook is evaluated.
179 186
180 187 """
181 188 import re
182 189
183 190 # Another option, seems to work great. Catches things like ''.<tab>
184 191 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
185 192
186 193 if not m:
187 194 return []
188 195
189 196 expr, attr = m.group(1, 3)
190 197 try:
191 198 object = eval(expr, self.namespace)
192 199 except:
193 200 object = eval(expr, self.global_namespace)
194 201
202 # Start building the attribute list via dir(), and then complete it
203 # with a few extra special-purpose calls.
195 204 words = dir(object)
205
196 206 if hasattr(object,'__class__'):
197 207 words.append('__class__')
198 208 words.extend(get_class_members(object.__class__))
199 209
210 # this is the 'dir' function for objects with Enthought's traits
211 if hasattr(object, 'trait_names'):
212 words.extend(object.trait_names())
213 # eliminate possible duplicates, as some traits may also appear as
214 # normal attributes in the dir() call.
215 words = set(words)
216
200 217 # filter out non-string attributes which may be stuffed by dir() calls
201 218 # and poor coding in third-party modules
202 219 words = [w for w in words
203 220 if isinstance(w, basestring) and w != "__builtins__"]
204 221 # Build match list to return
205 222 n = len(attr)
206 223 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
207 224
208 225 class IPCompleter(Completer):
209 226 """Extension of the completer class with IPython-specific features"""
210 227
211 228 def __init__(self,shell,namespace=None,global_namespace=None,
212 229 omit__names=0,alias_table=None):
213 230 """IPCompleter() -> completer
214 231
215 232 Return a completer object suitable for use by the readline library
216 233 via readline.set_completer().
217 234
218 235 Inputs:
219 236
220 237 - shell: a pointer to the ipython shell itself. This is needed
221 238 because this completer knows about magic functions, and those can
222 239 only be accessed via the ipython instance.
223 240
224 241 - namespace: an optional dict where completions are performed.
225 242
226 243 - global_namespace: secondary optional dict for completions, to
227 244 handle cases (such as IPython embedded inside functions) where
228 245 both Python scopes are visible.
229 246
230 247 - The optional omit__names parameter sets the completer to omit the
231 248 'magic' names (__magicname__) for python objects unless the text
232 249 to be completed explicitly starts with one or more underscores.
233 250
234 251 - If alias_table is supplied, it should be a dictionary of aliases
235 252 to complete. """
236 253
237 254 Completer.__init__(self,namespace,global_namespace)
238 255 self.magic_prefix = shell.name+'.magic_'
239 256 self.magic_escape = shell.ESC_MAGIC
240 257 self.readline = readline
241 258 delims = self.readline.get_completer_delims()
242 259 delims = delims.replace(self.magic_escape,'')
243 260 self.readline.set_completer_delims(delims)
244 261 self.get_line_buffer = self.readline.get_line_buffer
245 262 self.omit__names = omit__names
246 263 self.merge_completions = shell.rc.readline_merge_completions
247 264
248 265 if alias_table is None:
249 266 alias_table = {}
250 267 self.alias_table = alias_table
251 268 # Regexp to split filenames with spaces in them
252 269 self.space_name_re = re.compile(r'([^\\] )')
253 270 # Hold a local ref. to glob.glob for speed
254 271 self.glob = glob.glob
255 272
256 273 # Determine if we are running on 'dumb' terminals, like (X)Emacs
257 274 # buffers, to avoid completion problems.
258 275 term = os.environ.get('TERM','xterm')
259 276 self.dumb_terminal = term in ['dumb','emacs']
260 277
261 278 # Special handling of backslashes needed in win32 platforms
262 279 if sys.platform == "win32":
263 280 self.clean_glob = self._clean_glob_win32
264 281 else:
265 282 self.clean_glob = self._clean_glob
266 283 self.matchers = [self.python_matches,
267 284 self.file_matches,
268 285 self.alias_matches,
269 286 self.python_func_kw_matches]
270 287
271 288 # Code contributed by Alex Schmolck, for ipython/emacs integration
272 289 def all_completions(self, text):
273 290 """Return all possible completions for the benefit of emacs."""
274 291
275 292 completions = []
276 293 comp_append = completions.append
277 294 try:
278 295 for i in xrange(sys.maxint):
279 296 res = self.complete(text, i)
280 297
281 298 if not res: break
282 299
283 300 comp_append(res)
284 301 #XXX workaround for ``notDefined.<tab>``
285 302 except NameError:
286 303 pass
287 304 return completions
288 305 # /end Alex Schmolck code.
289 306
290 307 def _clean_glob(self,text):
291 308 return self.glob("%s*" % text)
292 309
293 310 def _clean_glob_win32(self,text):
294 311 return [f.replace("\\","/")
295 312 for f in self.glob("%s*" % text)]
296 313
297 314 def file_matches(self, text):
298 315 """Match filneames, expanding ~USER type strings.
299 316
300 317 Most of the seemingly convoluted logic in this completer is an
301 318 attempt to handle filenames with spaces in them. And yet it's not
302 319 quite perfect, because Python's readline doesn't expose all of the
303 320 GNU readline details needed for this to be done correctly.
304 321
305 322 For a filename with a space in it, the printed completions will be
306 323 only the parts after what's already been typed (instead of the
307 324 full completions, as is normally done). I don't think with the
308 325 current (as of Python 2.3) Python readline it's possible to do
309 326 better."""
310 327
311 328 #print 'Completer->file_matches: <%s>' % text # dbg
312 329
313 330 # chars that require escaping with backslash - i.e. chars
314 331 # that readline treats incorrectly as delimiters, but we
315 332 # don't want to treat as delimiters in filename matching
316 333 # when escaped with backslash
317 334
318 335 protectables = ' ()[]{}'
319 336
320 337 def protect_filename(s):
321 338 return "".join([(ch in protectables and '\\' + ch or ch)
322 339 for ch in s])
323 340
324 341 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
325 342 open_quotes = 0 # track strings with open quotes
326 343 try:
327 344 lsplit = shlex_split(lbuf)[-1]
328 345 except ValueError:
329 346 # typically an unmatched ", or backslash without escaped char.
330 347 if lbuf.count('"')==1:
331 348 open_quotes = 1
332 349 lsplit = lbuf.split('"')[-1]
333 350 elif lbuf.count("'")==1:
334 351 open_quotes = 1
335 352 lsplit = lbuf.split("'")[-1]
336 353 else:
337 354 return None
338 355 except IndexError:
339 356 # tab pressed on empty line
340 357 lsplit = ""
341 358
342 359 if lsplit != protect_filename(lsplit):
343 360 # if protectables are found, do matching on the whole escaped
344 361 # name
345 362 has_protectables = 1
346 363 text0,text = text,lsplit
347 364 else:
348 365 has_protectables = 0
349 366 text = os.path.expanduser(text)
350 367
351 368 if text == "":
352 369 return [protect_filename(f) for f in self.glob("*")]
353 370
354 371 m0 = self.clean_glob(text.replace('\\',''))
355 372 if has_protectables:
356 373 # If we had protectables, we need to revert our changes to the
357 374 # beginning of filename so that we don't double-write the part
358 375 # of the filename we have so far
359 376 len_lsplit = len(lsplit)
360 377 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
361 378 else:
362 379 if open_quotes:
363 380 # if we have a string with an open quote, we don't need to
364 381 # protect the names at all (and we _shouldn't_, as it
365 382 # would cause bugs when the filesystem call is made).
366 383 matches = m0
367 384 else:
368 385 matches = [protect_filename(f) for f in m0]
369 386 if len(matches) == 1 and os.path.isdir(matches[0]):
370 387 # Takes care of links to directories also. Use '/'
371 388 # explicitly, even under Windows, so that name completions
372 389 # don't end up escaped.
373 390 matches[0] += '/'
374 391 return matches
375 392
376 393 def alias_matches(self, text):
377 394 """Match internal system aliases"""
378 395 #print 'Completer->alias_matches:',text # dbg
379 396 text = os.path.expanduser(text)
380 397 aliases = self.alias_table.keys()
381 398 if text == "":
382 399 return aliases
383 400 else:
384 401 return [alias for alias in aliases if alias.startswith(text)]
385 402
386 403 def python_matches(self,text):
387 404 """Match attributes or global python names"""
388 405 #print 'Completer->python_matches' # dbg
389 406 if "." in text:
390 407 try:
391 408 matches = self.attr_matches(text)
392 409 if text.endswith('.') and self.omit__names:
393 410 if self.omit__names == 1:
394 411 # true if txt is _not_ a __ name, false otherwise:
395 412 no__name = (lambda txt:
396 413 re.match(r'.*\.__.*?__',txt) is None)
397 414 else:
398 415 # true if txt is _not_ a _ name, false otherwise:
399 416 no__name = (lambda txt:
400 417 re.match(r'.*\._.*?',txt) is None)
401 418 matches = filter(no__name, matches)
402 419 except NameError:
403 420 # catches <undefined attributes>.<tab>
404 421 matches = []
405 422 else:
406 423 matches = self.global_matches(text)
407 424 # this is so completion finds magics when automagic is on:
408 425 if matches == [] and not text.startswith(os.sep):
409 426 matches = self.attr_matches(self.magic_prefix+text)
410 427 return matches
411 428
412 429 def _default_arguments(self, obj):
413 430 """Return the list of default arguments of obj if it is callable,
414 431 or empty list otherwise."""
415 432
416 433 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
417 434 # for classes, check for __init__,__new__
418 435 if inspect.isclass(obj):
419 436 obj = (getattr(obj,'__init__',None) or
420 437 getattr(obj,'__new__',None))
421 438 # for all others, check if they are __call__able
422 439 elif hasattr(obj, '__call__'):
423 440 obj = obj.__call__
424 441 # XXX: is there a way to handle the builtins ?
425 442 try:
426 443 args,_,_1,defaults = inspect.getargspec(obj)
427 444 if defaults:
428 445 return args[-len(defaults):]
429 446 except TypeError: pass
430 447 return []
431 448
432 449 def python_func_kw_matches(self,text):
433 450 """Match named parameters (kwargs) of the last open function"""
434 451
435 452 if "." in text: # a parameter cannot be dotted
436 453 return []
437 454 try: regexp = self.__funcParamsRegex
438 455 except AttributeError:
439 456 regexp = self.__funcParamsRegex = re.compile(r'''
440 457 '.*?' | # single quoted strings or
441 458 ".*?" | # double quoted strings or
442 459 \w+ | # identifier
443 460 \S # other characters
444 461 ''', re.VERBOSE | re.DOTALL)
445 462 # 1. find the nearest identifier that comes before an unclosed
446 463 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
447 464 tokens = regexp.findall(self.get_line_buffer())
448 465 tokens.reverse()
449 466 iterTokens = iter(tokens); openPar = 0
450 467 for token in iterTokens:
451 468 if token == ')':
452 469 openPar -= 1
453 470 elif token == '(':
454 471 openPar += 1
455 472 if openPar > 0:
456 473 # found the last unclosed parenthesis
457 474 break
458 475 else:
459 476 return []
460 477 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
461 478 ids = []
462 479 isId = re.compile(r'\w+$').match
463 480 while True:
464 481 try:
465 482 ids.append(iterTokens.next())
466 483 if not isId(ids[-1]):
467 484 ids.pop(); break
468 485 if not iterTokens.next() == '.':
469 486 break
470 487 except StopIteration:
471 488 break
472 489 # lookup the candidate callable matches either using global_matches
473 490 # or attr_matches for dotted names
474 491 if len(ids) == 1:
475 492 callableMatches = self.global_matches(ids[0])
476 493 else:
477 494 callableMatches = self.attr_matches('.'.join(ids[::-1]))
478 495 argMatches = []
479 496 for callableMatch in callableMatches:
480 497 try: namedArgs = self._default_arguments(eval(callableMatch,
481 498 self.namespace))
482 499 except: continue
483 500 for namedArg in namedArgs:
484 501 if namedArg.startswith(text):
485 502 argMatches.append("%s=" %namedArg)
486 503 return argMatches
487 504
488 505 def complete(self, text, state):
489 506 """Return the next possible completion for 'text'.
490 507
491 508 This is called successively with state == 0, 1, 2, ... until it
492 509 returns None. The completion should begin with 'text'. """
493 510
494 511 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
495 512
496 513 # if there is only a tab on a line with only whitespace, instead
497 514 # of the mostly useless 'do you want to see all million
498 515 # completions' message, just do the right thing and give the user
499 516 # his tab! Incidentally, this enables pasting of tabbed text from
500 517 # an editor (as long as autoindent is off).
501 518
502 519 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
503 520 # don't interfere with their own tab-completion mechanism.
504 521 if not (self.dumb_terminal or self.get_line_buffer().strip()):
505 522 self.readline.insert_text('\t')
506 523 return None
507 524
508 525 magic_escape = self.magic_escape
509 526 magic_prefix = self.magic_prefix
510 527
511 528 try:
512 529 if text.startswith(magic_escape):
513 530 text = text.replace(magic_escape,magic_prefix)
514 531 elif text.startswith('~'):
515 532 text = os.path.expanduser(text)
516 533 if state == 0:
517 534 # Extend the list of completions with the results of each
518 535 # matcher, so we return results to the user from all
519 536 # namespaces.
520 537 if self.merge_completions:
521 538 self.matches = []
522 539 for matcher in self.matchers:
523 540 self.matches.extend(matcher(text))
524 541 else:
525 542 for matcher in self.matchers:
526 543 self.matches = matcher(text)
527 544 if self.matches:
528 545 break
529 546
530 547 try:
531 548 return self.matches[state].replace(magic_prefix,magic_escape)
532 549 except IndexError:
533 550 return None
534 551 except:
535 552 #from IPython.ultraTB import AutoFormattedTB; # dbg
536 553 #tb=AutoFormattedTB('Verbose');tb() #dbg
537 554
538 555 # If completion fails, don't annoy the user.
539 556 return None
@@ -1,1705 +1,1717 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 General purpose utilities.
4 4
5 5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 6 these things are also convenient when working at the command line.
7 7
8 $Id: genutils.py 980 2005-12-30 15:42:04Z fperez $"""
8 $Id: genutils.py 990 2006-01-04 06:59:02Z fperez $"""
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16
17 17 from __future__ import generators # 2.2 compatibility
18 18
19 19 from IPython import Release
20 20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 21 __license__ = Release.license
22 22
23 23 #****************************************************************************
24 24 # required modules from the Python standard library
25 25 import __main__
26 26 import commands
27 27 import os
28 28 import re
29 29 import shlex
30 30 import shutil
31 31 import sys
32 32 import tempfile
33 33 import time
34 34 import types
35 35
36 36 # Other IPython utilities
37 37 from IPython.Itpl import Itpl,itpl,printpl
38 38 from IPython import DPyGetOpt
39 39
40 40 if os.name == "nt":
41 41 from IPython.winconsole import get_console_size
42 42
43 43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 44 # 2.2-friendly
45 45 try:
46 46 basestring
47 47 except NameError:
48 48 import types
49 49 basestring = (types.StringType, types.UnicodeType)
50 50 True = 1==1
51 51 False = 1==0
52 52
53 53 def enumerate(obj):
54 54 i = -1
55 55 for item in obj:
56 56 i += 1
57 57 yield i, item
58 58
59 59 # add these to the builtin namespace, so that all modules find them
60 60 import __builtin__
61 61 __builtin__.basestring = basestring
62 62 __builtin__.True = True
63 63 __builtin__.False = False
64 64 __builtin__.enumerate = enumerate
65 65
66 66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 68 try:
69 69 shlex_split = shlex.split
70 70 except AttributeError:
71 71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
76 76 % os.sep)
77 77
78 78 def shlex_split(s):
79 79 """Simplified backport to Python 2.2 of shlex.split().
80 80
81 81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 82 several of the features needed to really match the functionality of
83 83 shlex.split() in 2.3."""
84 84
85 85 lex = shlex.shlex(StringIO(s))
86 86 # Try to get options, extensions and path separators as characters
87 87 lex.wordchars = _wordchars
88 88 lex.commenters = ''
89 89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 90 # iterator.
91 91 lout = []
92 92 while 1:
93 93 token = lex.get_token()
94 94 if token == '':
95 95 break
96 96 # Try to handle quoted tokens correctly
97 97 quotes = _quotesre.match(token)
98 98 if quotes:
99 99 token = quotes.group(1)
100 100 lout.append(token)
101 101 return lout
102 102
103 103 #****************************************************************************
104 104 # Exceptions
105 105 class Error(Exception):
106 106 """Base class for exceptions in this module."""
107 107 pass
108 108
109 109 #----------------------------------------------------------------------------
110 110 class IOStream:
111 111 def __init__(self,stream,fallback):
112 112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
113 113 stream = fallback
114 114 self.stream = stream
115 115 self._swrite = stream.write
116 116 self.flush = stream.flush
117 117
118 118 def write(self,data):
119 119 try:
120 120 self._swrite(data)
121 121 except:
122 122 try:
123 123 # print handles some unicode issues which may trip a plain
124 124 # write() call. Attempt to emulate write() by using a
125 125 # trailing comma
126 126 print >> self.stream, data,
127 127 except:
128 128 # if we get here, something is seriously broken.
129 129 print >> sys.stderr, \
130 130 'ERROR - failed to write data to stream:', stream
131 131
132 132 class IOTerm:
133 133 """ Term holds the file or file-like objects for handling I/O operations.
134 134
135 135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
136 136 Windows they can can replaced to allow editing the strings before they are
137 137 displayed."""
138 138
139 139 # In the future, having IPython channel all its I/O operations through
140 140 # this class will make it easier to embed it into other environments which
141 141 # are not a normal terminal (such as a GUI-based shell)
142 142 def __init__(self,cin=None,cout=None,cerr=None):
143 143 self.cin = IOStream(cin,sys.stdin)
144 144 self.cout = IOStream(cout,sys.stdout)
145 145 self.cerr = IOStream(cerr,sys.stderr)
146 146
147 147 # Global variable to be used for all I/O
148 148 Term = IOTerm()
149 149
150 150 # Windows-specific code to load Gary Bishop's readline and configure it
151 151 # automatically for the users
152 152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
153 153 # windows. Cygwin returns 'cygwin' for sys.platform.
154 154 if os.name == 'nt':
155 155 try:
156 156 import readline
157 157 except ImportError:
158 158 pass
159 159 else:
160 160 try:
161 161 _out = readline.GetOutputFile()
162 162 except AttributeError:
163 163 pass
164 164 else:
165 165 # Remake Term to use the readline i/o facilities
166 166 Term = IOTerm(cout=_out,cerr=_out)
167 167 del _out
168 168
169 169 #****************************************************************************
170 170 # Generic warning/error printer, used by everything else
171 171 def warn(msg,level=2,exit_val=1):
172 172 """Standard warning printer. Gives formatting consistency.
173 173
174 174 Output is sent to Term.cerr (sys.stderr by default).
175 175
176 176 Options:
177 177
178 178 -level(2): allows finer control:
179 179 0 -> Do nothing, dummy function.
180 180 1 -> Print message.
181 181 2 -> Print 'WARNING:' + message. (Default level).
182 182 3 -> Print 'ERROR:' + message.
183 183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
184 184
185 185 -exit_val (1): exit value returned by sys.exit() for a level 4
186 186 warning. Ignored for all other levels."""
187 187
188 188 if level>0:
189 189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
190 190 print >> Term.cerr, '%s%s' % (header[level],msg)
191 191 if level == 4:
192 192 print >> Term.cerr,'Exiting.\n'
193 193 sys.exit(exit_val)
194 194
195 195 def info(msg):
196 196 """Equivalent to warn(msg,level=1)."""
197 197
198 198 warn(msg,level=1)
199 199
200 200 def error(msg):
201 201 """Equivalent to warn(msg,level=3)."""
202 202
203 203 warn(msg,level=3)
204 204
205 205 def fatal(msg,exit_val=1):
206 206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
207 207
208 208 warn(msg,exit_val=exit_val,level=4)
209 209
210
211 # useful for debugging
212 def debugp(expr):
213 """Print the value of an expression from the caller's frame.
214
215 Takes an expression, evaluates it in the caller's frame and prints both
216 the given expression and the resulting value. The input must be of a form
217 suitable for eval()."""
218
219 cf = sys._getframe(1)
220 print '[DBG] %s -> %r' % (expr,eval(expr,cf.f_globals,cf.f_locals))
221
210 222 #----------------------------------------------------------------------------
211 223 StringTypes = types.StringTypes
212 224
213 225 # Basic timing functionality
214 226
215 227 # If possible (Unix), use the resource module instead of time.clock()
216 228 try:
217 229 import resource
218 230 def clock():
219 231 """clock() -> floating point number
220 232
221 233 Return the CPU time in seconds (user time only, system time is
222 234 ignored) since the start of the process. This is done via a call to
223 235 resource.getrusage, so it avoids the wraparound problems in
224 236 time.clock()."""
225 237
226 238 return resource.getrusage(resource.RUSAGE_SELF)[0]
227 239
228 240 def clock2():
229 241 """clock2() -> (t_user,t_system)
230 242
231 243 Similar to clock(), but return a tuple of user/system times."""
232 244 return resource.getrusage(resource.RUSAGE_SELF)[:2]
233 245
234 246 except ImportError:
235 247 clock = time.clock
236 248 def clock2():
237 249 """Under windows, system CPU time can't be measured.
238 250
239 251 This just returns clock() and zero."""
240 252 return time.clock(),0.0
241 253
242 254 def timings_out(reps,func,*args,**kw):
243 255 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
244 256
245 257 Execute a function reps times, return a tuple with the elapsed total
246 258 CPU time in seconds, the time per call and the function's output.
247 259
248 260 Under Unix, the return value is the sum of user+system time consumed by
249 261 the process, computed via the resource module. This prevents problems
250 262 related to the wraparound effect which the time.clock() function has.
251 263
252 264 Under Windows the return value is in wall clock seconds. See the
253 265 documentation for the time module for more details."""
254 266
255 267 reps = int(reps)
256 268 assert reps >=1, 'reps must be >= 1'
257 269 if reps==1:
258 270 start = clock()
259 271 out = func(*args,**kw)
260 272 tot_time = clock()-start
261 273 else:
262 274 rng = xrange(reps-1) # the last time is executed separately to store output
263 275 start = clock()
264 276 for dummy in rng: func(*args,**kw)
265 277 out = func(*args,**kw) # one last time
266 278 tot_time = clock()-start
267 279 av_time = tot_time / reps
268 280 return tot_time,av_time,out
269 281
270 282 def timings(reps,func,*args,**kw):
271 283 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
272 284
273 285 Execute a function reps times, return a tuple with the elapsed total CPU
274 286 time in seconds and the time per call. These are just the first two values
275 287 in timings_out()."""
276 288
277 289 return timings_out(reps,func,*args,**kw)[0:2]
278 290
279 291 def timing(func,*args,**kw):
280 292 """timing(func,*args,**kw) -> t_total
281 293
282 294 Execute a function once, return the elapsed total CPU time in
283 295 seconds. This is just the first value in timings_out()."""
284 296
285 297 return timings_out(1,func,*args,**kw)[0]
286 298
287 299 #****************************************************************************
288 300 # file and system
289 301
290 302 def system(cmd,verbose=0,debug=0,header=''):
291 303 """Execute a system command, return its exit status.
292 304
293 305 Options:
294 306
295 307 - verbose (0): print the command to be executed.
296 308
297 309 - debug (0): only print, do not actually execute.
298 310
299 311 - header (''): Header to print on screen prior to the executed command (it
300 312 is only prepended to the command, no newlines are added).
301 313
302 314 Note: a stateful version of this function is available through the
303 315 SystemExec class."""
304 316
305 317 stat = 0
306 318 if verbose or debug: print header+cmd
307 319 sys.stdout.flush()
308 320 if not debug: stat = os.system(cmd)
309 321 return stat
310 322
311 323 # This function is used by ipython in a lot of places to make system calls.
312 324 # We need it to be slightly different under win32, due to the vagaries of
313 325 # 'network shares'. A win32 override is below.
314 326
315 327 def shell(cmd,verbose=0,debug=0,header=''):
316 328 """Execute a command in the system shell, always return None.
317 329
318 330 Options:
319 331
320 332 - verbose (0): print the command to be executed.
321 333
322 334 - debug (0): only print, do not actually execute.
323 335
324 336 - header (''): Header to print on screen prior to the executed command (it
325 337 is only prepended to the command, no newlines are added).
326 338
327 339 Note: this is similar to genutils.system(), but it returns None so it can
328 340 be conveniently used in interactive loops without getting the return value
329 341 (typically 0) printed many times."""
330 342
331 343 stat = 0
332 344 if verbose or debug: print header+cmd
333 345 # flush stdout so we don't mangle python's buffering
334 346 sys.stdout.flush()
335 347 if not debug:
336 348 os.system(cmd)
337 349
338 350 # override shell() for win32 to deal with network shares
339 351 if os.name in ('nt','dos'):
340 352
341 353 shell_ori = shell
342 354
343 355 def shell(cmd,verbose=0,debug=0,header=''):
344 356 if os.getcwd().startswith(r"\\"):
345 357 path = os.getcwd()
346 358 # change to c drive (cannot be on UNC-share when issuing os.system,
347 359 # as cmd.exe cannot handle UNC addresses)
348 360 os.chdir("c:")
349 361 # issue pushd to the UNC-share and then run the command
350 362 try:
351 363 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
352 364 finally:
353 365 os.chdir(path)
354 366 else:
355 367 shell_ori(cmd,verbose,debug,header)
356 368
357 369 shell.__doc__ = shell_ori.__doc__
358 370
359 371 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
360 372 """Dummy substitute for perl's backquotes.
361 373
362 374 Executes a command and returns the output.
363 375
364 376 Accepts the same arguments as system(), plus:
365 377
366 378 - split(0): if true, the output is returned as a list split on newlines.
367 379
368 380 Note: a stateful version of this function is available through the
369 381 SystemExec class."""
370 382
371 383 if verbose or debug: print header+cmd
372 384 if not debug:
373 385 output = commands.getoutput(cmd)
374 386 if split:
375 387 return output.split('\n')
376 388 else:
377 389 return output
378 390
379 391 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
380 392 """Return (standard output,standard error) of executing cmd in a shell.
381 393
382 394 Accepts the same arguments as system(), plus:
383 395
384 396 - split(0): if true, each of stdout/err is returned as a list split on
385 397 newlines.
386 398
387 399 Note: a stateful version of this function is available through the
388 400 SystemExec class."""
389 401
390 402 if verbose or debug: print header+cmd
391 403 if not cmd:
392 404 if split:
393 405 return [],[]
394 406 else:
395 407 return '',''
396 408 if not debug:
397 409 pin,pout,perr = os.popen3(cmd)
398 410 tout = pout.read().rstrip()
399 411 terr = perr.read().rstrip()
400 412 pin.close()
401 413 pout.close()
402 414 perr.close()
403 415 if split:
404 416 return tout.split('\n'),terr.split('\n')
405 417 else:
406 418 return tout,terr
407 419
408 420 # for compatibility with older naming conventions
409 421 xsys = system
410 422 bq = getoutput
411 423
412 424 class SystemExec:
413 425 """Access the system and getoutput functions through a stateful interface.
414 426
415 427 Note: here we refer to the system and getoutput functions from this
416 428 library, not the ones from the standard python library.
417 429
418 430 This class offers the system and getoutput functions as methods, but the
419 431 verbose, debug and header parameters can be set for the instance (at
420 432 creation time or later) so that they don't need to be specified on each
421 433 call.
422 434
423 435 For efficiency reasons, there's no way to override the parameters on a
424 436 per-call basis other than by setting instance attributes. If you need
425 437 local overrides, it's best to directly call system() or getoutput().
426 438
427 439 The following names are provided as alternate options:
428 440 - xsys: alias to system
429 441 - bq: alias to getoutput
430 442
431 443 An instance can then be created as:
432 444 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
433 445
434 446 And used as:
435 447 >>> sysexec.xsys('pwd')
436 448 >>> dirlist = sysexec.bq('ls -l')
437 449 """
438 450
439 451 def __init__(self,verbose=0,debug=0,header='',split=0):
440 452 """Specify the instance's values for verbose, debug and header."""
441 453 setattr_list(self,'verbose debug header split')
442 454
443 455 def system(self,cmd):
444 456 """Stateful interface to system(), with the same keyword parameters."""
445 457
446 458 system(cmd,self.verbose,self.debug,self.header)
447 459
448 460 def shell(self,cmd):
449 461 """Stateful interface to shell(), with the same keyword parameters."""
450 462
451 463 shell(cmd,self.verbose,self.debug,self.header)
452 464
453 465 xsys = system # alias
454 466
455 467 def getoutput(self,cmd):
456 468 """Stateful interface to getoutput()."""
457 469
458 470 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
459 471
460 472 def getoutputerror(self,cmd):
461 473 """Stateful interface to getoutputerror()."""
462 474
463 475 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
464 476
465 477 bq = getoutput # alias
466 478
467 479 #-----------------------------------------------------------------------------
468 480 def mutex_opts(dict,ex_op):
469 481 """Check for presence of mutually exclusive keys in a dict.
470 482
471 483 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
472 484 for op1,op2 in ex_op:
473 485 if op1 in dict and op2 in dict:
474 486 raise ValueError,'\n*** ERROR in Arguments *** '\
475 487 'Options '+op1+' and '+op2+' are mutually exclusive.'
476 488
477 489 #-----------------------------------------------------------------------------
478 490 def get_py_filename(name):
479 491 """Return a valid python filename in the current directory.
480 492
481 493 If the given name is not a file, it adds '.py' and searches again.
482 494 Raises IOError with an informative message if the file isn't found."""
483 495
484 496 name = os.path.expanduser(name)
485 497 if not os.path.isfile(name) and not name.endswith('.py'):
486 498 name += '.py'
487 499 if os.path.isfile(name):
488 500 return name
489 501 else:
490 502 raise IOError,'File `%s` not found.' % name
491 503
492 504 #-----------------------------------------------------------------------------
493 505 def filefind(fname,alt_dirs = None):
494 506 """Return the given filename either in the current directory, if it
495 507 exists, or in a specified list of directories.
496 508
497 509 ~ expansion is done on all file and directory names.
498 510
499 511 Upon an unsuccessful search, raise an IOError exception."""
500 512
501 513 if alt_dirs is None:
502 514 try:
503 515 alt_dirs = get_home_dir()
504 516 except HomeDirError:
505 517 alt_dirs = os.getcwd()
506 518 search = [fname] + list_strings(alt_dirs)
507 519 search = map(os.path.expanduser,search)
508 520 #print 'search list for',fname,'list:',search # dbg
509 521 fname = search[0]
510 522 if os.path.isfile(fname):
511 523 return fname
512 524 for direc in search[1:]:
513 525 testname = os.path.join(direc,fname)
514 526 #print 'testname',testname # dbg
515 527 if os.path.isfile(testname):
516 528 return testname
517 529 raise IOError,'File' + `fname` + \
518 530 ' not found in current or supplied directories:' + `alt_dirs`
519 531
520 532 #----------------------------------------------------------------------------
521 533 def file_read(filename):
522 534 """Read a file and close it. Returns the file source."""
523 535 fobj=open(filename,'r');
524 536 source = fobj.read();
525 537 fobj.close()
526 538 return source
527 539
528 540 #----------------------------------------------------------------------------
529 541 def target_outdated(target,deps):
530 542 """Determine whether a target is out of date.
531 543
532 544 target_outdated(target,deps) -> 1/0
533 545
534 546 deps: list of filenames which MUST exist.
535 547 target: single filename which may or may not exist.
536 548
537 549 If target doesn't exist or is older than any file listed in deps, return
538 550 true, otherwise return false.
539 551 """
540 552 try:
541 553 target_time = os.path.getmtime(target)
542 554 except os.error:
543 555 return 1
544 556 for dep in deps:
545 557 dep_time = os.path.getmtime(dep)
546 558 if dep_time > target_time:
547 559 #print "For target",target,"Dep failed:",dep # dbg
548 560 #print "times (dep,tar):",dep_time,target_time # dbg
549 561 return 1
550 562 return 0
551 563
552 564 #-----------------------------------------------------------------------------
553 565 def target_update(target,deps,cmd):
554 566 """Update a target with a given command given a list of dependencies.
555 567
556 568 target_update(target,deps,cmd) -> runs cmd if target is outdated.
557 569
558 570 This is just a wrapper around target_outdated() which calls the given
559 571 command if target is outdated."""
560 572
561 573 if target_outdated(target,deps):
562 574 xsys(cmd)
563 575
564 576 #----------------------------------------------------------------------------
565 577 def unquote_ends(istr):
566 578 """Remove a single pair of quotes from the endpoints of a string."""
567 579
568 580 if not istr:
569 581 return istr
570 582 if (istr[0]=="'" and istr[-1]=="'") or \
571 583 (istr[0]=='"' and istr[-1]=='"'):
572 584 return istr[1:-1]
573 585 else:
574 586 return istr
575 587
576 588 #----------------------------------------------------------------------------
577 589 def process_cmdline(argv,names=[],defaults={},usage=''):
578 590 """ Process command-line options and arguments.
579 591
580 592 Arguments:
581 593
582 594 - argv: list of arguments, typically sys.argv.
583 595
584 596 - names: list of option names. See DPyGetOpt docs for details on options
585 597 syntax.
586 598
587 599 - defaults: dict of default values.
588 600
589 601 - usage: optional usage notice to print if a wrong argument is passed.
590 602
591 603 Return a dict of options and a list of free arguments."""
592 604
593 605 getopt = DPyGetOpt.DPyGetOpt()
594 606 getopt.setIgnoreCase(0)
595 607 getopt.parseConfiguration(names)
596 608
597 609 try:
598 610 getopt.processArguments(argv)
599 611 except:
600 612 print usage
601 613 warn(`sys.exc_value`,level=4)
602 614
603 615 defaults.update(getopt.optionValues)
604 616 args = getopt.freeValues
605 617
606 618 return defaults,args
607 619
608 620 #----------------------------------------------------------------------------
609 621 def optstr2types(ostr):
610 622 """Convert a string of option names to a dict of type mappings.
611 623
612 624 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
613 625
614 626 This is used to get the types of all the options in a string formatted
615 627 with the conventions of DPyGetOpt. The 'type' None is used for options
616 628 which are strings (they need no further conversion). This function's main
617 629 use is to get a typemap for use with read_dict().
618 630 """
619 631
620 632 typeconv = {None:'',int:'',float:''}
621 633 typemap = {'s':None,'i':int,'f':float}
622 634 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
623 635
624 636 for w in ostr.split():
625 637 oname,alias,otype = opt_re.match(w).groups()
626 638 if otype == '' or alias == '!': # simple switches are integers too
627 639 otype = 'i'
628 640 typeconv[typemap[otype]] += oname + ' '
629 641 return typeconv
630 642
631 643 #----------------------------------------------------------------------------
632 644 def read_dict(filename,type_conv=None,**opt):
633 645
634 646 """Read a dictionary of key=value pairs from an input file, optionally
635 647 performing conversions on the resulting values.
636 648
637 649 read_dict(filename,type_conv,**opt) -> dict
638 650
639 651 Only one value per line is accepted, the format should be
640 652 # optional comments are ignored
641 653 key value\n
642 654
643 655 Args:
644 656
645 657 - type_conv: A dictionary specifying which keys need to be converted to
646 658 which types. By default all keys are read as strings. This dictionary
647 659 should have as its keys valid conversion functions for strings
648 660 (int,long,float,complex, or your own). The value for each key
649 661 (converter) should be a whitespace separated string containing the names
650 662 of all the entries in the file to be converted using that function. For
651 663 keys to be left alone, use None as the conversion function (only needed
652 664 with purge=1, see below).
653 665
654 666 - opt: dictionary with extra options as below (default in parens)
655 667
656 668 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
657 669 of the dictionary to be returned. If purge is going to be used, the
658 670 set of keys to be left as strings also has to be explicitly specified
659 671 using the (non-existent) conversion function None.
660 672
661 673 fs(None): field separator. This is the key/value separator to be used
662 674 when parsing the file. The None default means any whitespace [behavior
663 675 of string.split()].
664 676
665 677 strip(0): if 1, strip string values of leading/trailinig whitespace.
666 678
667 679 warn(1): warning level if requested keys are not found in file.
668 680 - 0: silently ignore.
669 681 - 1: inform but proceed.
670 682 - 2: raise KeyError exception.
671 683
672 684 no_empty(0): if 1, remove keys with whitespace strings as a value.
673 685
674 686 unique([]): list of keys (or space separated string) which can't be
675 687 repeated. If one such key is found in the file, each new instance
676 688 overwrites the previous one. For keys not listed here, the behavior is
677 689 to make a list of all appearances.
678 690
679 691 Example:
680 692 If the input file test.ini has:
681 693 i 3
682 694 x 4.5
683 695 y 5.5
684 696 s hi ho
685 697 Then:
686 698
687 699 >>> type_conv={int:'i',float:'x',None:'s'}
688 700 >>> read_dict('test.ini')
689 701 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
690 702 >>> read_dict('test.ini',type_conv)
691 703 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
692 704 >>> read_dict('test.ini',type_conv,purge=1)
693 705 {'i': 3, 's': 'hi ho', 'x': 4.5}
694 706 """
695 707
696 708 # starting config
697 709 opt.setdefault('purge',0)
698 710 opt.setdefault('fs',None) # field sep defaults to any whitespace
699 711 opt.setdefault('strip',0)
700 712 opt.setdefault('warn',1)
701 713 opt.setdefault('no_empty',0)
702 714 opt.setdefault('unique','')
703 715 if type(opt['unique']) in StringTypes:
704 716 unique_keys = qw(opt['unique'])
705 717 elif type(opt['unique']) in (types.TupleType,types.ListType):
706 718 unique_keys = opt['unique']
707 719 else:
708 720 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
709 721
710 722 dict = {}
711 723 # first read in table of values as strings
712 724 file = open(filename,'r')
713 725 for line in file.readlines():
714 726 line = line.strip()
715 727 if len(line) and line[0]=='#': continue
716 728 if len(line)>0:
717 729 lsplit = line.split(opt['fs'],1)
718 730 try:
719 731 key,val = lsplit
720 732 except ValueError:
721 733 key,val = lsplit[0],''
722 734 key = key.strip()
723 735 if opt['strip']: val = val.strip()
724 736 if val == "''" or val == '""': val = ''
725 737 if opt['no_empty'] and (val=='' or val.isspace()):
726 738 continue
727 739 # if a key is found more than once in the file, build a list
728 740 # unless it's in the 'unique' list. In that case, last found in file
729 741 # takes precedence. User beware.
730 742 try:
731 743 if dict[key] and key in unique_keys:
732 744 dict[key] = val
733 745 elif type(dict[key]) is types.ListType:
734 746 dict[key].append(val)
735 747 else:
736 748 dict[key] = [dict[key],val]
737 749 except KeyError:
738 750 dict[key] = val
739 751 # purge if requested
740 752 if opt['purge']:
741 753 accepted_keys = qwflat(type_conv.values())
742 754 for key in dict.keys():
743 755 if key in accepted_keys: continue
744 756 del(dict[key])
745 757 # now convert if requested
746 758 if type_conv==None: return dict
747 759 conversions = type_conv.keys()
748 760 try: conversions.remove(None)
749 761 except: pass
750 762 for convert in conversions:
751 763 for val in qw(type_conv[convert]):
752 764 try:
753 765 dict[val] = convert(dict[val])
754 766 except KeyError,e:
755 767 if opt['warn'] == 0:
756 768 pass
757 769 elif opt['warn'] == 1:
758 770 print >>sys.stderr, 'Warning: key',val,\
759 771 'not found in file',filename
760 772 elif opt['warn'] == 2:
761 773 raise KeyError,e
762 774 else:
763 775 raise ValueError,'Warning level must be 0,1 or 2'
764 776
765 777 return dict
766 778
767 779 #----------------------------------------------------------------------------
768 780 def flag_calls(func):
769 781 """Wrap a function to detect and flag when it gets called.
770 782
771 783 This is a decorator which takes a function and wraps it in a function with
772 784 a 'called' attribute. wrapper.called is initialized to False.
773 785
774 786 The wrapper.called attribute is set to False right before each call to the
775 787 wrapped function, so if the call fails it remains False. After the call
776 788 completes, wrapper.called is set to True and the output is returned.
777 789
778 790 Testing for truth in wrapper.called allows you to determine if a call to
779 791 func() was attempted and succeeded."""
780 792
781 793 def wrapper(*args,**kw):
782 794 wrapper.called = False
783 795 out = func(*args,**kw)
784 796 wrapper.called = True
785 797 return out
786 798
787 799 wrapper.called = False
788 800 wrapper.__doc__ = func.__doc__
789 801 return wrapper
790 802
791 803 #----------------------------------------------------------------------------
792 804 class HomeDirError(Error):
793 805 pass
794 806
795 807 def get_home_dir():
796 808 """Return the closest possible equivalent to a 'home' directory.
797 809
798 810 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
799 811
800 812 Currently only Posix and NT are implemented, a HomeDirError exception is
801 813 raised for all other OSes. """
802 814
803 815 isdir = os.path.isdir
804 816 env = os.environ
805 817 try:
806 818 homedir = env['HOME']
807 819 if not isdir(homedir):
808 820 # in case a user stuck some string which does NOT resolve to a
809 821 # valid path, it's as good as if we hadn't foud it
810 822 raise KeyError
811 823 return homedir
812 824 except KeyError:
813 825 if os.name == 'posix':
814 826 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
815 827 elif os.name == 'nt':
816 828 # For some strange reason, win9x returns 'nt' for os.name.
817 829 try:
818 830 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
819 831 if not isdir(homedir):
820 832 homedir = os.path.join(env['USERPROFILE'])
821 833 if not isdir(homedir):
822 834 raise HomeDirError
823 835 return homedir
824 836 except:
825 837 try:
826 838 # Use the registry to get the 'My Documents' folder.
827 839 import _winreg as wreg
828 840 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
829 841 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
830 842 homedir = wreg.QueryValueEx(key,'Personal')[0]
831 843 key.Close()
832 844 if not isdir(homedir):
833 845 e = ('Invalid "Personal" folder registry key '
834 846 'typically "My Documents".\n'
835 847 'Value: %s\n'
836 848 'This is not a valid directory on your system.' %
837 849 homedir)
838 850 raise HomeDirError(e)
839 851 return homedir
840 852 except HomeDirError:
841 853 raise
842 854 except:
843 855 return 'C:\\'
844 856 elif os.name == 'dos':
845 857 # Desperate, may do absurd things in classic MacOS. May work under DOS.
846 858 return 'C:\\'
847 859 else:
848 860 raise HomeDirError,'support for your operating system not implemented.'
849 861
850 862 #****************************************************************************
851 863 # strings and text
852 864
853 865 class LSString(str):
854 866 """String derivative with a special access attributes.
855 867
856 868 These are normal strings, but with the special attributes:
857 869
858 870 .l (or .list) : value as list (split on newlines).
859 871 .n (or .nlstr): original value (the string itself).
860 872 .s (or .spstr): value as whitespace-separated string.
861 873
862 874 Any values which require transformations are computed only once and
863 875 cached.
864 876
865 877 Such strings are very useful to efficiently interact with the shell, which
866 878 typically only understands whitespace-separated options for commands."""
867 879
868 880 def get_list(self):
869 881 try:
870 882 return self.__list
871 883 except AttributeError:
872 884 self.__list = self.split('\n')
873 885 return self.__list
874 886
875 887 l = list = property(get_list)
876 888
877 889 def get_spstr(self):
878 890 try:
879 891 return self.__spstr
880 892 except AttributeError:
881 893 self.__spstr = self.replace('\n',' ')
882 894 return self.__spstr
883 895
884 896 s = spstr = property(get_spstr)
885 897
886 898 def get_nlstr(self):
887 899 return self
888 900
889 901 n = nlstr = property(get_nlstr)
890 902
891 903 #----------------------------------------------------------------------------
892 904 class SList(list):
893 905 """List derivative with a special access attributes.
894 906
895 907 These are normal lists, but with the special attributes:
896 908
897 909 .l (or .list) : value as list (the list itself).
898 910 .n (or .nlstr): value as a string, joined on newlines.
899 911 .s (or .spstr): value as a string, joined on spaces.
900 912
901 913 Any values which require transformations are computed only once and
902 914 cached."""
903 915
904 916 def get_list(self):
905 917 return self
906 918
907 919 l = list = property(get_list)
908 920
909 921 def get_spstr(self):
910 922 try:
911 923 return self.__spstr
912 924 except AttributeError:
913 925 self.__spstr = ' '.join(self)
914 926 return self.__spstr
915 927
916 928 s = spstr = property(get_spstr)
917 929
918 930 def get_nlstr(self):
919 931 try:
920 932 return self.__nlstr
921 933 except AttributeError:
922 934 self.__nlstr = '\n'.join(self)
923 935 return self.__nlstr
924 936
925 937 n = nlstr = property(get_nlstr)
926 938
927 939 #----------------------------------------------------------------------------
928 940 # This can be replaced with an isspace() call once we drop 2.2 compatibility
929 941 _isspace_match = re.compile(r'^\s+$').match
930 942 def isspace(s):
931 943 return bool(_isspace_match(s))
932 944
933 945 #----------------------------------------------------------------------------
934 946 def esc_quotes(strng):
935 947 """Return the input string with single and double quotes escaped out"""
936 948
937 949 return strng.replace('"','\\"').replace("'","\\'")
938 950
939 951 #----------------------------------------------------------------------------
940 952 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
941 953 """Take multiple lines of input.
942 954
943 955 A list with each line of input as a separate element is returned when a
944 956 termination string is entered (defaults to a single '.'). Input can also
945 957 terminate via EOF (^D in Unix, ^Z-RET in Windows).
946 958
947 959 Lines of input which end in \\ are joined into single entries (and a
948 960 secondary continuation prompt is issued as long as the user terminates
949 961 lines with \\). This allows entering very long strings which are still
950 962 meant to be treated as single entities.
951 963 """
952 964
953 965 try:
954 966 if header:
955 967 header += '\n'
956 968 lines = [raw_input(header + ps1)]
957 969 except EOFError:
958 970 return []
959 971 terminate = [terminate_str]
960 972 try:
961 973 while lines[-1:] != terminate:
962 974 new_line = raw_input(ps1)
963 975 while new_line.endswith('\\'):
964 976 new_line = new_line[:-1] + raw_input(ps2)
965 977 lines.append(new_line)
966 978
967 979 return lines[:-1] # don't return the termination command
968 980 except EOFError:
969 981 print
970 982 return lines
971 983
972 984 #----------------------------------------------------------------------------
973 985 def raw_input_ext(prompt='', ps2='... '):
974 986 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
975 987
976 988 line = raw_input(prompt)
977 989 while line.endswith('\\'):
978 990 line = line[:-1] + raw_input(ps2)
979 991 return line
980 992
981 993 #----------------------------------------------------------------------------
982 994 def ask_yes_no(prompt,default=None):
983 995 """Asks a question and returns an integer 1/0 (y/n) answer.
984 996
985 997 If default is given (one of 'y','n'), it is used if the user input is
986 998 empty. Otherwise the question is repeated until an answer is given.
987 999 If EOF occurs 20 times consecutively, the default answer is assumed,
988 1000 or if there is no default, an exception is raised to prevent infinite
989 1001 loops.
990 1002
991 1003 Valid answers are: y/yes/n/no (match is not case sensitive)."""
992 1004
993 1005 answers = {'y':True,'n':False,'yes':True,'no':False}
994 1006 ans = None
995 1007 eofs, max_eofs = 0, 20
996 1008 while ans not in answers.keys():
997 1009 try:
998 1010 ans = raw_input(prompt+' ').lower()
999 1011 if not ans: # response was an empty string
1000 1012 ans = default
1001 1013 eofs = 0
1002 1014 except (EOFError,KeyboardInterrupt):
1003 1015 eofs = eofs + 1
1004 1016 if eofs >= max_eofs:
1005 1017 if default in answers.keys():
1006 1018 ans = default
1007 1019 else:
1008 1020 raise
1009 1021
1010 1022 return answers[ans]
1011 1023
1012 1024 #----------------------------------------------------------------------------
1013 1025 def marquee(txt='',width=78,mark='*'):
1014 1026 """Return the input string centered in a 'marquee'."""
1015 1027 if not txt:
1016 1028 return (mark*width)[:width]
1017 1029 nmark = (width-len(txt)-2)/len(mark)/2
1018 1030 if nmark < 0: nmark =0
1019 1031 marks = mark*nmark
1020 1032 return '%s %s %s' % (marks,txt,marks)
1021 1033
1022 1034 #----------------------------------------------------------------------------
1023 1035 class EvalDict:
1024 1036 """
1025 1037 Emulate a dict which evaluates its contents in the caller's frame.
1026 1038
1027 1039 Usage:
1028 1040 >>>number = 19
1029 1041 >>>text = "python"
1030 1042 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1031 1043 """
1032 1044
1033 1045 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1034 1046 # modified (shorter) version of:
1035 1047 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1036 1048 # Skip Montanaro (skip@pobox.com).
1037 1049
1038 1050 def __getitem__(self, name):
1039 1051 frame = sys._getframe(1)
1040 1052 return eval(name, frame.f_globals, frame.f_locals)
1041 1053
1042 1054 EvalString = EvalDict # for backwards compatibility
1043 1055 #----------------------------------------------------------------------------
1044 1056 def qw(words,flat=0,sep=None,maxsplit=-1):
1045 1057 """Similar to Perl's qw() operator, but with some more options.
1046 1058
1047 1059 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1048 1060
1049 1061 words can also be a list itself, and with flat=1, the output will be
1050 1062 recursively flattened. Examples:
1051 1063
1052 1064 >>> qw('1 2')
1053 1065 ['1', '2']
1054 1066 >>> qw(['a b','1 2',['m n','p q']])
1055 1067 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1056 1068 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1057 1069 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1058 1070
1059 1071 if type(words) in StringTypes:
1060 1072 return [word.strip() for word in words.split(sep,maxsplit)
1061 1073 if word and not word.isspace() ]
1062 1074 if flat:
1063 1075 return flatten(map(qw,words,[1]*len(words)))
1064 1076 return map(qw,words)
1065 1077
1066 1078 #----------------------------------------------------------------------------
1067 1079 def qwflat(words,sep=None,maxsplit=-1):
1068 1080 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1069 1081 return qw(words,1,sep,maxsplit)
1070 1082
1071 1083 #----------------------------------------------------------------------------
1072 1084 def qw_lol(indata):
1073 1085 """qw_lol('a b') -> [['a','b']],
1074 1086 otherwise it's just a call to qw().
1075 1087
1076 1088 We need this to make sure the modules_some keys *always* end up as a
1077 1089 list of lists."""
1078 1090
1079 1091 if type(indata) in StringTypes:
1080 1092 return [qw(indata)]
1081 1093 else:
1082 1094 return qw(indata)
1083 1095
1084 1096 #-----------------------------------------------------------------------------
1085 1097 def list_strings(arg):
1086 1098 """Always return a list of strings, given a string or list of strings
1087 1099 as input."""
1088 1100
1089 1101 if type(arg) in StringTypes: return [arg]
1090 1102 else: return arg
1091 1103
1092 1104 #----------------------------------------------------------------------------
1093 1105 def grep(pat,list,case=1):
1094 1106 """Simple minded grep-like function.
1095 1107 grep(pat,list) returns occurrences of pat in list, None on failure.
1096 1108
1097 1109 It only does simple string matching, with no support for regexps. Use the
1098 1110 option case=0 for case-insensitive matching."""
1099 1111
1100 1112 # This is pretty crude. At least it should implement copying only references
1101 1113 # to the original data in case it's big. Now it copies the data for output.
1102 1114 out=[]
1103 1115 if case:
1104 1116 for term in list:
1105 1117 if term.find(pat)>-1: out.append(term)
1106 1118 else:
1107 1119 lpat=pat.lower()
1108 1120 for term in list:
1109 1121 if term.lower().find(lpat)>-1: out.append(term)
1110 1122
1111 1123 if len(out): return out
1112 1124 else: return None
1113 1125
1114 1126 #----------------------------------------------------------------------------
1115 1127 def dgrep(pat,*opts):
1116 1128 """Return grep() on dir()+dir(__builtins__).
1117 1129
1118 1130 A very common use of grep() when working interactively."""
1119 1131
1120 1132 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1121 1133
1122 1134 #----------------------------------------------------------------------------
1123 1135 def idgrep(pat):
1124 1136 """Case-insensitive dgrep()"""
1125 1137
1126 1138 return dgrep(pat,0)
1127 1139
1128 1140 #----------------------------------------------------------------------------
1129 1141 def igrep(pat,list):
1130 1142 """Synonym for case-insensitive grep."""
1131 1143
1132 1144 return grep(pat,list,case=0)
1133 1145
1134 1146 #----------------------------------------------------------------------------
1135 1147 def indent(str,nspaces=4,ntabs=0):
1136 1148 """Indent a string a given number of spaces or tabstops.
1137 1149
1138 1150 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1139 1151 """
1140 1152 if str is None:
1141 1153 return
1142 1154 ind = '\t'*ntabs+' '*nspaces
1143 1155 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1144 1156 if outstr.endswith(os.linesep+ind):
1145 1157 return outstr[:-len(ind)]
1146 1158 else:
1147 1159 return outstr
1148 1160
1149 1161 #-----------------------------------------------------------------------------
1150 1162 def native_line_ends(filename,backup=1):
1151 1163 """Convert (in-place) a file to line-ends native to the current OS.
1152 1164
1153 1165 If the optional backup argument is given as false, no backup of the
1154 1166 original file is left. """
1155 1167
1156 1168 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1157 1169
1158 1170 bak_filename = filename + backup_suffixes[os.name]
1159 1171
1160 1172 original = open(filename).read()
1161 1173 shutil.copy2(filename,bak_filename)
1162 1174 try:
1163 1175 new = open(filename,'wb')
1164 1176 new.write(os.linesep.join(original.splitlines()))
1165 1177 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1166 1178 new.close()
1167 1179 except:
1168 1180 os.rename(bak_filename,filename)
1169 1181 if not backup:
1170 1182 try:
1171 1183 os.remove(bak_filename)
1172 1184 except:
1173 1185 pass
1174 1186
1175 1187 #----------------------------------------------------------------------------
1176 1188 def get_pager_cmd(pager_cmd = None):
1177 1189 """Return a pager command.
1178 1190
1179 1191 Makes some attempts at finding an OS-correct one."""
1180 1192
1181 1193 if os.name == 'posix':
1182 1194 default_pager_cmd = 'less -r' # -r for color control sequences
1183 1195 elif os.name in ['nt','dos']:
1184 1196 default_pager_cmd = 'type'
1185 1197
1186 1198 if pager_cmd is None:
1187 1199 try:
1188 1200 pager_cmd = os.environ['PAGER']
1189 1201 except:
1190 1202 pager_cmd = default_pager_cmd
1191 1203 return pager_cmd
1192 1204
1193 1205 #-----------------------------------------------------------------------------
1194 1206 def get_pager_start(pager,start):
1195 1207 """Return the string for paging files with an offset.
1196 1208
1197 1209 This is the '+N' argument which less and more (under Unix) accept.
1198 1210 """
1199 1211
1200 1212 if pager in ['less','more']:
1201 1213 if start:
1202 1214 start_string = '+' + str(start)
1203 1215 else:
1204 1216 start_string = ''
1205 1217 else:
1206 1218 start_string = ''
1207 1219 return start_string
1208 1220
1209 1221 #----------------------------------------------------------------------------
1210 1222 if os.name == "nt":
1211 1223 import msvcrt
1212 1224 def page_more():
1213 1225 """ Smart pausing between pages
1214 1226
1215 1227 @return: True if need print more lines, False if quit
1216 1228 """
1217 1229 Term.cout.write('---Return to continue, q to quit--- ')
1218 1230 ans = msvcrt.getch()
1219 1231 if ans in ("q", "Q"):
1220 1232 result = False
1221 1233 else:
1222 1234 result = True
1223 1235 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1224 1236 return result
1225 1237 else:
1226 1238 def page_more():
1227 1239 ans = raw_input('---Return to continue, q to quit--- ')
1228 1240 if ans.lower().startswith('q'):
1229 1241 return False
1230 1242 else:
1231 1243 return True
1232 1244
1233 1245 esc_re = re.compile(r"(\x1b[^m]+m)")
1234 1246
1235 1247 def page_dumb(strng,start=0,screen_lines=25):
1236 1248 """Very dumb 'pager' in Python, for when nothing else works.
1237 1249
1238 1250 Only moves forward, same interface as page(), except for pager_cmd and
1239 1251 mode."""
1240 1252
1241 1253 out_ln = strng.splitlines()[start:]
1242 1254 screens = chop(out_ln,screen_lines-1)
1243 1255 if len(screens) == 1:
1244 1256 print >>Term.cout, os.linesep.join(screens[0])
1245 1257 else:
1246 1258 last_escape = ""
1247 1259 for scr in screens[0:-1]:
1248 1260 hunk = os.linesep.join(scr)
1249 1261 print >>Term.cout, last_escape + hunk
1250 1262 if not page_more():
1251 1263 return
1252 1264 esc_list = esc_re.findall(hunk)
1253 1265 if len(esc_list) > 0:
1254 1266 last_escape = esc_list[-1]
1255 1267 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1256 1268
1257 1269 #----------------------------------------------------------------------------
1258 1270 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1259 1271 """Print a string, piping through a pager after a certain length.
1260 1272
1261 1273 The screen_lines parameter specifies the number of *usable* lines of your
1262 1274 terminal screen (total lines minus lines you need to reserve to show other
1263 1275 information).
1264 1276
1265 1277 If you set screen_lines to a number <=0, page() will try to auto-determine
1266 1278 your screen size and will only use up to (screen_size+screen_lines) for
1267 1279 printing, paging after that. That is, if you want auto-detection but need
1268 1280 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1269 1281 auto-detection without any lines reserved simply use screen_lines = 0.
1270 1282
1271 1283 If a string won't fit in the allowed lines, it is sent through the
1272 1284 specified pager command. If none given, look for PAGER in the environment,
1273 1285 and ultimately default to less.
1274 1286
1275 1287 If no system pager works, the string is sent through a 'dumb pager'
1276 1288 written in python, very simplistic.
1277 1289 """
1278 1290
1279 1291 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1280 1292 TERM = os.environ.get('TERM','dumb')
1281 1293 if TERM in ['dumb','emacs'] and os.name != 'nt':
1282 1294 print strng
1283 1295 return
1284 1296 # chop off the topmost part of the string we don't want to see
1285 1297 str_lines = strng.split(os.linesep)[start:]
1286 1298 str_toprint = os.linesep.join(str_lines)
1287 1299 num_newlines = len(str_lines)
1288 1300 len_str = len(str_toprint)
1289 1301
1290 1302 # Dumb heuristics to guesstimate number of on-screen lines the string
1291 1303 # takes. Very basic, but good enough for docstrings in reasonable
1292 1304 # terminals. If someone later feels like refining it, it's not hard.
1293 1305 numlines = max(num_newlines,int(len_str/80)+1)
1294 1306
1295 1307 if os.name == "nt":
1296 1308 screen_lines_def = get_console_size(defaulty=25)[1]
1297 1309 else:
1298 1310 screen_lines_def = 25 # default value if we can't auto-determine
1299 1311
1300 1312 # auto-determine screen size
1301 1313 if screen_lines <= 0:
1302 1314 if TERM=='xterm':
1303 1315 try:
1304 1316 import curses
1305 1317 if hasattr(curses,'initscr'):
1306 1318 use_curses = 1
1307 1319 else:
1308 1320 use_curses = 0
1309 1321 except ImportError:
1310 1322 use_curses = 0
1311 1323 else:
1312 1324 # curses causes problems on many terminals other than xterm.
1313 1325 use_curses = 0
1314 1326 if use_curses:
1315 1327 scr = curses.initscr()
1316 1328 screen_lines_real,screen_cols = scr.getmaxyx()
1317 1329 curses.endwin()
1318 1330 screen_lines += screen_lines_real
1319 1331 #print '***Screen size:',screen_lines_real,'lines x',\
1320 1332 #screen_cols,'columns.' # dbg
1321 1333 else:
1322 1334 screen_lines += screen_lines_def
1323 1335
1324 1336 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1325 1337 if numlines <= screen_lines :
1326 1338 #print '*** normal print' # dbg
1327 1339 print >>Term.cout, str_toprint
1328 1340 else:
1329 1341 # Try to open pager and default to internal one if that fails.
1330 1342 # All failure modes are tagged as 'retval=1', to match the return
1331 1343 # value of a failed system command. If any intermediate attempt
1332 1344 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1333 1345 pager_cmd = get_pager_cmd(pager_cmd)
1334 1346 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1335 1347 if os.name == 'nt':
1336 1348 if pager_cmd.startswith('type'):
1337 1349 # The default WinXP 'type' command is failing on complex strings.
1338 1350 retval = 1
1339 1351 else:
1340 1352 tmpname = tempfile.mktemp('.txt')
1341 1353 tmpfile = file(tmpname,'wt')
1342 1354 tmpfile.write(strng)
1343 1355 tmpfile.close()
1344 1356 cmd = "%s < %s" % (pager_cmd,tmpname)
1345 1357 if os.system(cmd):
1346 1358 retval = 1
1347 1359 else:
1348 1360 retval = None
1349 1361 os.remove(tmpname)
1350 1362 else:
1351 1363 try:
1352 1364 retval = None
1353 1365 # if I use popen4, things hang. No idea why.
1354 1366 #pager,shell_out = os.popen4(pager_cmd)
1355 1367 pager = os.popen(pager_cmd,'w')
1356 1368 pager.write(strng)
1357 1369 pager.close()
1358 1370 retval = pager.close() # success returns None
1359 1371 except IOError,msg: # broken pipe when user quits
1360 1372 if msg.args == (32,'Broken pipe'):
1361 1373 retval = None
1362 1374 else:
1363 1375 retval = 1
1364 1376 except OSError:
1365 1377 # Other strange problems, sometimes seen in Win2k/cygwin
1366 1378 retval = 1
1367 1379 if retval is not None:
1368 1380 page_dumb(strng,screen_lines=screen_lines)
1369 1381
1370 1382 #----------------------------------------------------------------------------
1371 1383 def page_file(fname,start = 0, pager_cmd = None):
1372 1384 """Page a file, using an optional pager command and starting line.
1373 1385 """
1374 1386
1375 1387 pager_cmd = get_pager_cmd(pager_cmd)
1376 1388 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1377 1389
1378 1390 try:
1379 1391 if os.environ['TERM'] in ['emacs','dumb']:
1380 1392 raise EnvironmentError
1381 1393 xsys(pager_cmd + ' ' + fname)
1382 1394 except:
1383 1395 try:
1384 1396 if start > 0:
1385 1397 start -= 1
1386 1398 page(open(fname).read(),start)
1387 1399 except:
1388 1400 print 'Unable to show file',`fname`
1389 1401
1390 1402 #----------------------------------------------------------------------------
1391 1403 def snip_print(str,width = 75,print_full = 0,header = ''):
1392 1404 """Print a string snipping the midsection to fit in width.
1393 1405
1394 1406 print_full: mode control:
1395 1407 - 0: only snip long strings
1396 1408 - 1: send to page() directly.
1397 1409 - 2: snip long strings and ask for full length viewing with page()
1398 1410 Return 1 if snipping was necessary, 0 otherwise."""
1399 1411
1400 1412 if print_full == 1:
1401 1413 page(header+str)
1402 1414 return 0
1403 1415
1404 1416 print header,
1405 1417 if len(str) < width:
1406 1418 print str
1407 1419 snip = 0
1408 1420 else:
1409 1421 whalf = int((width -5)/2)
1410 1422 print str[:whalf] + ' <...> ' + str[-whalf:]
1411 1423 snip = 1
1412 1424 if snip and print_full == 2:
1413 1425 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1414 1426 page(str)
1415 1427 return snip
1416 1428
1417 1429 #****************************************************************************
1418 1430 # lists, dicts and structures
1419 1431
1420 1432 def belong(candidates,checklist):
1421 1433 """Check whether a list of items appear in a given list of options.
1422 1434
1423 1435 Returns a list of 1 and 0, one for each candidate given."""
1424 1436
1425 1437 return [x in checklist for x in candidates]
1426 1438
1427 1439 #----------------------------------------------------------------------------
1428 1440 def uniq_stable(elems):
1429 1441 """uniq_stable(elems) -> list
1430 1442
1431 1443 Return from an iterable, a list of all the unique elements in the input,
1432 1444 but maintaining the order in which they first appear.
1433 1445
1434 1446 A naive solution to this problem which just makes a dictionary with the
1435 1447 elements as keys fails to respect the stability condition, since
1436 1448 dictionaries are unsorted by nature.
1437 1449
1438 1450 Note: All elements in the input must be valid dictionary keys for this
1439 1451 routine to work, as it internally uses a dictionary for efficiency
1440 1452 reasons."""
1441 1453
1442 1454 unique = []
1443 1455 unique_dict = {}
1444 1456 for nn in elems:
1445 1457 if nn not in unique_dict:
1446 1458 unique.append(nn)
1447 1459 unique_dict[nn] = None
1448 1460 return unique
1449 1461
1450 1462 #----------------------------------------------------------------------------
1451 1463 class NLprinter:
1452 1464 """Print an arbitrarily nested list, indicating index numbers.
1453 1465
1454 1466 An instance of this class called nlprint is available and callable as a
1455 1467 function.
1456 1468
1457 1469 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1458 1470 and using 'sep' to separate the index from the value. """
1459 1471
1460 1472 def __init__(self):
1461 1473 self.depth = 0
1462 1474
1463 1475 def __call__(self,lst,pos='',**kw):
1464 1476 """Prints the nested list numbering levels."""
1465 1477 kw.setdefault('indent',' ')
1466 1478 kw.setdefault('sep',': ')
1467 1479 kw.setdefault('start',0)
1468 1480 kw.setdefault('stop',len(lst))
1469 1481 # we need to remove start and stop from kw so they don't propagate
1470 1482 # into a recursive call for a nested list.
1471 1483 start = kw['start']; del kw['start']
1472 1484 stop = kw['stop']; del kw['stop']
1473 1485 if self.depth == 0 and 'header' in kw.keys():
1474 1486 print kw['header']
1475 1487
1476 1488 for idx in range(start,stop):
1477 1489 elem = lst[idx]
1478 1490 if type(elem)==type([]):
1479 1491 self.depth += 1
1480 1492 self.__call__(elem,itpl('$pos$idx,'),**kw)
1481 1493 self.depth -= 1
1482 1494 else:
1483 1495 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1484 1496
1485 1497 nlprint = NLprinter()
1486 1498 #----------------------------------------------------------------------------
1487 1499 def all_belong(candidates,checklist):
1488 1500 """Check whether a list of items ALL appear in a given list of options.
1489 1501
1490 1502 Returns a single 1 or 0 value."""
1491 1503
1492 1504 return 1-(0 in [x in checklist for x in candidates])
1493 1505
1494 1506 #----------------------------------------------------------------------------
1495 1507 def sort_compare(lst1,lst2,inplace = 1):
1496 1508 """Sort and compare two lists.
1497 1509
1498 1510 By default it does it in place, thus modifying the lists. Use inplace = 0
1499 1511 to avoid that (at the cost of temporary copy creation)."""
1500 1512 if not inplace:
1501 1513 lst1 = lst1[:]
1502 1514 lst2 = lst2[:]
1503 1515 lst1.sort(); lst2.sort()
1504 1516 return lst1 == lst2
1505 1517
1506 1518 #----------------------------------------------------------------------------
1507 1519 def mkdict(**kwargs):
1508 1520 """Return a dict from a keyword list.
1509 1521
1510 1522 It's just syntactic sugar for making ditcionary creation more convenient:
1511 1523 # the standard way
1512 1524 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1513 1525 # a cleaner way
1514 1526 >>>data = dict(red=1, green=2, blue=3)
1515 1527
1516 1528 If you need more than this, look at the Struct() class."""
1517 1529
1518 1530 return kwargs
1519 1531
1520 1532 #----------------------------------------------------------------------------
1521 1533 def list2dict(lst):
1522 1534 """Takes a list of (key,value) pairs and turns it into a dict."""
1523 1535
1524 1536 dic = {}
1525 1537 for k,v in lst: dic[k] = v
1526 1538 return dic
1527 1539
1528 1540 #----------------------------------------------------------------------------
1529 1541 def list2dict2(lst,default=''):
1530 1542 """Takes a list and turns it into a dict.
1531 1543 Much slower than list2dict, but more versatile. This version can take
1532 1544 lists with sublists of arbitrary length (including sclars)."""
1533 1545
1534 1546 dic = {}
1535 1547 for elem in lst:
1536 1548 if type(elem) in (types.ListType,types.TupleType):
1537 1549 size = len(elem)
1538 1550 if size == 0:
1539 1551 pass
1540 1552 elif size == 1:
1541 1553 dic[elem] = default
1542 1554 else:
1543 1555 k,v = elem[0], elem[1:]
1544 1556 if len(v) == 1: v = v[0]
1545 1557 dic[k] = v
1546 1558 else:
1547 1559 dic[elem] = default
1548 1560 return dic
1549 1561
1550 1562 #----------------------------------------------------------------------------
1551 1563 def flatten(seq):
1552 1564 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1553 1565
1554 1566 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1555 1567
1556 1568 # if the x=0 isn't made, a *global* variable x is left over after calling
1557 1569 # this function, with the value of the last element in the return
1558 1570 # list. This does seem like a bug big time to me.
1559 1571
1560 1572 # the problem is fixed with the x=0, which seems to force the creation of
1561 1573 # a local name
1562 1574
1563 1575 x = 0
1564 1576 return [x for subseq in seq for x in subseq]
1565 1577
1566 1578 #----------------------------------------------------------------------------
1567 1579 def get_slice(seq,start=0,stop=None,step=1):
1568 1580 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1569 1581 if stop == None:
1570 1582 stop = len(seq)
1571 1583 item = lambda i: seq[i]
1572 1584 return map(item,xrange(start,stop,step))
1573 1585
1574 1586 #----------------------------------------------------------------------------
1575 1587 def chop(seq,size):
1576 1588 """Chop a sequence into chunks of the given size."""
1577 1589 chunk = lambda i: seq[i:i+size]
1578 1590 return map(chunk,xrange(0,len(seq),size))
1579 1591
1580 1592 #----------------------------------------------------------------------------
1581 1593 def with(object, **args):
1582 1594 """Set multiple attributes for an object, similar to Pascal's with.
1583 1595
1584 1596 Example:
1585 1597 with(jim,
1586 1598 born = 1960,
1587 1599 haircolour = 'Brown',
1588 1600 eyecolour = 'Green')
1589 1601
1590 1602 Credit: Greg Ewing, in
1591 1603 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1592 1604
1593 1605 object.__dict__.update(args)
1594 1606
1595 1607 #----------------------------------------------------------------------------
1596 1608 def setattr_list(obj,alist,nspace = None):
1597 1609 """Set a list of attributes for an object taken from a namespace.
1598 1610
1599 1611 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1600 1612 alist with their values taken from nspace, which must be a dict (something
1601 1613 like locals() will often do) If nspace isn't given, locals() of the
1602 1614 *caller* is used, so in most cases you can omit it.
1603 1615
1604 1616 Note that alist can be given as a string, which will be automatically
1605 1617 split into a list on whitespace. If given as a list, it must be a list of
1606 1618 *strings* (the variable names themselves), not of variables."""
1607 1619
1608 1620 # this grabs the local variables from the *previous* call frame -- that is
1609 1621 # the locals from the function that called setattr_list().
1610 1622 # - snipped from weave.inline()
1611 1623 if nspace is None:
1612 1624 call_frame = sys._getframe().f_back
1613 1625 nspace = call_frame.f_locals
1614 1626
1615 1627 if type(alist) in StringTypes:
1616 1628 alist = alist.split()
1617 1629 for attr in alist:
1618 1630 val = eval(attr,nspace)
1619 1631 setattr(obj,attr,val)
1620 1632
1621 1633 #----------------------------------------------------------------------------
1622 1634 def getattr_list(obj,alist,*args):
1623 1635 """getattr_list(obj,alist[, default]) -> attribute list.
1624 1636
1625 1637 Get a list of named attributes for an object. When a default argument is
1626 1638 given, it is returned when the attribute doesn't exist; without it, an
1627 1639 exception is raised in that case.
1628 1640
1629 1641 Note that alist can be given as a string, which will be automatically
1630 1642 split into a list on whitespace. If given as a list, it must be a list of
1631 1643 *strings* (the variable names themselves), not of variables."""
1632 1644
1633 1645 if type(alist) in StringTypes:
1634 1646 alist = alist.split()
1635 1647 if args:
1636 1648 if len(args)==1:
1637 1649 default = args[0]
1638 1650 return map(lambda attr: getattr(obj,attr,default),alist)
1639 1651 else:
1640 1652 raise ValueError,'getattr_list() takes only one optional argument'
1641 1653 else:
1642 1654 return map(lambda attr: getattr(obj,attr),alist)
1643 1655
1644 1656 #----------------------------------------------------------------------------
1645 1657 def map_method(method,object_list,*argseq,**kw):
1646 1658 """map_method(method,object_list,*args,**kw) -> list
1647 1659
1648 1660 Return a list of the results of applying the methods to the items of the
1649 1661 argument sequence(s). If more than one sequence is given, the method is
1650 1662 called with an argument list consisting of the corresponding item of each
1651 1663 sequence. All sequences must be of the same length.
1652 1664
1653 1665 Keyword arguments are passed verbatim to all objects called.
1654 1666
1655 1667 This is Python code, so it's not nearly as fast as the builtin map()."""
1656 1668
1657 1669 out_list = []
1658 1670 idx = 0
1659 1671 for object in object_list:
1660 1672 try:
1661 1673 handler = getattr(object, method)
1662 1674 except AttributeError:
1663 1675 out_list.append(None)
1664 1676 else:
1665 1677 if argseq:
1666 1678 args = map(lambda lst:lst[idx],argseq)
1667 1679 #print 'ob',object,'hand',handler,'ar',args # dbg
1668 1680 out_list.append(handler(args,**kw))
1669 1681 else:
1670 1682 out_list.append(handler(**kw))
1671 1683 idx += 1
1672 1684 return out_list
1673 1685
1674 1686 #----------------------------------------------------------------------------
1675 1687 def import_fail_info(mod_name,fns=None):
1676 1688 """Inform load failure for a module."""
1677 1689
1678 1690 if fns == None:
1679 1691 warn("Loading of %s failed.\n" % (mod_name,))
1680 1692 else:
1681 1693 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1682 1694
1683 1695 #----------------------------------------------------------------------------
1684 1696 # Proposed popitem() extension, written as a method
1685 1697
1686 1698 class NotGiven: pass
1687 1699
1688 1700 def popkey(dct,key,default=NotGiven):
1689 1701 """Return dct[key] and delete dct[key].
1690 1702
1691 1703 If default is given, return it if dct[key] doesn't exist, otherwise raise
1692 1704 KeyError. """
1693 1705
1694 1706 try:
1695 1707 val = dct[key]
1696 1708 except KeyError:
1697 1709 if default is NotGiven:
1698 1710 raise
1699 1711 else:
1700 1712 return default
1701 1713 else:
1702 1714 del dct[key]
1703 1715 return val
1704 1716 #*************************** end of file <genutils.py> **********************
1705 1717
@@ -1,2138 +1,2153 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 988 2006-01-02 21:21:47Z fperez $
9 $Id: iplib.py 990 2006-01-04 06:59:02Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from __future__ import generators # for 2.2 backwards-compatibility
32 32
33 33 from IPython import Release
34 34 __author__ = '%s <%s>\n%s <%s>' % \
35 35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 36 __license__ = Release.license
37 37 __version__ = Release.version
38 38
39 39 # Python standard modules
40 40 import __main__
41 41 import __builtin__
42 42 import StringIO
43 43 import bdb
44 44 import cPickle as pickle
45 45 import codeop
46 46 import exceptions
47 47 import glob
48 48 import inspect
49 49 import keyword
50 50 import new
51 51 import os
52 52 import pdb
53 53 import pydoc
54 54 import re
55 55 import shutil
56 56 import string
57 57 import sys
58 58 import tempfile
59 59 import traceback
60 60 import types
61 61
62 62 from pprint import pprint, pformat
63 63
64 64 # IPython's own modules
65 65 import IPython
66 66 from IPython import OInspect,PyColorize,ultraTB
67 67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
68 68 from IPython.FakeModule import FakeModule
69 69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
70 70 from IPython.Logger import Logger
71 71 from IPython.Magic import Magic
72 72 from IPython.Prompts import CachedOutput
73 73 from IPython.Struct import Struct
74 74 from IPython.background_jobs import BackgroundJobManager
75 75 from IPython.usage import cmd_line_usage,interactive_usage
76 76 from IPython.genutils import *
77 77
78 78 # store the builtin raw_input globally, and use this always, in case user code
79 79 # overwrites it (like wx.py.PyShell does)
80 80 raw_input_original = raw_input
81 81
82 82 # compiled regexps for autoindent management
83 83 ini_spaces_re = re.compile(r'^(\s+)')
84 84 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 85
86 86 #****************************************************************************
87 87 # Some utility function definitions
88 88
89 89 def softspace(file, newvalue):
90 90 """Copied from code.py, to remove the dependency"""
91 91 oldvalue = 0
92 92 try:
93 93 oldvalue = file.softspace
94 94 except AttributeError:
95 95 pass
96 96 try:
97 97 file.softspace = newvalue
98 98 except (AttributeError, TypeError):
99 99 # "attribute-less object" or "read-only attributes"
100 100 pass
101 101 return oldvalue
102 102
103 103 #****************************************************************************
104 104
105 105
106 106 #****************************************************************************
107 107 # Local use exceptions
108 108 class SpaceInInput(exceptions.Exception): pass
109 109
110 110 #****************************************************************************
111 111 # Local use classes
112 112 class Bunch: pass
113 113
114 114 class Undefined: pass
115 115
116 116 class InputList(list):
117 117 """Class to store user input.
118 118
119 119 It's basically a list, but slices return a string instead of a list, thus
120 120 allowing things like (assuming 'In' is an instance):
121 121
122 122 exec In[4:7]
123 123
124 124 or
125 125
126 126 exec In[5:9] + In[14] + In[21:25]"""
127 127
128 128 def __getslice__(self,i,j):
129 129 return ''.join(list.__getslice__(self,i,j))
130 130
131 131 class SyntaxTB(ultraTB.ListTB):
132 132 """Extension which holds some state: the last exception value"""
133 133
134 134 def __init__(self,color_scheme = 'NoColor'):
135 135 ultraTB.ListTB.__init__(self,color_scheme)
136 136 self.last_syntax_error = None
137 137
138 138 def __call__(self, etype, value, elist):
139 139 self.last_syntax_error = value
140 140 ultraTB.ListTB.__call__(self,etype,value,elist)
141 141
142 142 def clear_err_state(self):
143 143 """Return the current error state and clear it"""
144 144 e = self.last_syntax_error
145 145 self.last_syntax_error = None
146 146 return e
147 147
148 148 #****************************************************************************
149 149 # Main IPython class
150 150
151 151 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
152 152 # until a full rewrite is made. I've cleaned all cross-class uses of
153 153 # attributes and methods, but too much user code out there relies on the
154 154 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
155 155 #
156 156 # But at least now, all the pieces have been separated and we could, in
157 157 # principle, stop using the mixin. This will ease the transition to the
158 158 # chainsaw branch.
159 159
160 160 # For reference, the following is the list of 'self.foo' uses in the Magic
161 161 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
162 162 # class, to prevent clashes.
163 163
164 164 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
165 165 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
166 166 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
167 167 # 'self.value']
168 168
169 169 class InteractiveShell(object,Magic):
170 170 """An enhanced console for Python."""
171 171
172 172 # class attribute to indicate whether the class supports threads or not.
173 173 # Subclasses with thread support should override this as needed.
174 174 isthreaded = False
175 175
176 176 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
177 177 user_ns = None,user_global_ns=None,banner2='',
178 178 custom_exceptions=((),None),embedded=False):
179 179
180 180 # some minimal strict typechecks. For some core data structures, I
181 181 # want actual basic python types, not just anything that looks like
182 182 # one. This is especially true for namespaces.
183 183 for ns in (user_ns,user_global_ns):
184 184 if ns is not None and type(ns) != types.DictType:
185 185 raise TypeError,'namespace must be a dictionary'
186 186
187 187 # Job manager (for jobs run as background threads)
188 188 self.jobs = BackgroundJobManager()
189 189
190 190 # track which builtins we add, so we can clean up later
191 191 self.builtins_added = {}
192 192 # This method will add the necessary builtins for operation, but
193 193 # tracking what it did via the builtins_added dict.
194 194 self.add_builtins()
195 195
196 196 # Do the intuitively correct thing for quit/exit: we remove the
197 197 # builtins if they exist, and our own magics will deal with this
198 198 try:
199 199 del __builtin__.exit, __builtin__.quit
200 200 except AttributeError:
201 201 pass
202 202
203 203 # Store the actual shell's name
204 204 self.name = name
205 205
206 206 # We need to know whether the instance is meant for embedding, since
207 207 # global/local namespaces need to be handled differently in that case
208 208 self.embedded = embedded
209 209
210 210 # command compiler
211 211 self.compile = codeop.CommandCompiler()
212 212
213 213 # User input buffer
214 214 self.buffer = []
215 215
216 216 # Default name given in compilation of code
217 217 self.filename = '<ipython console>'
218 218
219 219 # Make an empty namespace, which extension writers can rely on both
220 220 # existing and NEVER being used by ipython itself. This gives them a
221 221 # convenient location for storing additional information and state
222 222 # their extensions may require, without fear of collisions with other
223 223 # ipython names that may develop later.
224 224 self.meta = Bunch()
225 225
226 226 # Create the namespace where the user will operate. user_ns is
227 227 # normally the only one used, and it is passed to the exec calls as
228 228 # the locals argument. But we do carry a user_global_ns namespace
229 229 # given as the exec 'globals' argument, This is useful in embedding
230 230 # situations where the ipython shell opens in a context where the
231 231 # distinction between locals and globals is meaningful.
232 232
233 233 # FIXME. For some strange reason, __builtins__ is showing up at user
234 234 # level as a dict instead of a module. This is a manual fix, but I
235 235 # should really track down where the problem is coming from. Alex
236 236 # Schmolck reported this problem first.
237 237
238 238 # A useful post by Alex Martelli on this topic:
239 239 # Re: inconsistent value from __builtins__
240 240 # Von: Alex Martelli <aleaxit@yahoo.com>
241 241 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
242 242 # Gruppen: comp.lang.python
243 243
244 244 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
245 245 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
246 246 # > <type 'dict'>
247 247 # > >>> print type(__builtins__)
248 248 # > <type 'module'>
249 249 # > Is this difference in return value intentional?
250 250
251 251 # Well, it's documented that '__builtins__' can be either a dictionary
252 252 # or a module, and it's been that way for a long time. Whether it's
253 253 # intentional (or sensible), I don't know. In any case, the idea is
254 254 # that if you need to access the built-in namespace directly, you
255 255 # should start with "import __builtin__" (note, no 's') which will
256 256 # definitely give you a module. Yeah, it's somewhat confusing:-(.
257 257
258 258 if user_ns is None:
259 259 # Set __name__ to __main__ to better match the behavior of the
260 260 # normal interpreter.
261 261 user_ns = {'__name__' :'__main__',
262 262 '__builtins__' : __builtin__,
263 263 }
264 264
265 265 if user_global_ns is None:
266 266 user_global_ns = {}
267 267
268 268 # Assign namespaces
269 269 # This is the namespace where all normal user variables live
270 270 self.user_ns = user_ns
271 271 # Embedded instances require a separate namespace for globals.
272 272 # Normally this one is unused by non-embedded instances.
273 273 self.user_global_ns = user_global_ns
274 274 # A namespace to keep track of internal data structures to prevent
275 275 # them from cluttering user-visible stuff. Will be updated later
276 276 self.internal_ns = {}
277 277
278 278 # Namespace of system aliases. Each entry in the alias
279 279 # table must be a 2-tuple of the form (N,name), where N is the number
280 280 # of positional arguments of the alias.
281 281 self.alias_table = {}
282 282
283 283 # A table holding all the namespaces IPython deals with, so that
284 284 # introspection facilities can search easily.
285 285 self.ns_table = {'user':user_ns,
286 286 'user_global':user_global_ns,
287 287 'alias':self.alias_table,
288 288 'internal':self.internal_ns,
289 289 'builtin':__builtin__.__dict__
290 290 }
291 291
292 292 # The user namespace MUST have a pointer to the shell itself.
293 293 self.user_ns[name] = self
294 294
295 295 # We need to insert into sys.modules something that looks like a
296 296 # module but which accesses the IPython namespace, for shelve and
297 297 # pickle to work interactively. Normally they rely on getting
298 298 # everything out of __main__, but for embedding purposes each IPython
299 299 # instance has its own private namespace, so we can't go shoving
300 300 # everything into __main__.
301 301
302 302 # note, however, that we should only do this for non-embedded
303 303 # ipythons, which really mimic the __main__.__dict__ with their own
304 304 # namespace. Embedded instances, on the other hand, should not do
305 305 # this because they need to manage the user local/global namespaces
306 306 # only, but they live within a 'normal' __main__ (meaning, they
307 307 # shouldn't overtake the execution environment of the script they're
308 308 # embedded in).
309 309
310 310 if not embedded:
311 311 try:
312 312 main_name = self.user_ns['__name__']
313 313 except KeyError:
314 314 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
315 315 else:
316 316 #print "pickle hack in place" # dbg
317 317 #print 'main_name:',main_name # dbg
318 318 sys.modules[main_name] = FakeModule(self.user_ns)
319 319
320 320 # List of input with multi-line handling.
321 321 # Fill its zero entry, user counter starts at 1
322 322 self.input_hist = InputList(['\n'])
323 323
324 324 # list of visited directories
325 325 try:
326 326 self.dir_hist = [os.getcwd()]
327 327 except IOError, e:
328 328 self.dir_hist = []
329 329
330 330 # dict of output history
331 331 self.output_hist = {}
332 332
333 333 # dict of things NOT to alias (keywords, builtins and some magics)
334 334 no_alias = {}
335 335 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
336 336 for key in keyword.kwlist + no_alias_magics:
337 337 no_alias[key] = 1
338 338 no_alias.update(__builtin__.__dict__)
339 339 self.no_alias = no_alias
340 340
341 341 # make global variables for user access to these
342 342 self.user_ns['_ih'] = self.input_hist
343 343 self.user_ns['_oh'] = self.output_hist
344 344 self.user_ns['_dh'] = self.dir_hist
345 345
346 346 # user aliases to input and output histories
347 347 self.user_ns['In'] = self.input_hist
348 348 self.user_ns['Out'] = self.output_hist
349 349
350 350 # Object variable to store code object waiting execution. This is
351 351 # used mainly by the multithreaded shells, but it can come in handy in
352 352 # other situations. No need to use a Queue here, since it's a single
353 353 # item which gets cleared once run.
354 354 self.code_to_run = None
355 355
356 356 # escapes for automatic behavior on the command line
357 357 self.ESC_SHELL = '!'
358 358 self.ESC_HELP = '?'
359 359 self.ESC_MAGIC = '%'
360 360 self.ESC_QUOTE = ','
361 361 self.ESC_QUOTE2 = ';'
362 362 self.ESC_PAREN = '/'
363 363
364 364 # And their associated handlers
365 365 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
366 366 self.ESC_QUOTE : self.handle_auto,
367 367 self.ESC_QUOTE2 : self.handle_auto,
368 368 self.ESC_MAGIC : self.handle_magic,
369 369 self.ESC_HELP : self.handle_help,
370 370 self.ESC_SHELL : self.handle_shell_escape,
371 371 }
372 372
373 373 # class initializations
374 374 Magic.__init__(self,self)
375 375
376 376 # Python source parser/formatter for syntax highlighting
377 377 pyformat = PyColorize.Parser().format
378 378 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
379 379
380 380 # hooks holds pointers used for user-side customizations
381 381 self.hooks = Struct()
382 382
383 383 # Set all default hooks, defined in the IPython.hooks module.
384 384 hooks = IPython.hooks
385 385 for hook_name in hooks.__all__:
386 386 self.set_hook(hook_name,getattr(hooks,hook_name))
387 387
388 388 # Flag to mark unconditional exit
389 389 self.exit_now = False
390 390
391 391 self.usage_min = """\
392 392 An enhanced console for Python.
393 393 Some of its features are:
394 394 - Readline support if the readline library is present.
395 395 - Tab completion in the local namespace.
396 396 - Logging of input, see command-line options.
397 397 - System shell escape via ! , eg !ls.
398 398 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
399 399 - Keeps track of locally defined variables via %who, %whos.
400 400 - Show object information with a ? eg ?x or x? (use ?? for more info).
401 401 """
402 402 if usage: self.usage = usage
403 403 else: self.usage = self.usage_min
404 404
405 405 # Storage
406 406 self.rc = rc # This will hold all configuration information
407 407 self.pager = 'less'
408 408 # temporary files used for various purposes. Deleted at exit.
409 409 self.tempfiles = []
410 410
411 411 # Keep track of readline usage (later set by init_readline)
412 412 self.has_readline = False
413 413
414 414 # template for logfile headers. It gets resolved at runtime by the
415 415 # logstart method.
416 416 self.loghead_tpl = \
417 417 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
418 418 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
419 419 #log# opts = %s
420 420 #log# args = %s
421 421 #log# It is safe to make manual edits below here.
422 422 #log#-----------------------------------------------------------------------
423 423 """
424 424 # for pushd/popd management
425 425 try:
426 426 self.home_dir = get_home_dir()
427 427 except HomeDirError,msg:
428 428 fatal(msg)
429 429
430 430 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
431 431
432 432 # Functions to call the underlying shell.
433 433
434 434 # utility to expand user variables via Itpl
435 435 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
436 436 self.user_ns))
437 437 # The first is similar to os.system, but it doesn't return a value,
438 438 # and it allows interpolation of variables in the user's namespace.
439 439 self.system = lambda cmd: shell(self.var_expand(cmd),
440 440 header='IPython system call: ',
441 441 verbose=self.rc.system_verbose)
442 442 # These are for getoutput and getoutputerror:
443 443 self.getoutput = lambda cmd: \
444 444 getoutput(self.var_expand(cmd),
445 445 header='IPython system call: ',
446 446 verbose=self.rc.system_verbose)
447 447 self.getoutputerror = lambda cmd: \
448 448 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
449 449 self.user_ns)),
450 450 header='IPython system call: ',
451 451 verbose=self.rc.system_verbose)
452 452
453 453 # RegExp for splitting line contents into pre-char//first
454 454 # word-method//rest. For clarity, each group in on one line.
455 455
456 456 # WARNING: update the regexp if the above escapes are changed, as they
457 457 # are hardwired in.
458 458
459 459 # Don't get carried away with trying to make the autocalling catch too
460 460 # much: it's better to be conservative rather than to trigger hidden
461 461 # evals() somewhere and end up causing side effects.
462 462
463 463 self.line_split = re.compile(r'^([\s*,;/])'
464 464 r'([\?\w\.]+\w*\s*)'
465 465 r'(\(?.*$)')
466 466
467 467 # Original re, keep around for a while in case changes break something
468 468 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
469 469 # r'(\s*[\?\w\.]+\w*\s*)'
470 470 # r'(\(?.*$)')
471 471
472 472 # RegExp to identify potential function names
473 473 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
474 474 # RegExp to exclude strings with this start from autocalling
475 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
475 self.re_exclude_auto = re.compile('^[!=()\[\]<>,\*/\+-]|^is ')
476 476
477 477 # try to catch also methods for stuff in lists/tuples/dicts: off
478 478 # (experimental). For this to work, the line_split regexp would need
479 479 # to be modified so it wouldn't break things at '['. That line is
480 480 # nasty enough that I shouldn't change it until I can test it _well_.
481 481 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
482 482
483 483 # keep track of where we started running (mainly for crash post-mortem)
484 484 self.starting_dir = os.getcwd()
485 485
486 486 # Various switches which can be set
487 487 self.CACHELENGTH = 5000 # this is cheap, it's just text
488 488 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
489 489 self.banner2 = banner2
490 490
491 491 # TraceBack handlers:
492 492
493 493 # Syntax error handler.
494 494 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
495 495
496 496 # The interactive one is initialized with an offset, meaning we always
497 497 # want to remove the topmost item in the traceback, which is our own
498 498 # internal code. Valid modes: ['Plain','Context','Verbose']
499 499 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
500 500 color_scheme='NoColor',
501 501 tb_offset = 1)
502 502
503 503 # IPython itself shouldn't crash. This will produce a detailed
504 504 # post-mortem if it does. But we only install the crash handler for
505 505 # non-threaded shells, the threaded ones use a normal verbose reporter
506 506 # and lose the crash handler. This is because exceptions in the main
507 507 # thread (such as in GUI code) propagate directly to sys.excepthook,
508 508 # and there's no point in printing crash dumps for every user exception.
509 509 if self.isthreaded:
510 510 sys.excepthook = ultraTB.FormattedTB()
511 511 else:
512 512 from IPython import CrashHandler
513 513 sys.excepthook = CrashHandler.CrashHandler(self)
514 514
515 515 # The instance will store a pointer to this, so that runtime code
516 516 # (such as magics) can access it. This is because during the
517 517 # read-eval loop, it gets temporarily overwritten (to deal with GUI
518 518 # frameworks).
519 519 self.sys_excepthook = sys.excepthook
520 520
521 521 # and add any custom exception handlers the user may have specified
522 522 self.set_custom_exc(*custom_exceptions)
523 523
524 524 # Object inspector
525 525 self.inspector = OInspect.Inspector(OInspect.InspectColors,
526 526 PyColorize.ANSICodeColors,
527 527 'NoColor')
528 528 # indentation management
529 529 self.autoindent = False
530 530 self.indent_current_nsp = 0
531 531 self.indent_current = '' # actual indent string
532 532
533 533 # Make some aliases automatically
534 534 # Prepare list of shell aliases to auto-define
535 535 if os.name == 'posix':
536 536 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
537 537 'mv mv -i','rm rm -i','cp cp -i',
538 538 'cat cat','less less','clear clear',
539 539 # a better ls
540 540 'ls ls -F',
541 541 # long ls
542 542 'll ls -lF',
543 543 # color ls
544 544 'lc ls -F -o --color',
545 545 # ls normal files only
546 546 'lf ls -F -o --color %l | grep ^-',
547 547 # ls symbolic links
548 548 'lk ls -F -o --color %l | grep ^l',
549 549 # directories or links to directories,
550 550 'ldir ls -F -o --color %l | grep /$',
551 551 # things which are executable
552 552 'lx ls -F -o --color %l | grep ^-..x',
553 553 )
554 554 elif os.name in ['nt','dos']:
555 555 auto_alias = ('dir dir /on', 'ls dir /on',
556 556 'ddir dir /ad /on', 'ldir dir /ad /on',
557 557 'mkdir mkdir','rmdir rmdir','echo echo',
558 558 'ren ren','cls cls','copy copy')
559 559 else:
560 560 auto_alias = ()
561 561 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
562 562 # Call the actual (public) initializer
563 563 self.init_auto_alias()
564 564 # end __init__
565 565
566 566 def post_config_initialization(self):
567 567 """Post configuration init method
568 568
569 569 This is called after the configuration files have been processed to
570 570 'finalize' the initialization."""
571 571
572 572 rc = self.rc
573 573
574 574 # Load readline proper
575 575 if rc.readline:
576 576 self.init_readline()
577 577
578 578 # log system
579 579 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
580 580 # local shortcut, this is used a LOT
581 581 self.log = self.logger.log
582 582
583 583 # Initialize cache, set in/out prompts and printing system
584 584 self.outputcache = CachedOutput(self,
585 585 rc.cache_size,
586 586 rc.pprint,
587 587 input_sep = rc.separate_in,
588 588 output_sep = rc.separate_out,
589 589 output_sep2 = rc.separate_out2,
590 590 ps1 = rc.prompt_in1,
591 591 ps2 = rc.prompt_in2,
592 592 ps_out = rc.prompt_out,
593 593 pad_left = rc.prompts_pad_left)
594 594
595 595 # user may have over-ridden the default print hook:
596 596 try:
597 597 self.outputcache.__class__.display = self.hooks.display
598 598 except AttributeError:
599 599 pass
600 600
601 601 # I don't like assigning globally to sys, because it means when embedding
602 602 # instances, each embedded instance overrides the previous choice. But
603 603 # sys.displayhook seems to be called internally by exec, so I don't see a
604 604 # way around it.
605 605 sys.displayhook = self.outputcache
606 606
607 607 # Set user colors (don't do it in the constructor above so that it
608 608 # doesn't crash if colors option is invalid)
609 609 self.magic_colors(rc.colors)
610 610
611 611 # Set calling of pdb on exceptions
612 612 self.call_pdb = rc.pdb
613 613
614 614 # Load user aliases
615 615 for alias in rc.alias:
616 616 self.magic_alias(alias)
617 617
618 618 # dynamic data that survives through sessions
619 619 # XXX make the filename a config option?
620 620 persist_base = 'persist'
621 621 if rc.profile:
622 622 persist_base += '_%s' % rc.profile
623 623 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
624 624
625 625 try:
626 626 self.persist = pickle.load(file(self.persist_fname))
627 627 except:
628 628 self.persist = {}
629 629
630 630
631 631 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
632 632 try:
633 633 obj = pickle.loads(value)
634 634 except:
635 635
636 636 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
637 637 print "The error was:",sys.exc_info()[0]
638 638 continue
639 639
640 640
641 641 self.user_ns[key] = obj
642 642
643 643 def add_builtins(self):
644 644 """Store ipython references into the builtin namespace.
645 645
646 646 Some parts of ipython operate via builtins injected here, which hold a
647 647 reference to IPython itself."""
648 648
649 649 builtins_new = dict(__IPYTHON__ = self,
650 650 ip_set_hook = self.set_hook,
651 651 jobs = self.jobs,
652 652 ipmagic = self.ipmagic,
653 653 ipalias = self.ipalias,
654 654 ipsystem = self.ipsystem,
655 655 )
656 656 for biname,bival in builtins_new.items():
657 657 try:
658 658 # store the orignal value so we can restore it
659 659 self.builtins_added[biname] = __builtin__.__dict__[biname]
660 660 except KeyError:
661 661 # or mark that it wasn't defined, and we'll just delete it at
662 662 # cleanup
663 663 self.builtins_added[biname] = Undefined
664 664 __builtin__.__dict__[biname] = bival
665 665
666 666 # Keep in the builtins a flag for when IPython is active. We set it
667 667 # with setdefault so that multiple nested IPythons don't clobber one
668 668 # another. Each will increase its value by one upon being activated,
669 669 # which also gives us a way to determine the nesting level.
670 670 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
671 671
672 672 def clean_builtins(self):
673 673 """Remove any builtins which might have been added by add_builtins, or
674 674 restore overwritten ones to their previous values."""
675 675 for biname,bival in self.builtins_added.items():
676 676 if bival is Undefined:
677 677 del __builtin__.__dict__[biname]
678 678 else:
679 679 __builtin__.__dict__[biname] = bival
680 680 self.builtins_added.clear()
681 681
682 682 def set_hook(self,name,hook):
683 683 """set_hook(name,hook) -> sets an internal IPython hook.
684 684
685 685 IPython exposes some of its internal API as user-modifiable hooks. By
686 686 resetting one of these hooks, you can modify IPython's behavior to
687 687 call at runtime your own routines."""
688 688
689 689 # At some point in the future, this should validate the hook before it
690 690 # accepts it. Probably at least check that the hook takes the number
691 691 # of args it's supposed to.
692 692 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
693 693
694 694 def set_custom_exc(self,exc_tuple,handler):
695 695 """set_custom_exc(exc_tuple,handler)
696 696
697 697 Set a custom exception handler, which will be called if any of the
698 698 exceptions in exc_tuple occur in the mainloop (specifically, in the
699 699 runcode() method.
700 700
701 701 Inputs:
702 702
703 703 - exc_tuple: a *tuple* of valid exceptions to call the defined
704 704 handler for. It is very important that you use a tuple, and NOT A
705 705 LIST here, because of the way Python's except statement works. If
706 706 you only want to trap a single exception, use a singleton tuple:
707 707
708 708 exc_tuple == (MyCustomException,)
709 709
710 710 - handler: this must be defined as a function with the following
711 711 basic interface: def my_handler(self,etype,value,tb).
712 712
713 713 This will be made into an instance method (via new.instancemethod)
714 714 of IPython itself, and it will be called if any of the exceptions
715 715 listed in the exc_tuple are caught. If the handler is None, an
716 716 internal basic one is used, which just prints basic info.
717 717
718 718 WARNING: by putting in your own exception handler into IPython's main
719 719 execution loop, you run a very good chance of nasty crashes. This
720 720 facility should only be used if you really know what you are doing."""
721 721
722 722 assert type(exc_tuple)==type(()) , \
723 723 "The custom exceptions must be given AS A TUPLE."
724 724
725 725 def dummy_handler(self,etype,value,tb):
726 726 print '*** Simple custom exception handler ***'
727 727 print 'Exception type :',etype
728 728 print 'Exception value:',value
729 729 print 'Traceback :',tb
730 730 print 'Source code :','\n'.join(self.buffer)
731 731
732 732 if handler is None: handler = dummy_handler
733 733
734 734 self.CustomTB = new.instancemethod(handler,self,self.__class__)
735 735 self.custom_exceptions = exc_tuple
736 736
737 737 def set_custom_completer(self,completer,pos=0):
738 738 """set_custom_completer(completer,pos=0)
739 739
740 740 Adds a new custom completer function.
741 741
742 742 The position argument (defaults to 0) is the index in the completers
743 743 list where you want the completer to be inserted."""
744 744
745 745 newcomp = new.instancemethod(completer,self.Completer,
746 746 self.Completer.__class__)
747 747 self.Completer.matchers.insert(pos,newcomp)
748 748
749 749 def _get_call_pdb(self):
750 750 return self._call_pdb
751 751
752 752 def _set_call_pdb(self,val):
753 753
754 754 if val not in (0,1,False,True):
755 755 raise ValueError,'new call_pdb value must be boolean'
756 756
757 757 # store value in instance
758 758 self._call_pdb = val
759 759
760 760 # notify the actual exception handlers
761 761 self.InteractiveTB.call_pdb = val
762 762 if self.isthreaded:
763 763 try:
764 764 self.sys_excepthook.call_pdb = val
765 765 except:
766 766 warn('Failed to activate pdb for threaded exception handler')
767 767
768 768 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
769 769 'Control auto-activation of pdb at exceptions')
770 770
771 771
772 772 # These special functions get installed in the builtin namespace, to
773 773 # provide programmatic (pure python) access to magics, aliases and system
774 774 # calls. This is important for logging, user scripting, and more.
775 775
776 776 # We are basically exposing, via normal python functions, the three
777 777 # mechanisms in which ipython offers special call modes (magics for
778 778 # internal control, aliases for direct system access via pre-selected
779 779 # names, and !cmd for calling arbitrary system commands).
780 780
781 781 def ipmagic(self,arg_s):
782 782 """Call a magic function by name.
783 783
784 784 Input: a string containing the name of the magic function to call and any
785 785 additional arguments to be passed to the magic.
786 786
787 787 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
788 788 prompt:
789 789
790 790 In[1]: %name -opt foo bar
791 791
792 792 To call a magic without arguments, simply use ipmagic('name').
793 793
794 794 This provides a proper Python function to call IPython's magics in any
795 795 valid Python code you can type at the interpreter, including loops and
796 796 compound statements. It is added by IPython to the Python builtin
797 797 namespace upon initialization."""
798 798
799 799 args = arg_s.split(' ',1)
800 800 magic_name = args[0]
801 801 if magic_name.startswith(self.ESC_MAGIC):
802 802 magic_name = magic_name[1:]
803 803 try:
804 804 magic_args = args[1]
805 805 except IndexError:
806 806 magic_args = ''
807 807 fn = getattr(self,'magic_'+magic_name,None)
808 808 if fn is None:
809 809 error("Magic function `%s` not found." % magic_name)
810 810 else:
811 811 magic_args = self.var_expand(magic_args)
812 812 return fn(magic_args)
813 813
814 814 def ipalias(self,arg_s):
815 815 """Call an alias by name.
816 816
817 817 Input: a string containing the name of the alias to call and any
818 818 additional arguments to be passed to the magic.
819 819
820 820 ipalias('name -opt foo bar') is equivalent to typing at the ipython
821 821 prompt:
822 822
823 823 In[1]: name -opt foo bar
824 824
825 825 To call an alias without arguments, simply use ipalias('name').
826 826
827 827 This provides a proper Python function to call IPython's aliases in any
828 828 valid Python code you can type at the interpreter, including loops and
829 829 compound statements. It is added by IPython to the Python builtin
830 830 namespace upon initialization."""
831 831
832 832 args = arg_s.split(' ',1)
833 833 alias_name = args[0]
834 834 try:
835 835 alias_args = args[1]
836 836 except IndexError:
837 837 alias_args = ''
838 838 if alias_name in self.alias_table:
839 839 self.call_alias(alias_name,alias_args)
840 840 else:
841 841 error("Alias `%s` not found." % alias_name)
842 842
843 843 def ipsystem(self,arg_s):
844 844 """Make a system call, using IPython."""
845 845 self.system(arg_s)
846 846
847 847 def complete(self,text):
848 848 """Return a sorted list of all possible completions on text.
849 849
850 850 Inputs:
851 851
852 852 - text: a string of text to be completed on.
853 853
854 854 This is a wrapper around the completion mechanism, similar to what
855 855 readline does at the command line when the TAB key is hit. By
856 856 exposing it as a method, it can be used by other non-readline
857 857 environments (such as GUIs) for text completion.
858 858
859 859 Simple usage example:
860 860
861 861 In [1]: x = 'hello'
862 862
863 863 In [2]: __IP.complete('x.l')
864 864 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
865 865
866 866 complete = self.Completer.complete
867 867 state = 0
868 868 # use a dict so we get unique keys, since ipyhton's multiple
869 869 # completers can return duplicates.
870 870 comps = {}
871 871 while True:
872 872 newcomp = complete(text,state)
873 873 if newcomp is None:
874 874 break
875 875 comps[newcomp] = 1
876 876 state += 1
877 877 outcomps = comps.keys()
878 878 outcomps.sort()
879 879 return outcomps
880 880
881 881 def set_completer_frame(self, frame):
882 882 if frame:
883 883 self.Completer.namespace = frame.f_locals
884 884 self.Completer.global_namespace = frame.f_globals
885 885 else:
886 886 self.Completer.namespace = self.user_ns
887 887 self.Completer.global_namespace = self.user_global_ns
888 888
889 889 def init_auto_alias(self):
890 890 """Define some aliases automatically.
891 891
892 892 These are ALL parameter-less aliases"""
893 893 for alias,cmd in self.auto_alias:
894 894 self.alias_table[alias] = (0,cmd)
895 895
896 896 def alias_table_validate(self,verbose=0):
897 897 """Update information about the alias table.
898 898
899 899 In particular, make sure no Python keywords/builtins are in it."""
900 900
901 901 no_alias = self.no_alias
902 902 for k in self.alias_table.keys():
903 903 if k in no_alias:
904 904 del self.alias_table[k]
905 905 if verbose:
906 906 print ("Deleting alias <%s>, it's a Python "
907 907 "keyword or builtin." % k)
908 908
909 909 def set_autoindent(self,value=None):
910 910 """Set the autoindent flag, checking for readline support.
911 911
912 912 If called with no arguments, it acts as a toggle."""
913 913
914 914 if not self.has_readline:
915 915 if os.name == 'posix':
916 916 warn("The auto-indent feature requires the readline library")
917 917 self.autoindent = 0
918 918 return
919 919 if value is None:
920 920 self.autoindent = not self.autoindent
921 921 else:
922 922 self.autoindent = value
923 923
924 924 def rc_set_toggle(self,rc_field,value=None):
925 925 """Set or toggle a field in IPython's rc config. structure.
926 926
927 927 If called with no arguments, it acts as a toggle.
928 928
929 929 If called with a non-existent field, the resulting AttributeError
930 930 exception will propagate out."""
931 931
932 932 rc_val = getattr(self.rc,rc_field)
933 933 if value is None:
934 934 value = not rc_val
935 935 setattr(self.rc,rc_field,value)
936 936
937 937 def user_setup(self,ipythondir,rc_suffix,mode='install'):
938 938 """Install the user configuration directory.
939 939
940 940 Can be called when running for the first time or to upgrade the user's
941 941 .ipython/ directory with the mode parameter. Valid modes are 'install'
942 942 and 'upgrade'."""
943 943
944 944 def wait():
945 945 try:
946 946 raw_input("Please press <RETURN> to start IPython.")
947 947 except EOFError:
948 948 print >> Term.cout
949 949 print '*'*70
950 950
951 951 cwd = os.getcwd() # remember where we started
952 952 glb = glob.glob
953 953 print '*'*70
954 954 if mode == 'install':
955 955 print \
956 956 """Welcome to IPython. I will try to create a personal configuration directory
957 957 where you can customize many aspects of IPython's functionality in:\n"""
958 958 else:
959 959 print 'I am going to upgrade your configuration in:'
960 960
961 961 print ipythondir
962 962
963 963 rcdirend = os.path.join('IPython','UserConfig')
964 964 cfg = lambda d: os.path.join(d,rcdirend)
965 965 try:
966 966 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
967 967 except IOError:
968 968 warning = """
969 969 Installation error. IPython's directory was not found.
970 970
971 971 Check the following:
972 972
973 973 The ipython/IPython directory should be in a directory belonging to your
974 974 PYTHONPATH environment variable (that is, it should be in a directory
975 975 belonging to sys.path). You can copy it explicitly there or just link to it.
976 976
977 977 IPython will proceed with builtin defaults.
978 978 """
979 979 warn(warning)
980 980 wait()
981 981 return
982 982
983 983 if mode == 'install':
984 984 try:
985 985 shutil.copytree(rcdir,ipythondir)
986 986 os.chdir(ipythondir)
987 987 rc_files = glb("ipythonrc*")
988 988 for rc_file in rc_files:
989 989 os.rename(rc_file,rc_file+rc_suffix)
990 990 except:
991 991 warning = """
992 992
993 993 There was a problem with the installation:
994 994 %s
995 995 Try to correct it or contact the developers if you think it's a bug.
996 996 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
997 997 warn(warning)
998 998 wait()
999 999 return
1000 1000
1001 1001 elif mode == 'upgrade':
1002 1002 try:
1003 1003 os.chdir(ipythondir)
1004 1004 except:
1005 1005 print """
1006 1006 Can not upgrade: changing to directory %s failed. Details:
1007 1007 %s
1008 1008 """ % (ipythondir,sys.exc_info()[1])
1009 1009 wait()
1010 1010 return
1011 1011 else:
1012 1012 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1013 1013 for new_full_path in sources:
1014 1014 new_filename = os.path.basename(new_full_path)
1015 1015 if new_filename.startswith('ipythonrc'):
1016 1016 new_filename = new_filename + rc_suffix
1017 1017 # The config directory should only contain files, skip any
1018 1018 # directories which may be there (like CVS)
1019 1019 if os.path.isdir(new_full_path):
1020 1020 continue
1021 1021 if os.path.exists(new_filename):
1022 1022 old_file = new_filename+'.old'
1023 1023 if os.path.exists(old_file):
1024 1024 os.remove(old_file)
1025 1025 os.rename(new_filename,old_file)
1026 1026 shutil.copy(new_full_path,new_filename)
1027 1027 else:
1028 1028 raise ValueError,'unrecognized mode for install:',`mode`
1029 1029
1030 1030 # Fix line-endings to those native to each platform in the config
1031 1031 # directory.
1032 1032 try:
1033 1033 os.chdir(ipythondir)
1034 1034 except:
1035 1035 print """
1036 1036 Problem: changing to directory %s failed.
1037 1037 Details:
1038 1038 %s
1039 1039
1040 1040 Some configuration files may have incorrect line endings. This should not
1041 1041 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1042 1042 wait()
1043 1043 else:
1044 1044 for fname in glb('ipythonrc*'):
1045 1045 try:
1046 1046 native_line_ends(fname,backup=0)
1047 1047 except IOError:
1048 1048 pass
1049 1049
1050 1050 if mode == 'install':
1051 1051 print """
1052 1052 Successful installation!
1053 1053
1054 1054 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1055 1055 IPython manual (there are both HTML and PDF versions supplied with the
1056 1056 distribution) to make sure that your system environment is properly configured
1057 1057 to take advantage of IPython's features."""
1058 1058 else:
1059 1059 print """
1060 1060 Successful upgrade!
1061 1061
1062 1062 All files in your directory:
1063 1063 %(ipythondir)s
1064 1064 which would have been overwritten by the upgrade were backed up with a .old
1065 1065 extension. If you had made particular customizations in those files you may
1066 1066 want to merge them back into the new files.""" % locals()
1067 1067 wait()
1068 1068 os.chdir(cwd)
1069 1069 # end user_setup()
1070 1070
1071 1071 def atexit_operations(self):
1072 1072 """This will be executed at the time of exit.
1073 1073
1074 1074 Saving of persistent data should be performed here. """
1075 1075
1076 1076 # input history
1077 1077 self.savehist()
1078 1078
1079 1079 # Cleanup all tempfiles left around
1080 1080 for tfile in self.tempfiles:
1081 1081 try:
1082 1082 os.unlink(tfile)
1083 1083 except OSError:
1084 1084 pass
1085 1085
1086 1086 # save the "persistent data" catch-all dictionary
1087 1087 try:
1088 1088 pickle.dump(self.persist, open(self.persist_fname,"w"))
1089 1089 except:
1090 1090 print "*** ERROR *** persistent data saving failed."
1091 1091
1092 1092 def savehist(self):
1093 1093 """Save input history to a file (via readline library)."""
1094 1094 try:
1095 1095 self.readline.write_history_file(self.histfile)
1096 1096 except:
1097 1097 print 'Unable to save IPython command history to file: ' + \
1098 1098 `self.histfile`
1099 1099
1100 1100 def pre_readline(self):
1101 1101 """readline hook to be used at the start of each line.
1102 1102
1103 1103 Currently it handles auto-indent only."""
1104 1104
1105 1105 self.readline.insert_text(self.indent_current)
1106 1106
1107 1107 def init_readline(self):
1108 1108 """Command history completion/saving/reloading."""
1109 1109 try:
1110 1110 import readline
1111 1111 except ImportError:
1112 1112 self.has_readline = 0
1113 1113 self.readline = None
1114 1114 # no point in bugging windows users with this every time:
1115 1115 if os.name == 'posix':
1116 1116 warn('Readline services not available on this platform.')
1117 1117 else:
1118 1118 import atexit
1119 1119 from IPython.completer import IPCompleter
1120 1120 self.Completer = IPCompleter(self,
1121 1121 self.user_ns,
1122 1122 self.user_global_ns,
1123 1123 self.rc.readline_omit__names,
1124 1124 self.alias_table)
1125 1125
1126 1126 # Platform-specific configuration
1127 1127 if os.name == 'nt':
1128 1128 self.readline_startup_hook = readline.set_pre_input_hook
1129 1129 else:
1130 1130 self.readline_startup_hook = readline.set_startup_hook
1131 1131
1132 1132 # Load user's initrc file (readline config)
1133 1133 inputrc_name = os.environ.get('INPUTRC')
1134 1134 if inputrc_name is None:
1135 1135 home_dir = get_home_dir()
1136 1136 if home_dir is not None:
1137 1137 inputrc_name = os.path.join(home_dir,'.inputrc')
1138 1138 if os.path.isfile(inputrc_name):
1139 1139 try:
1140 1140 readline.read_init_file(inputrc_name)
1141 1141 except:
1142 1142 warn('Problems reading readline initialization file <%s>'
1143 1143 % inputrc_name)
1144 1144
1145 1145 self.has_readline = 1
1146 1146 self.readline = readline
1147 1147 # save this in sys so embedded copies can restore it properly
1148 1148 sys.ipcompleter = self.Completer.complete
1149 1149 readline.set_completer(self.Completer.complete)
1150 1150
1151 1151 # Configure readline according to user's prefs
1152 1152 for rlcommand in self.rc.readline_parse_and_bind:
1153 1153 readline.parse_and_bind(rlcommand)
1154 1154
1155 1155 # remove some chars from the delimiters list
1156 1156 delims = readline.get_completer_delims()
1157 1157 delims = delims.translate(string._idmap,
1158 1158 self.rc.readline_remove_delims)
1159 1159 readline.set_completer_delims(delims)
1160 1160 # otherwise we end up with a monster history after a while:
1161 1161 readline.set_history_length(1000)
1162 1162 try:
1163 1163 #print '*** Reading readline history' # dbg
1164 1164 readline.read_history_file(self.histfile)
1165 1165 except IOError:
1166 1166 pass # It doesn't exist yet.
1167 1167
1168 1168 atexit.register(self.atexit_operations)
1169 1169 del atexit
1170 1170
1171 1171 # Configure auto-indent for all platforms
1172 1172 self.set_autoindent(self.rc.autoindent)
1173 1173
1174 1174 def _should_recompile(self,e):
1175 1175 """Utility routine for edit_syntax_error"""
1176 1176
1177 1177 if e.filename in ('<ipython console>','<input>','<string>',
1178 1178 '<console>'):
1179 1179 return False
1180 1180 try:
1181 1181 if not ask_yes_no('Return to editor to correct syntax error? '
1182 1182 '[Y/n] ','y'):
1183 1183 return False
1184 1184 except EOFError:
1185 1185 return False
1186 1186 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1187 1187 return True
1188 1188
1189 1189 def edit_syntax_error(self):
1190 1190 """The bottom half of the syntax error handler called in the main loop.
1191 1191
1192 1192 Loop until syntax error is fixed or user cancels.
1193 1193 """
1194 1194
1195 1195 while self.SyntaxTB.last_syntax_error:
1196 1196 # copy and clear last_syntax_error
1197 1197 err = self.SyntaxTB.clear_err_state()
1198 1198 if not self._should_recompile(err):
1199 1199 return
1200 1200 try:
1201 1201 # may set last_syntax_error again if a SyntaxError is raised
1202 1202 self.safe_execfile(err.filename,self.shell.user_ns)
1203 1203 except:
1204 1204 self.showtraceback()
1205 1205 else:
1206 1206 f = file(err.filename)
1207 1207 try:
1208 1208 sys.displayhook(f.read())
1209 1209 finally:
1210 1210 f.close()
1211 1211
1212 1212 def showsyntaxerror(self, filename=None):
1213 1213 """Display the syntax error that just occurred.
1214 1214
1215 1215 This doesn't display a stack trace because there isn't one.
1216 1216
1217 1217 If a filename is given, it is stuffed in the exception instead
1218 1218 of what was there before (because Python's parser always uses
1219 1219 "<string>" when reading from a string).
1220 1220 """
1221 1221 etype, value, last_traceback = sys.exc_info()
1222 1222 if filename and etype is SyntaxError:
1223 1223 # Work hard to stuff the correct filename in the exception
1224 1224 try:
1225 1225 msg, (dummy_filename, lineno, offset, line) = value
1226 1226 except:
1227 1227 # Not the format we expect; leave it alone
1228 1228 pass
1229 1229 else:
1230 1230 # Stuff in the right filename
1231 1231 try:
1232 1232 # Assume SyntaxError is a class exception
1233 1233 value = SyntaxError(msg, (filename, lineno, offset, line))
1234 1234 except:
1235 1235 # If that failed, assume SyntaxError is a string
1236 1236 value = msg, (filename, lineno, offset, line)
1237 1237 self.SyntaxTB(etype,value,[])
1238 1238
1239 1239 def debugger(self):
1240 1240 """Call the pdb debugger."""
1241 1241
1242 1242 if not self.rc.pdb:
1243 1243 return
1244 1244 pdb.pm()
1245 1245
1246 1246 def showtraceback(self,exc_tuple = None,filename=None):
1247 1247 """Display the exception that just occurred."""
1248 1248
1249 1249 # Though this won't be called by syntax errors in the input line,
1250 1250 # there may be SyntaxError cases whith imported code.
1251 1251 if exc_tuple is None:
1252 1252 type, value, tb = sys.exc_info()
1253 1253 else:
1254 1254 type, value, tb = exc_tuple
1255 1255 if type is SyntaxError:
1256 1256 self.showsyntaxerror(filename)
1257 1257 else:
1258 1258 self.InteractiveTB()
1259 1259 if self.InteractiveTB.call_pdb and self.has_readline:
1260 1260 # pdb mucks up readline, fix it back
1261 1261 self.readline.set_completer(self.Completer.complete)
1262 1262
1263 1263 def mainloop(self,banner=None):
1264 1264 """Creates the local namespace and starts the mainloop.
1265 1265
1266 1266 If an optional banner argument is given, it will override the
1267 1267 internally created default banner."""
1268 1268
1269 1269 if self.rc.c: # Emulate Python's -c option
1270 1270 self.exec_init_cmd()
1271 1271 if banner is None:
1272 1272 if self.rc.banner:
1273 1273 banner = self.BANNER+self.banner2
1274 1274 else:
1275 1275 banner = ''
1276 1276 self.interact(banner)
1277 1277
1278 1278 def exec_init_cmd(self):
1279 1279 """Execute a command given at the command line.
1280 1280
1281 1281 This emulates Python's -c option."""
1282 1282
1283 1283 sys.argv = ['-c']
1284 1284 self.push(self.rc.c)
1285 1285
1286 1286 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1287 1287 """Embeds IPython into a running python program.
1288 1288
1289 1289 Input:
1290 1290
1291 1291 - header: An optional header message can be specified.
1292 1292
1293 1293 - local_ns, global_ns: working namespaces. If given as None, the
1294 1294 IPython-initialized one is updated with __main__.__dict__, so that
1295 1295 program variables become visible but user-specific configuration
1296 1296 remains possible.
1297 1297
1298 1298 - stack_depth: specifies how many levels in the stack to go to
1299 1299 looking for namespaces (when local_ns and global_ns are None). This
1300 1300 allows an intermediate caller to make sure that this function gets
1301 1301 the namespace from the intended level in the stack. By default (0)
1302 1302 it will get its locals and globals from the immediate caller.
1303 1303
1304 1304 Warning: it's possible to use this in a program which is being run by
1305 1305 IPython itself (via %run), but some funny things will happen (a few
1306 1306 globals get overwritten). In the future this will be cleaned up, as
1307 1307 there is no fundamental reason why it can't work perfectly."""
1308 1308
1309 1309 # Get locals and globals from caller
1310 1310 if local_ns is None or global_ns is None:
1311 1311 call_frame = sys._getframe(stack_depth).f_back
1312 1312
1313 1313 if local_ns is None:
1314 1314 local_ns = call_frame.f_locals
1315 1315 if global_ns is None:
1316 1316 global_ns = call_frame.f_globals
1317 1317
1318 1318 # Update namespaces and fire up interpreter
1319 1319
1320 1320 # The global one is easy, we can just throw it in
1321 1321 self.user_global_ns = global_ns
1322 1322
1323 1323 # but the user/local one is tricky: ipython needs it to store internal
1324 1324 # data, but we also need the locals. We'll copy locals in the user
1325 1325 # one, but will track what got copied so we can delete them at exit.
1326 1326 # This is so that a later embedded call doesn't see locals from a
1327 1327 # previous call (which most likely existed in a separate scope).
1328 1328 local_varnames = local_ns.keys()
1329 1329 self.user_ns.update(local_ns)
1330 1330
1331 1331 # Patch for global embedding to make sure that things don't overwrite
1332 1332 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1333 1333 # FIXME. Test this a bit more carefully (the if.. is new)
1334 1334 if local_ns is None and global_ns is None:
1335 1335 self.user_global_ns.update(__main__.__dict__)
1336 1336
1337 1337 # make sure the tab-completer has the correct frame information, so it
1338 1338 # actually completes using the frame's locals/globals
1339 1339 self.set_completer_frame(call_frame)
1340 1340
1341 1341 # before activating the interactive mode, we need to make sure that
1342 1342 # all names in the builtin namespace needed by ipython point to
1343 1343 # ourselves, and not to other instances.
1344 1344 self.add_builtins()
1345 1345
1346 1346 self.interact(header)
1347 1347
1348 1348 # now, purge out the user namespace from anything we might have added
1349 1349 # from the caller's local namespace
1350 1350 delvar = self.user_ns.pop
1351 1351 for var in local_varnames:
1352 1352 delvar(var,None)
1353 1353 # and clean builtins we may have overridden
1354 1354 self.clean_builtins()
1355 1355
1356 1356 def interact(self, banner=None):
1357 1357 """Closely emulate the interactive Python console.
1358 1358
1359 1359 The optional banner argument specify the banner to print
1360 1360 before the first interaction; by default it prints a banner
1361 1361 similar to the one printed by the real Python interpreter,
1362 1362 followed by the current class name in parentheses (so as not
1363 1363 to confuse this with the real interpreter -- since it's so
1364 1364 close!).
1365 1365
1366 1366 """
1367 1367 cprt = 'Type "copyright", "credits" or "license" for more information.'
1368 1368 if banner is None:
1369 1369 self.write("Python %s on %s\n%s\n(%s)\n" %
1370 1370 (sys.version, sys.platform, cprt,
1371 1371 self.__class__.__name__))
1372 1372 else:
1373 1373 self.write(banner)
1374 1374
1375 1375 more = 0
1376 1376
1377 1377 # Mark activity in the builtins
1378 1378 __builtin__.__dict__['__IPYTHON__active'] += 1
1379 1379
1380 1380 # exit_now is set by a call to %Exit or %Quit
1381 1381 self.exit_now = False
1382 1382 while not self.exit_now:
1383 1383
1384 1384 try:
1385 1385 if more:
1386 1386 prompt = self.outputcache.prompt2
1387 1387 if self.autoindent:
1388 1388 self.readline_startup_hook(self.pre_readline)
1389 1389 else:
1390 1390 prompt = self.outputcache.prompt1
1391 1391 try:
1392 1392 line = self.raw_input(prompt,more)
1393 1393 if self.autoindent:
1394 1394 self.readline_startup_hook(None)
1395 1395 except EOFError:
1396 1396 if self.autoindent:
1397 1397 self.readline_startup_hook(None)
1398 1398 self.write("\n")
1399 1399 self.exit()
1400 1400 else:
1401 1401 more = self.push(line)
1402 1402
1403 1403 if (self.SyntaxTB.last_syntax_error and
1404 1404 self.rc.autoedit_syntax):
1405 1405 self.edit_syntax_error()
1406 1406
1407 1407 except KeyboardInterrupt:
1408 1408 self.write("\nKeyboardInterrupt\n")
1409 1409 self.resetbuffer()
1410 1410 more = 0
1411 1411 # keep cache in sync with the prompt counter:
1412 1412 self.outputcache.prompt_count -= 1
1413 1413
1414 1414 if self.autoindent:
1415 1415 self.indent_current_nsp = 0
1416 1416 self.indent_current = ' '* self.indent_current_nsp
1417 1417
1418 1418 except bdb.BdbQuit:
1419 1419 warn("The Python debugger has exited with a BdbQuit exception.\n"
1420 1420 "Because of how pdb handles the stack, it is impossible\n"
1421 1421 "for IPython to properly format this particular exception.\n"
1422 1422 "IPython will resume normal operation.")
1423 1423
1424 1424 # We are off again...
1425 1425 __builtin__.__dict__['__IPYTHON__active'] -= 1
1426 1426
1427 1427 def excepthook(self, type, value, tb):
1428 1428 """One more defense for GUI apps that call sys.excepthook.
1429 1429
1430 1430 GUI frameworks like wxPython trap exceptions and call
1431 1431 sys.excepthook themselves. I guess this is a feature that
1432 1432 enables them to keep running after exceptions that would
1433 1433 otherwise kill their mainloop. This is a bother for IPython
1434 1434 which excepts to catch all of the program exceptions with a try:
1435 1435 except: statement.
1436 1436
1437 1437 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1438 1438 any app directly invokes sys.excepthook, it will look to the user like
1439 1439 IPython crashed. In order to work around this, we can disable the
1440 1440 CrashHandler and replace it with this excepthook instead, which prints a
1441 1441 regular traceback using our InteractiveTB. In this fashion, apps which
1442 1442 call sys.excepthook will generate a regular-looking exception from
1443 1443 IPython, and the CrashHandler will only be triggered by real IPython
1444 1444 crashes.
1445 1445
1446 1446 This hook should be used sparingly, only in places which are not likely
1447 1447 to be true IPython errors.
1448 1448 """
1449 1449
1450 1450 self.InteractiveTB(type, value, tb, tb_offset=0)
1451 1451 if self.InteractiveTB.call_pdb and self.has_readline:
1452 1452 self.readline.set_completer(self.Completer.complete)
1453 1453
1454 1454 def call_alias(self,alias,rest=''):
1455 1455 """Call an alias given its name and the rest of the line.
1456 1456
1457 1457 This function MUST be given a proper alias, because it doesn't make
1458 1458 any checks when looking up into the alias table. The caller is
1459 1459 responsible for invoking it only with a valid alias."""
1460 1460
1461 1461 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1462 1462 nargs,cmd = self.alias_table[alias]
1463 1463 # Expand the %l special to be the user's input line
1464 1464 if cmd.find('%l') >= 0:
1465 1465 cmd = cmd.replace('%l',rest)
1466 1466 rest = ''
1467 1467 if nargs==0:
1468 1468 # Simple, argument-less aliases
1469 1469 cmd = '%s %s' % (cmd,rest)
1470 1470 else:
1471 1471 # Handle aliases with positional arguments
1472 1472 args = rest.split(None,nargs)
1473 1473 if len(args)< nargs:
1474 1474 error('Alias <%s> requires %s arguments, %s given.' %
1475 1475 (alias,nargs,len(args)))
1476 1476 return
1477 1477 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1478 1478 # Now call the macro, evaluating in the user's namespace
1479 1479 try:
1480 1480 self.system(cmd)
1481 1481 except:
1482 1482 self.showtraceback()
1483 1483
1484 1484 def autoindent_update(self,line):
1485 1485 """Keep track of the indent level."""
1486 1486 if self.autoindent:
1487 1487 if line:
1488 1488 ini_spaces = ini_spaces_re.match(line)
1489 1489 if ini_spaces:
1490 1490 nspaces = ini_spaces.end()
1491 1491 else:
1492 1492 nspaces = 0
1493 1493 self.indent_current_nsp = nspaces
1494 1494
1495 1495 if line[-1] == ':':
1496 1496 self.indent_current_nsp += 4
1497 1497 elif dedent_re.match(line):
1498 1498 self.indent_current_nsp -= 4
1499 1499 else:
1500 1500 self.indent_current_nsp = 0
1501 1501
1502 1502 # indent_current is the actual string to be inserted
1503 1503 # by the readline hooks for indentation
1504 1504 self.indent_current = ' '* self.indent_current_nsp
1505 1505
1506 1506 def runlines(self,lines):
1507 1507 """Run a string of one or more lines of source.
1508 1508
1509 1509 This method is capable of running a string containing multiple source
1510 1510 lines, as if they had been entered at the IPython prompt. Since it
1511 1511 exposes IPython's processing machinery, the given strings can contain
1512 1512 magic calls (%magic), special shell access (!cmd), etc."""
1513 1513
1514 1514 # We must start with a clean buffer, in case this is run from an
1515 1515 # interactive IPython session (via a magic, for example).
1516 1516 self.resetbuffer()
1517 1517 lines = lines.split('\n')
1518 1518 more = 0
1519 1519 for line in lines:
1520 1520 # skip blank lines so we don't mess up the prompt counter, but do
1521 1521 # NOT skip even a blank line if we are in a code block (more is
1522 1522 # true)
1523 1523 if line or more:
1524 1524 more = self.push(self.prefilter(line,more))
1525 1525 # IPython's runsource returns None if there was an error
1526 1526 # compiling the code. This allows us to stop processing right
1527 1527 # away, so the user gets the error message at the right place.
1528 1528 if more is None:
1529 1529 break
1530 1530 # final newline in case the input didn't have it, so that the code
1531 1531 # actually does get executed
1532 1532 if more:
1533 1533 self.push('\n')
1534 1534
1535 1535 def runsource(self, source, filename='<input>', symbol='single'):
1536 1536 """Compile and run some source in the interpreter.
1537 1537
1538 1538 Arguments are as for compile_command().
1539 1539
1540 1540 One several things can happen:
1541 1541
1542 1542 1) The input is incorrect; compile_command() raised an
1543 1543 exception (SyntaxError or OverflowError). A syntax traceback
1544 1544 will be printed by calling the showsyntaxerror() method.
1545 1545
1546 1546 2) The input is incomplete, and more input is required;
1547 1547 compile_command() returned None. Nothing happens.
1548 1548
1549 1549 3) The input is complete; compile_command() returned a code
1550 1550 object. The code is executed by calling self.runcode() (which
1551 1551 also handles run-time exceptions, except for SystemExit).
1552 1552
1553 1553 The return value is:
1554 1554
1555 1555 - True in case 2
1556 1556
1557 1557 - False in the other cases, unless an exception is raised, where
1558 1558 None is returned instead. This can be used by external callers to
1559 1559 know whether to continue feeding input or not.
1560 1560
1561 1561 The return value can be used to decide whether to use sys.ps1 or
1562 1562 sys.ps2 to prompt the next line."""
1563 1563
1564 1564 try:
1565 1565 code = self.compile(source,filename,symbol)
1566 1566 except (OverflowError, SyntaxError, ValueError):
1567 1567 # Case 1
1568 1568 self.showsyntaxerror(filename)
1569 1569 return None
1570 1570
1571 1571 if code is None:
1572 1572 # Case 2
1573 1573 return True
1574 1574
1575 1575 # Case 3
1576 1576 # We store the code object so that threaded shells and
1577 1577 # custom exception handlers can access all this info if needed.
1578 1578 # The source corresponding to this can be obtained from the
1579 1579 # buffer attribute as '\n'.join(self.buffer).
1580 1580 self.code_to_run = code
1581 1581 # now actually execute the code object
1582 1582 if self.runcode(code) == 0:
1583 1583 return False
1584 1584 else:
1585 1585 return None
1586 1586
1587 1587 def runcode(self,code_obj):
1588 1588 """Execute a code object.
1589 1589
1590 1590 When an exception occurs, self.showtraceback() is called to display a
1591 1591 traceback.
1592 1592
1593 1593 Return value: a flag indicating whether the code to be run completed
1594 1594 successfully:
1595 1595
1596 1596 - 0: successful execution.
1597 1597 - 1: an error occurred.
1598 1598 """
1599 1599
1600 1600 # Set our own excepthook in case the user code tries to call it
1601 1601 # directly, so that the IPython crash handler doesn't get triggered
1602 1602 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1603 1603
1604 1604 # we save the original sys.excepthook in the instance, in case config
1605 1605 # code (such as magics) needs access to it.
1606 1606 self.sys_excepthook = old_excepthook
1607 1607 outflag = 1 # happens in more places, so it's easier as default
1608 1608 try:
1609 1609 try:
1610 1610 # Embedded instances require separate global/local namespaces
1611 1611 # so they can see both the surrounding (local) namespace and
1612 1612 # the module-level globals when called inside another function.
1613 1613 if self.embedded:
1614 1614 exec code_obj in self.user_global_ns, self.user_ns
1615 1615 # Normal (non-embedded) instances should only have a single
1616 1616 # namespace for user code execution, otherwise functions won't
1617 1617 # see interactive top-level globals.
1618 1618 else:
1619 1619 exec code_obj in self.user_ns
1620 1620 finally:
1621 1621 # Reset our crash handler in place
1622 1622 sys.excepthook = old_excepthook
1623 1623 except SystemExit:
1624 1624 self.resetbuffer()
1625 1625 self.showtraceback()
1626 1626 warn("Type exit or quit to exit IPython "
1627 1627 "(%Exit or %Quit do so unconditionally).",level=1)
1628 1628 except self.custom_exceptions:
1629 1629 etype,value,tb = sys.exc_info()
1630 1630 self.CustomTB(etype,value,tb)
1631 1631 except:
1632 1632 self.showtraceback()
1633 1633 else:
1634 1634 outflag = 0
1635 1635 if softspace(sys.stdout, 0):
1636 1636 print
1637 1637 # Flush out code object which has been run (and source)
1638 1638 self.code_to_run = None
1639 1639 return outflag
1640 1640
1641 1641 def push(self, line):
1642 1642 """Push a line to the interpreter.
1643 1643
1644 1644 The line should not have a trailing newline; it may have
1645 1645 internal newlines. The line is appended to a buffer and the
1646 1646 interpreter's runsource() method is called with the
1647 1647 concatenated contents of the buffer as source. If this
1648 1648 indicates that the command was executed or invalid, the buffer
1649 1649 is reset; otherwise, the command is incomplete, and the buffer
1650 1650 is left as it was after the line was appended. The return
1651 1651 value is 1 if more input is required, 0 if the line was dealt
1652 1652 with in some way (this is the same as runsource()).
1653 1653 """
1654 1654
1655 1655 # autoindent management should be done here, and not in the
1656 1656 # interactive loop, since that one is only seen by keyboard input. We
1657 1657 # need this done correctly even for code run via runlines (which uses
1658 1658 # push).
1659 1659
1660 1660 #print 'push line: <%s>' % line # dbg
1661 1661 self.autoindent_update(line)
1662 1662
1663 1663 self.buffer.append(line)
1664 1664 more = self.runsource('\n'.join(self.buffer), self.filename)
1665 1665 if not more:
1666 1666 self.resetbuffer()
1667 1667 return more
1668 1668
1669 1669 def resetbuffer(self):
1670 1670 """Reset the input buffer."""
1671 1671 self.buffer[:] = []
1672 1672
1673 1673 def raw_input(self,prompt='',continue_prompt=False):
1674 1674 """Write a prompt and read a line.
1675 1675
1676 1676 The returned line does not include the trailing newline.
1677 1677 When the user enters the EOF key sequence, EOFError is raised.
1678 1678
1679 1679 Optional inputs:
1680 1680
1681 1681 - prompt(''): a string to be printed to prompt the user.
1682 1682
1683 1683 - continue_prompt(False): whether this line is the first one or a
1684 1684 continuation in a sequence of inputs.
1685 1685 """
1686 1686
1687 1687 line = raw_input_original(prompt)
1688 1688 # Try to be reasonably smart about not re-indenting pasted input more
1689 1689 # than necessary. We do this by trimming out the auto-indent initial
1690 1690 # spaces, if the user's actual input started itself with whitespace.
1691 1691 if self.autoindent:
1692 1692 line2 = line[self.indent_current_nsp:]
1693 1693 if line2[0:1] in (' ','\t'):
1694 1694 line = line2
1695 1695 return self.prefilter(line,continue_prompt)
1696 1696
1697 1697 def split_user_input(self,line):
1698 1698 """Split user input into pre-char, function part and rest."""
1699 1699
1700 1700 lsplit = self.line_split.match(line)
1701 1701 if lsplit is None: # no regexp match returns None
1702 1702 try:
1703 1703 iFun,theRest = line.split(None,1)
1704 1704 except ValueError:
1705 1705 iFun,theRest = line,''
1706 1706 pre = re.match('^(\s*)(.*)',line).groups()[0]
1707 1707 else:
1708 1708 pre,iFun,theRest = lsplit.groups()
1709 1709
1710 1710 #print 'line:<%s>' % line # dbg
1711 1711 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1712 1712 return pre,iFun.strip(),theRest
1713 1713
1714 1714 def _prefilter(self, line, continue_prompt):
1715 1715 """Calls different preprocessors, depending on the form of line."""
1716 1716
1717 1717 # All handlers *must* return a value, even if it's blank ('').
1718 1718
1719 1719 # Lines are NOT logged here. Handlers should process the line as
1720 1720 # needed, update the cache AND log it (so that the input cache array
1721 1721 # stays synced).
1722 1722
1723 1723 # This function is _very_ delicate, and since it's also the one which
1724 1724 # determines IPython's response to user input, it must be as efficient
1725 1725 # as possible. For this reason it has _many_ returns in it, trying
1726 1726 # always to exit as quickly as it can figure out what it needs to do.
1727 1727
1728 1728 # This function is the main responsible for maintaining IPython's
1729 1729 # behavior respectful of Python's semantics. So be _very_ careful if
1730 1730 # making changes to anything here.
1731 1731
1732 1732 #.....................................................................
1733 1733 # Code begins
1734 1734
1735 1735 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1736 1736
1737 1737 # save the line away in case we crash, so the post-mortem handler can
1738 1738 # record it
1739 1739 self._last_input_line = line
1740 1740
1741 1741 #print '***line: <%s>' % line # dbg
1742 1742
1743 1743 # the input history needs to track even empty lines
1744 1744 if not line.strip():
1745 1745 if not continue_prompt:
1746 1746 self.outputcache.prompt_count -= 1
1747 1747 return self.handle_normal(line,continue_prompt)
1748 1748 #return self.handle_normal('',continue_prompt)
1749 1749
1750 1750 # print '***cont',continue_prompt # dbg
1751 1751 # special handlers are only allowed for single line statements
1752 1752 if continue_prompt and not self.rc.multi_line_specials:
1753 1753 return self.handle_normal(line,continue_prompt)
1754 1754
1755 1755 # For the rest, we need the structure of the input
1756 1756 pre,iFun,theRest = self.split_user_input(line)
1757 1757 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1758 1758
1759 1759 # First check for explicit escapes in the last/first character
1760 1760 handler = None
1761 1761 if line[-1] == self.ESC_HELP:
1762 1762 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1763 1763 if handler is None:
1764 1764 # look at the first character of iFun, NOT of line, so we skip
1765 1765 # leading whitespace in multiline input
1766 1766 handler = self.esc_handlers.get(iFun[0:1])
1767 1767 if handler is not None:
1768 1768 return handler(line,continue_prompt,pre,iFun,theRest)
1769 1769 # Emacs ipython-mode tags certain input lines
1770 1770 if line.endswith('# PYTHON-MODE'):
1771 1771 return self.handle_emacs(line,continue_prompt)
1772 1772
1773 1773 # Next, check if we can automatically execute this thing
1774 1774
1775 1775 # Allow ! in multi-line statements if multi_line_specials is on:
1776 1776 if continue_prompt and self.rc.multi_line_specials and \
1777 1777 iFun.startswith(self.ESC_SHELL):
1778 1778 return self.handle_shell_escape(line,continue_prompt,
1779 1779 pre=pre,iFun=iFun,
1780 1780 theRest=theRest)
1781 1781
1782 1782 # Let's try to find if the input line is a magic fn
1783 1783 oinfo = None
1784 1784 if hasattr(self,'magic_'+iFun):
1785 1785 # WARNING: _ofind uses getattr(), so it can consume generators and
1786 1786 # cause other side effects.
1787 1787 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1788 1788 if oinfo['ismagic']:
1789 1789 # Be careful not to call magics when a variable assignment is
1790 1790 # being made (ls='hi', for example)
1791 1791 if self.rc.automagic and \
1792 1792 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1793 1793 (self.rc.multi_line_specials or not continue_prompt):
1794 1794 return self.handle_magic(line,continue_prompt,
1795 1795 pre,iFun,theRest)
1796 1796 else:
1797 1797 return self.handle_normal(line,continue_prompt)
1798 1798
1799 1799 # If the rest of the line begins with an (in)equality, assginment or
1800 1800 # function call, we should not call _ofind but simply execute it.
1801 1801 # This avoids spurious geattr() accesses on objects upon assignment.
1802 1802 #
1803 1803 # It also allows users to assign to either alias or magic names true
1804 1804 # python variables (the magic/alias systems always take second seat to
1805 1805 # true python code).
1806 1806 if theRest and theRest[0] in '!=()':
1807 1807 return self.handle_normal(line,continue_prompt)
1808 1808
1809 1809 if oinfo is None:
1810 1810 # let's try to ensure that _oinfo is ONLY called when autocall is
1811 1811 # on. Since it has inevitable potential side effects, at least
1812 1812 # having autocall off should be a guarantee to the user that no
1813 1813 # weird things will happen.
1814 1814
1815 1815 if self.rc.autocall:
1816 1816 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1817 1817 else:
1818 1818 # in this case, all that's left is either an alias or
1819 1819 # processing the line normally.
1820 1820 if iFun in self.alias_table:
1821 1821 return self.handle_alias(line,continue_prompt,
1822 1822 pre,iFun,theRest)
1823 1823 else:
1824 1824 return self.handle_normal(line,continue_prompt)
1825 1825
1826 1826 if not oinfo['found']:
1827 1827 return self.handle_normal(line,continue_prompt)
1828 1828 else:
1829 1829 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1830 1830 if oinfo['isalias']:
1831 1831 return self.handle_alias(line,continue_prompt,
1832 1832 pre,iFun,theRest)
1833 1833
1834 1834 if self.rc.autocall and \
1835 1835 not self.re_exclude_auto.match(theRest) and \
1836 1836 self.re_fun_name.match(iFun) and \
1837 1837 callable(oinfo['obj']) :
1838 1838 #print 'going auto' # dbg
1839 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1839 return self.handle_auto(line,continue_prompt,
1840 pre,iFun,theRest,oinfo['obj'])
1840 1841 else:
1841 1842 #print 'was callable?', callable(oinfo['obj']) # dbg
1842 1843 return self.handle_normal(line,continue_prompt)
1843 1844
1844 1845 # If we get here, we have a normal Python line. Log and return.
1845 1846 return self.handle_normal(line,continue_prompt)
1846 1847
1847 1848 def _prefilter_dumb(self, line, continue_prompt):
1848 1849 """simple prefilter function, for debugging"""
1849 1850 return self.handle_normal(line,continue_prompt)
1850 1851
1851 1852 # Set the default prefilter() function (this can be user-overridden)
1852 1853 prefilter = _prefilter
1853 1854
1854 1855 def handle_normal(self,line,continue_prompt=None,
1855 1856 pre=None,iFun=None,theRest=None):
1856 1857 """Handle normal input lines. Use as a template for handlers."""
1857 1858
1858 1859 # With autoindent on, we need some way to exit the input loop, and I
1859 1860 # don't want to force the user to have to backspace all the way to
1860 1861 # clear the line. The rule will be in this case, that either two
1861 1862 # lines of pure whitespace in a row, or a line of pure whitespace but
1862 1863 # of a size different to the indent level, will exit the input loop.
1863 1864
1864 1865 if (continue_prompt and self.autoindent and isspace(line) and
1865 1866 (line != self.indent_current or isspace(self.buffer[-1]))):
1866 1867 line = ''
1867 1868
1868 1869 self.log(line,continue_prompt)
1869 1870 return line
1870 1871
1871 1872 def handle_alias(self,line,continue_prompt=None,
1872 1873 pre=None,iFun=None,theRest=None):
1873 1874 """Handle alias input lines. """
1874 1875
1875 1876 # pre is needed, because it carries the leading whitespace. Otherwise
1876 1877 # aliases won't work in indented sections.
1877 1878 line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest))
1878 1879 self.log(line_out,continue_prompt)
1879 1880 return line_out
1880 1881
1881 1882 def handle_shell_escape(self, line, continue_prompt=None,
1882 1883 pre=None,iFun=None,theRest=None):
1883 1884 """Execute the line in a shell, empty return value"""
1884 1885
1885 1886 #print 'line in :', `line` # dbg
1886 1887 # Example of a special handler. Others follow a similar pattern.
1887 1888 if continue_prompt: # multi-line statements
1888 1889 if iFun.startswith('!!'):
1889 1890 print 'SyntaxError: !! is not allowed in multiline statements'
1890 1891 return pre
1891 1892 else:
1892 1893 cmd = ("%s %s" % (iFun[1:],theRest))
1893 1894 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_")
1894 1895 else: # single-line input
1895 1896 if line.startswith('!!'):
1896 1897 # rewrite iFun/theRest to properly hold the call to %sx and
1897 1898 # the actual command to be executed, so handle_magic can work
1898 1899 # correctly
1899 1900 theRest = '%s %s' % (iFun[2:],theRest)
1900 1901 iFun = 'sx'
1901 1902 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1902 1903 continue_prompt,pre,iFun,theRest)
1903 1904 else:
1904 1905 cmd=line[1:]
1905 1906 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_")
1906 1907 # update cache/log and return
1907 1908 self.log(line_out,continue_prompt)
1908 1909 return line_out
1909 1910
1910 1911 def handle_magic(self, line, continue_prompt=None,
1911 1912 pre=None,iFun=None,theRest=None):
1912 1913 """Execute magic functions.
1913 1914
1914 1915 Also log them with a prepended # so the log is clean Python."""
1915 1916
1916 1917 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1917 1918 self.log(cmd,continue_prompt)
1918 1919 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1919 1920 return cmd
1920 1921
1921 1922 def handle_auto(self, line, continue_prompt=None,
1922 pre=None,iFun=None,theRest=None):
1923 pre=None,iFun=None,theRest=None,obj=None):
1923 1924 """Hande lines which can be auto-executed, quoting if requested."""
1924 1925
1925 1926 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1926 1927
1927 1928 # This should only be active for single-line input!
1928 1929 if continue_prompt:
1930 self.log(line,continue_prompt)
1929 1931 return line
1930 1932
1933 auto_rewrite = True
1931 1934 if pre == self.ESC_QUOTE:
1932 1935 # Auto-quote splitting on whitespace
1933 1936 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1934 1937 elif pre == self.ESC_QUOTE2:
1935 1938 # Auto-quote whole string
1936 1939 newcmd = '%s("%s")' % (iFun,theRest)
1937 1940 else:
1938 # Auto-paren
1939 if theRest[0:1] in ('=','['):
1940 # Don't autocall in these cases. They can be either
1941 # rebindings of an existing callable's name, or item access
1942 # for an object which is BOTH callable and implements
1943 # __getitem__.
1944 return '%s %s' % (iFun,theRest)
1945 if theRest.endswith(';'):
1941 # Auto-paren.
1942 # We only apply it to argument-less calls if the autocall
1943 # parameter is set to 2. We only need to check that autocall is <
1944 # 2, since this function isn't called unless it's at least 1.
1945 if not theRest and self.rc.autocall < 2:
1946 newcmd = '%s %s' % (iFun,theRest)
1947 auto_rewrite = False
1948 else:
1949 if theRest.startswith('['):
1950 if hasattr(obj,'__getitem__'):
1951 # Don't autocall in this case: item access for an object
1952 # which is BOTH callable and implements __getitem__.
1953 newcmd = '%s %s' % (iFun,theRest)
1954 auto_rewrite = False
1955 else:
1956 # if the object doesn't support [] access, go ahead and
1957 # autocall
1958 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1959 elif theRest.endswith(';'):
1946 1960 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1947 1961 else:
1948 1962 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1949 1963
1964 if auto_rewrite:
1950 1965 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1951 1966 # log what is now valid Python, not the actual user input (without the
1952 1967 # final newline)
1953 1968 self.log(newcmd,continue_prompt)
1954 1969 return newcmd
1955 1970
1956 1971 def handle_help(self, line, continue_prompt=None,
1957 1972 pre=None,iFun=None,theRest=None):
1958 1973 """Try to get some help for the object.
1959 1974
1960 1975 obj? or ?obj -> basic information.
1961 1976 obj?? or ??obj -> more details.
1962 1977 """
1963 1978
1964 1979 # We need to make sure that we don't process lines which would be
1965 1980 # otherwise valid python, such as "x=1 # what?"
1966 1981 try:
1967 1982 codeop.compile_command(line)
1968 1983 except SyntaxError:
1969 1984 # We should only handle as help stuff which is NOT valid syntax
1970 1985 if line[0]==self.ESC_HELP:
1971 1986 line = line[1:]
1972 1987 elif line[-1]==self.ESC_HELP:
1973 1988 line = line[:-1]
1974 1989 self.log('#?'+line)
1975 1990 if line:
1976 1991 self.magic_pinfo(line)
1977 1992 else:
1978 1993 page(self.usage,screen_lines=self.rc.screen_length)
1979 1994 return '' # Empty string is needed here!
1980 1995 except:
1981 1996 # Pass any other exceptions through to the normal handler
1982 1997 return self.handle_normal(line,continue_prompt)
1983 1998 else:
1984 1999 # If the code compiles ok, we should handle it normally
1985 2000 return self.handle_normal(line,continue_prompt)
1986 2001
1987 2002 def handle_emacs(self,line,continue_prompt=None,
1988 2003 pre=None,iFun=None,theRest=None):
1989 2004 """Handle input lines marked by python-mode."""
1990 2005
1991 2006 # Currently, nothing is done. Later more functionality can be added
1992 2007 # here if needed.
1993 2008
1994 2009 # The input cache shouldn't be updated
1995 2010
1996 2011 return line
1997 2012
1998 2013 def mktempfile(self,data=None):
1999 2014 """Make a new tempfile and return its filename.
2000 2015
2001 2016 This makes a call to tempfile.mktemp, but it registers the created
2002 2017 filename internally so ipython cleans it up at exit time.
2003 2018
2004 2019 Optional inputs:
2005 2020
2006 2021 - data(None): if data is given, it gets written out to the temp file
2007 2022 immediately, and the file is closed again."""
2008 2023
2009 2024 filename = tempfile.mktemp('.py')
2010 2025 self.tempfiles.append(filename)
2011 2026
2012 2027 if data:
2013 2028 tmp_file = open(filename,'w')
2014 2029 tmp_file.write(data)
2015 2030 tmp_file.close()
2016 2031 return filename
2017 2032
2018 2033 def write(self,data):
2019 2034 """Write a string to the default output"""
2020 2035 Term.cout.write(data)
2021 2036
2022 2037 def write_err(self,data):
2023 2038 """Write a string to the default error output"""
2024 2039 Term.cerr.write(data)
2025 2040
2026 2041 def exit(self):
2027 2042 """Handle interactive exit.
2028 2043
2029 2044 This method sets the exit_now attribute."""
2030 2045
2031 2046 if self.rc.confirm_exit:
2032 2047 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2033 2048 self.exit_now = True
2034 2049 else:
2035 2050 self.exit_now = True
2036 2051 return self.exit_now
2037 2052
2038 2053 def safe_execfile(self,fname,*where,**kw):
2039 2054 fname = os.path.expanduser(fname)
2040 2055
2041 2056 # find things also in current directory
2042 2057 dname = os.path.dirname(fname)
2043 2058 if not sys.path.count(dname):
2044 2059 sys.path.append(dname)
2045 2060
2046 2061 try:
2047 2062 xfile = open(fname)
2048 2063 except:
2049 2064 print >> Term.cerr, \
2050 2065 'Could not open file <%s> for safe execution.' % fname
2051 2066 return None
2052 2067
2053 2068 kw.setdefault('islog',0)
2054 2069 kw.setdefault('quiet',1)
2055 2070 kw.setdefault('exit_ignore',0)
2056 2071 first = xfile.readline()
2057 2072 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2058 2073 xfile.close()
2059 2074 # line by line execution
2060 2075 if first.startswith(loghead) or kw['islog']:
2061 2076 print 'Loading log file <%s> one line at a time...' % fname
2062 2077 if kw['quiet']:
2063 2078 stdout_save = sys.stdout
2064 2079 sys.stdout = StringIO.StringIO()
2065 2080 try:
2066 2081 globs,locs = where[0:2]
2067 2082 except:
2068 2083 try:
2069 2084 globs = locs = where[0]
2070 2085 except:
2071 2086 globs = locs = globals()
2072 2087 badblocks = []
2073 2088
2074 2089 # we also need to identify indented blocks of code when replaying
2075 2090 # logs and put them together before passing them to an exec
2076 2091 # statement. This takes a bit of regexp and look-ahead work in the
2077 2092 # file. It's easiest if we swallow the whole thing in memory
2078 2093 # first, and manually walk through the lines list moving the
2079 2094 # counter ourselves.
2080 2095 indent_re = re.compile('\s+\S')
2081 2096 xfile = open(fname)
2082 2097 filelines = xfile.readlines()
2083 2098 xfile.close()
2084 2099 nlines = len(filelines)
2085 2100 lnum = 0
2086 2101 while lnum < nlines:
2087 2102 line = filelines[lnum]
2088 2103 lnum += 1
2089 2104 # don't re-insert logger status info into cache
2090 2105 if line.startswith('#log#'):
2091 2106 continue
2092 2107 else:
2093 2108 # build a block of code (maybe a single line) for execution
2094 2109 block = line
2095 2110 try:
2096 2111 next = filelines[lnum] # lnum has already incremented
2097 2112 except:
2098 2113 next = None
2099 2114 while next and indent_re.match(next):
2100 2115 block += next
2101 2116 lnum += 1
2102 2117 try:
2103 2118 next = filelines[lnum]
2104 2119 except:
2105 2120 next = None
2106 2121 # now execute the block of one or more lines
2107 2122 try:
2108 2123 exec block in globs,locs
2109 2124 except SystemExit:
2110 2125 pass
2111 2126 except:
2112 2127 badblocks.append(block.rstrip())
2113 2128 if kw['quiet']: # restore stdout
2114 2129 sys.stdout.close()
2115 2130 sys.stdout = stdout_save
2116 2131 print 'Finished replaying log file <%s>' % fname
2117 2132 if badblocks:
2118 2133 print >> sys.stderr, ('\nThe following lines/blocks in file '
2119 2134 '<%s> reported errors:' % fname)
2120 2135
2121 2136 for badline in badblocks:
2122 2137 print >> sys.stderr, badline
2123 2138 else: # regular file execution
2124 2139 try:
2125 2140 execfile(fname,*where)
2126 2141 except SyntaxError:
2127 2142 etype,evalue = sys.exc_info()[:2]
2128 2143 self.SyntaxTB(etype,evalue,[])
2129 2144 warn('Failure executing file: <%s>' % fname)
2130 2145 except SystemExit,status:
2131 2146 if not kw['exit_ignore']:
2132 2147 self.InteractiveTB()
2133 2148 warn('Failure executing file: <%s>' % fname)
2134 2149 except:
2135 2150 self.InteractiveTB()
2136 2151 warn('Failure executing file: <%s>' % fname)
2137 2152
2138 2153 #************************* end of file <iplib.py> *****************************
@@ -1,701 +1,701 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 967 2005-12-29 09:02:13Z fperez $"""
9 $Id: ipmaker.py 990 2006-01-04 06:59:02Z fperez $"""
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #*****************************************************************************
17 17
18 18 from IPython import Release
19 19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 20 __license__ = Release.license
21 21 __version__ = Release.version
22 22
23 23 credits._Printer__data = """
24 24 Python: %s
25 25
26 26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 27 See http://ipython.scipy.org for more information.""" \
28 28 % credits._Printer__data
29 29
30 30 copyright._Printer__data += """
31 31
32 32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 33 All Rights Reserved."""
34 34
35 35 #****************************************************************************
36 36 # Required modules
37 37
38 38 # From the standard library
39 39 import __main__
40 40 import __builtin__
41 41 import os
42 42 import re
43 43 import sys
44 44 import types
45 45 from pprint import pprint,pformat
46 46
47 47 # Our own
48 48 from IPython import DPyGetOpt
49 49 from IPython.Struct import Struct
50 50 from IPython.OutputTrap import OutputTrap
51 51 from IPython.ConfigLoader import ConfigLoader
52 52 from IPython.iplib import InteractiveShell
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 = os.path.abspath(os.environ.get('IPYTHONDIR',
128 128 os.path.join(IP.home_dir,ipdir_def)))
129 129
130 130 # we need the directory where IPython itself is installed
131 131 import IPython
132 132 IPython_dir = os.path.dirname(IPython.__file__)
133 133 del IPython
134 134
135 135 #-------------------------------------------------------------------------
136 136 # Command line handling
137 137
138 138 # Valid command line options (uses DPyGetOpt syntax, like Perl's
139 139 # GetOpt::Long)
140 140
141 141 # Any key not listed here gets deleted even if in the file (like session
142 142 # or profile). That's deliberate, to maintain the rc namespace clean.
143 143
144 144 # Each set of options appears twice: under _conv only the names are
145 145 # listed, indicating which type they must be converted to when reading the
146 146 # ipythonrc file. And under DPyGetOpt they are listed with the regular
147 147 # DPyGetOpt syntax (=s,=i,:f,etc).
148 148
149 149 # Make sure there's a space before each end of line (they get auto-joined!)
150 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
150 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
151 151 'c=s classic|cl color_info! colors=s confirm_exit! '
152 152 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
153 153 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
154 154 'quick screen_length|sl=i prompts_pad_left=i '
155 155 'logfile|lf=s logplay|lp=s profile|p=s '
156 156 'readline! readline_merge_completions! '
157 157 'readline_omit__names! '
158 158 'rcfile=s separate_in|si=s separate_out|so=s '
159 159 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
160 160 'magic_docstrings system_verbose! '
161 161 'multi_line_specials! '
162 162 'autoedit_syntax!')
163 163
164 164 # Options that can *only* appear at the cmd line (not in rcfiles).
165 165
166 166 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
167 167 # the 'C-c !' command in emacs automatically appends a -i option at the end.
168 168 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
169 169 'gthread! qthread! wthread! pylab! tk!')
170 170
171 171 # Build the actual name list to be used by DPyGetOpt
172 172 opts_names = qw(cmdline_opts) + qw(cmdline_only)
173 173
174 174 # Set sensible command line defaults.
175 175 # This should have everything from cmdline_opts and cmdline_only
176 176 opts_def = Struct(autocall = 1,
177 177 autoedit_syntax = 1,
178 178 autoindent=0,
179 179 automagic = 1,
180 180 banner = 1,
181 181 cache_size = 1000,
182 182 c = '',
183 183 classic = 0,
184 184 colors = 'NoColor',
185 185 color_info = 0,
186 186 confirm_exit = 1,
187 187 debug = 0,
188 188 deep_reload = 0,
189 189 editor = '0',
190 190 help = 0,
191 191 ignore = 0,
192 192 ipythondir = ipythondir,
193 193 log = 0,
194 194 logfile = '',
195 195 logplay = '',
196 196 multi_line_specials = 1,
197 197 messages = 1,
198 198 nosep = 0,
199 199 pdb = 0,
200 200 pprint = 0,
201 201 profile = '',
202 202 prompt_in1 = 'In [\\#]: ',
203 203 prompt_in2 = ' .\\D.: ',
204 204 prompt_out = 'Out[\\#]: ',
205 205 prompts_pad_left = 1,
206 206 quick = 0,
207 207 readline = 1,
208 208 readline_merge_completions = 1,
209 209 readline_omit__names = 0,
210 210 rcfile = 'ipythonrc' + rc_suffix,
211 211 screen_length = 0,
212 212 separate_in = '\n',
213 213 separate_out = '\n',
214 214 separate_out2 = '',
215 215 system_verbose = 0,
216 216 gthread = 0,
217 217 qthread = 0,
218 218 wthread = 0,
219 219 pylab = 0,
220 220 tk = 0,
221 221 upgrade = 0,
222 222 Version = 0,
223 223 xmode = 'Verbose',
224 224 wildcards_case_sensitive = 1,
225 225 magic_docstrings = 0, # undocumented, for doc generation
226 226 )
227 227
228 228 # Things that will *only* appear in rcfiles (not at the command line).
229 229 # Make sure there's a space before each end of line (they get auto-joined!)
230 230 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
231 231 qw_lol: 'import_some ',
232 232 # for things with embedded whitespace:
233 233 list_strings:'execute alias readline_parse_and_bind ',
234 234 # Regular strings need no conversion:
235 235 None:'readline_remove_delims ',
236 236 }
237 237 # Default values for these
238 238 rc_def = Struct(include = [],
239 239 import_mod = [],
240 240 import_all = [],
241 241 import_some = [[]],
242 242 execute = [],
243 243 execfile = [],
244 244 alias = [],
245 245 readline_parse_and_bind = [],
246 246 readline_remove_delims = '',
247 247 )
248 248
249 249 # Build the type conversion dictionary from the above tables:
250 250 typeconv = rcfile_opts.copy()
251 251 typeconv.update(optstr2types(cmdline_opts))
252 252
253 253 # FIXME: the None key appears in both, put that back together by hand. Ugly!
254 254 typeconv[None] += ' ' + rcfile_opts[None]
255 255
256 256 # Remove quotes at ends of all strings (used to protect spaces)
257 257 typeconv[unquote_ends] = typeconv[None]
258 258 del typeconv[None]
259 259
260 260 # Build the list we'll use to make all config decisions with defaults:
261 261 opts_all = opts_def.copy()
262 262 opts_all.update(rc_def)
263 263
264 264 # Build conflict resolver for recursive loading of config files:
265 265 # - preserve means the outermost file maintains the value, it is not
266 266 # overwritten if an included file has the same key.
267 267 # - add_flip applies + to the two values, so it better make sense to add
268 268 # those types of keys. But it flips them first so that things loaded
269 269 # deeper in the inclusion chain have lower precedence.
270 270 conflict = {'preserve': ' '.join([ typeconv[int],
271 271 typeconv[unquote_ends] ]),
272 272 'add_flip': ' '.join([ typeconv[qwflat],
273 273 typeconv[qw_lol],
274 274 typeconv[list_strings] ])
275 275 }
276 276
277 277 # Now actually process the command line
278 278 getopt = DPyGetOpt.DPyGetOpt()
279 279 getopt.setIgnoreCase(0)
280 280
281 281 getopt.parseConfiguration(opts_names)
282 282
283 283 try:
284 284 getopt.processArguments(argv)
285 285 except:
286 286 print cmd_line_usage
287 287 warn('\nError in Arguments: ' + `sys.exc_value`)
288 288 sys.exit(1)
289 289
290 290 # convert the options dict to a struct for much lighter syntax later
291 291 opts = Struct(getopt.optionValues)
292 292 args = getopt.freeValues
293 293
294 294 # this is the struct (which has default values at this point) with which
295 295 # we make all decisions:
296 296 opts_all.update(opts)
297 297
298 298 # Options that force an immediate exit
299 299 if opts_all.help:
300 300 page(cmd_line_usage)
301 301 sys.exit()
302 302
303 303 if opts_all.Version:
304 304 print __version__
305 305 sys.exit()
306 306
307 307 if opts_all.magic_docstrings:
308 308 IP.magic_magic('-latex')
309 309 sys.exit()
310 310
311 311 # Create user config directory if it doesn't exist. This must be done
312 312 # *after* getting the cmd line options.
313 313 if not os.path.isdir(opts_all.ipythondir):
314 314 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
315 315
316 316 # upgrade user config files while preserving a copy of the originals
317 317 if opts_all.upgrade:
318 318 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
319 319
320 320 # check mutually exclusive options in the *original* command line
321 321 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
322 322 qw('classic profile'),qw('classic rcfile')])
323 323
324 324 #---------------------------------------------------------------------------
325 325 # Log replay
326 326
327 327 # if -logplay, we need to 'become' the other session. That basically means
328 328 # replacing the current command line environment with that of the old
329 329 # session and moving on.
330 330
331 331 # this is needed so that later we know we're in session reload mode, as
332 332 # opts_all will get overwritten:
333 333 load_logplay = 0
334 334
335 335 if opts_all.logplay:
336 336 load_logplay = opts_all.logplay
337 337 opts_debug_save = opts_all.debug
338 338 try:
339 339 logplay = open(opts_all.logplay)
340 340 except IOError:
341 341 if opts_all.debug: IP.InteractiveTB()
342 342 warn('Could not open logplay file '+`opts_all.logplay`)
343 343 # restore state as if nothing had happened and move on, but make
344 344 # sure that later we don't try to actually load the session file
345 345 logplay = None
346 346 load_logplay = 0
347 347 del opts_all.logplay
348 348 else:
349 349 try:
350 350 logplay.readline()
351 351 logplay.readline();
352 352 # this reloads that session's command line
353 353 cmd = logplay.readline()[6:]
354 354 exec cmd
355 355 # restore the true debug flag given so that the process of
356 356 # session loading itself can be monitored.
357 357 opts.debug = opts_debug_save
358 358 # save the logplay flag so later we don't overwrite the log
359 359 opts.logplay = load_logplay
360 360 # now we must update our own structure with defaults
361 361 opts_all.update(opts)
362 362 # now load args
363 363 cmd = logplay.readline()[6:]
364 364 exec cmd
365 365 logplay.close()
366 366 except:
367 367 logplay.close()
368 368 if opts_all.debug: IP.InteractiveTB()
369 369 warn("Logplay file lacking full configuration information.\n"
370 370 "I'll try to read it, but some things may not work.")
371 371
372 372 #-------------------------------------------------------------------------
373 373 # set up output traps: catch all output from files, being run, modules
374 374 # loaded, etc. Then give it to the user in a clean form at the end.
375 375
376 376 msg_out = 'Output messages. '
377 377 msg_err = 'Error messages. '
378 378 msg_sep = '\n'
379 379 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
380 380 msg_err,msg_sep,debug,
381 381 quiet_out=1),
382 382 user_exec = OutputTrap('User File Execution',msg_out,
383 383 msg_err,msg_sep,debug),
384 384 logplay = OutputTrap('Log Loader',msg_out,
385 385 msg_err,msg_sep,debug),
386 386 summary = ''
387 387 )
388 388
389 389 #-------------------------------------------------------------------------
390 390 # Process user ipythonrc-type configuration files
391 391
392 392 # turn on output trapping and log to msg.config
393 393 # remember that with debug on, trapping is actually disabled
394 394 msg.config.trap_all()
395 395
396 396 # look for rcfile in current or default directory
397 397 try:
398 398 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
399 399 except IOError:
400 400 if opts_all.debug: IP.InteractiveTB()
401 401 warn('Configuration file %s not found. Ignoring request.'
402 402 % (opts_all.rcfile) )
403 403
404 404 # 'profiles' are a shorthand notation for config filenames
405 405 if opts_all.profile:
406 406 try:
407 407 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
408 408 + rc_suffix,
409 409 opts_all.ipythondir)
410 410 except IOError:
411 411 if opts_all.debug: IP.InteractiveTB()
412 412 opts.profile = '' # remove profile from options if invalid
413 413 warn('Profile configuration file %s not found. Ignoring request.'
414 414 % (opts_all.profile) )
415 415
416 416 # load the config file
417 417 rcfiledata = None
418 418 if opts_all.quick:
419 419 print 'Launching IPython in quick mode. No config file read.'
420 420 elif opts_all.classic:
421 421 print 'Launching IPython in classic mode. No config file read.'
422 422 elif opts_all.rcfile:
423 423 try:
424 424 cfg_loader = ConfigLoader(conflict)
425 425 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
426 426 'include',opts_all.ipythondir,
427 427 purge = 1,
428 428 unique = conflict['preserve'])
429 429 except:
430 430 IP.InteractiveTB()
431 431 warn('Problems loading configuration file '+
432 432 `opts_all.rcfile`+
433 433 '\nStarting with default -bare bones- configuration.')
434 434 else:
435 435 warn('No valid configuration file found in either currrent directory\n'+
436 436 'or in the IPython config. directory: '+`opts_all.ipythondir`+
437 437 '\nProceeding with internal defaults.')
438 438
439 439 #------------------------------------------------------------------------
440 440 # Set exception handlers in mode requested by user.
441 441 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
442 442 IP.magic_xmode(opts_all.xmode)
443 443 otrap.release_out()
444 444
445 445 #------------------------------------------------------------------------
446 446 # Execute user config
447 447
448 448 # Create a valid config structure with the right precedence order:
449 449 # defaults < rcfile < command line. This needs to be in the instance, so
450 450 # that method calls below that rely on it find it.
451 451 IP.rc = rc_def.copy()
452 452
453 453 # Work with a local alias inside this routine to avoid unnecessary
454 454 # attribute lookups.
455 455 IP_rc = IP.rc
456 456
457 457 IP_rc.update(opts_def)
458 458 if rcfiledata:
459 459 # now we can update
460 460 IP_rc.update(rcfiledata)
461 461 IP_rc.update(opts)
462 462 IP_rc.update(rc_override)
463 463
464 464 # Store the original cmd line for reference:
465 465 IP_rc.opts = opts
466 466 IP_rc.args = args
467 467
468 468 # create a *runtime* Struct like rc for holding parameters which may be
469 469 # created and/or modified by runtime user extensions.
470 470 IP.runtime_rc = Struct()
471 471
472 472 # from this point on, all config should be handled through IP_rc,
473 473 # opts* shouldn't be used anymore.
474 474
475 475 # add personal .ipython dir to sys.path so that users can put things in
476 476 # there for customization
477 477 sys.path.append(IP_rc.ipythondir)
478 478 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
479 479
480 480 # update IP_rc with some special things that need manual
481 481 # tweaks. Basically options which affect other options. I guess this
482 482 # should just be written so that options are fully orthogonal and we
483 483 # wouldn't worry about this stuff!
484 484
485 485 if IP_rc.classic:
486 486 IP_rc.quick = 1
487 487 IP_rc.cache_size = 0
488 488 IP_rc.pprint = 0
489 489 IP_rc.prompt_in1 = '>>> '
490 490 IP_rc.prompt_in2 = '... '
491 491 IP_rc.prompt_out = ''
492 492 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
493 493 IP_rc.colors = 'NoColor'
494 494 IP_rc.xmode = 'Plain'
495 495
496 496 # configure readline
497 497 # Define the history file for saving commands in between sessions
498 498 if IP_rc.profile:
499 499 histfname = 'history-%s' % IP_rc.profile
500 500 else:
501 501 histfname = 'history'
502 502 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
503 503
504 504 # update exception handlers with rc file status
505 505 otrap.trap_out() # I don't want these messages ever.
506 506 IP.magic_xmode(IP_rc.xmode)
507 507 otrap.release_out()
508 508
509 509 # activate logging if requested and not reloading a log
510 510 if IP_rc.logplay:
511 511 IP.magic_logstart(IP_rc.logplay + ' append')
512 512 elif IP_rc.logfile:
513 513 IP.magic_logstart(IP_rc.logfile)
514 514 elif IP_rc.log:
515 515 IP.magic_logstart()
516 516
517 517 # find user editor so that it we don't have to look it up constantly
518 518 if IP_rc.editor.strip()=='0':
519 519 try:
520 520 ed = os.environ['EDITOR']
521 521 except KeyError:
522 522 if os.name == 'posix':
523 523 ed = 'vi' # the only one guaranteed to be there!
524 524 else:
525 525 ed = 'notepad' # same in Windows!
526 526 IP_rc.editor = ed
527 527
528 528 # Keep track of whether this is an embedded instance or not (useful for
529 529 # post-mortems).
530 530 IP_rc.embedded = IP.embedded
531 531
532 532 # Recursive reload
533 533 try:
534 534 from IPython import deep_reload
535 535 if IP_rc.deep_reload:
536 536 __builtin__.reload = deep_reload.reload
537 537 else:
538 538 __builtin__.dreload = deep_reload.reload
539 539 del deep_reload
540 540 except ImportError:
541 541 pass
542 542
543 543 # Save the current state of our namespace so that the interactive shell
544 544 # can later know which variables have been created by us from config files
545 545 # and loading. This way, loading a file (in any way) is treated just like
546 546 # defining things on the command line, and %who works as expected.
547 547
548 548 # DON'T do anything that affects the namespace beyond this point!
549 549 IP.internal_ns.update(__main__.__dict__)
550 550
551 551 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
552 552
553 553 # Now run through the different sections of the users's config
554 554 if IP_rc.debug:
555 555 print 'Trying to execute the following configuration structure:'
556 556 print '(Things listed first are deeper in the inclusion tree and get'
557 557 print 'loaded first).\n'
558 558 pprint(IP_rc.__dict__)
559 559
560 560 for mod in IP_rc.import_mod:
561 561 try:
562 562 exec 'import '+mod in IP.user_ns
563 563 except :
564 564 IP.InteractiveTB()
565 565 import_fail_info(mod)
566 566
567 567 for mod_fn in IP_rc.import_some:
568 568 if mod_fn == []: break
569 569 mod,fn = mod_fn[0],','.join(mod_fn[1:])
570 570 try:
571 571 exec 'from '+mod+' import '+fn in IP.user_ns
572 572 except :
573 573 IP.InteractiveTB()
574 574 import_fail_info(mod,fn)
575 575
576 576 for mod in IP_rc.import_all:
577 577 try:
578 578 exec 'from '+mod+' import *' in IP.user_ns
579 579 except :
580 580 IP.InteractiveTB()
581 581 import_fail_info(mod)
582 582
583 583 for code in IP_rc.execute:
584 584 try:
585 585 exec code in IP.user_ns
586 586 except:
587 587 IP.InteractiveTB()
588 588 warn('Failure executing code: ' + `code`)
589 589
590 590 # Execute the files the user wants in ipythonrc
591 591 for file in IP_rc.execfile:
592 592 try:
593 593 file = filefind(file,sys.path+[IPython_dir])
594 594 except IOError:
595 595 warn(itpl('File $file not found. Skipping it.'))
596 596 else:
597 597 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
598 598
599 599 # release stdout and stderr and save config log into a global summary
600 600 msg.config.release_all()
601 601 if IP_rc.messages:
602 602 msg.summary += msg.config.summary_all()
603 603
604 604 #------------------------------------------------------------------------
605 605 # Setup interactive session
606 606
607 607 # Now we should be fully configured. We can then execute files or load
608 608 # things only needed for interactive use. Then we'll open the shell.
609 609
610 610 # Take a snapshot of the user namespace before opening the shell. That way
611 611 # we'll be able to identify which things were interactively defined and
612 612 # which were defined through config files.
613 613 IP.user_config_ns = IP.user_ns.copy()
614 614
615 615 # Force reading a file as if it were a session log. Slower but safer.
616 616 if load_logplay:
617 617 print 'Replaying log...'
618 618 try:
619 619 if IP_rc.debug:
620 620 logplay_quiet = 0
621 621 else:
622 622 logplay_quiet = 1
623 623
624 624 msg.logplay.trap_all()
625 625 IP.safe_execfile(load_logplay,IP.user_ns,
626 626 islog = 1, quiet = logplay_quiet)
627 627 msg.logplay.release_all()
628 628 if IP_rc.messages:
629 629 msg.summary += msg.logplay.summary_all()
630 630 except:
631 631 warn('Problems replaying logfile %s.' % load_logplay)
632 632 IP.InteractiveTB()
633 633
634 634 # Load remaining files in command line
635 635 msg.user_exec.trap_all()
636 636
637 637 # Do NOT execute files named in the command line as scripts to be loaded
638 638 # by embedded instances. Doing so has the potential for an infinite
639 639 # recursion if there are exceptions thrown in the process.
640 640
641 641 # XXX FIXME: the execution of user files should be moved out to after
642 642 # ipython is fully initialized, just as if they were run via %run at the
643 643 # ipython prompt. This would also give them the benefit of ipython's
644 644 # nice tracebacks.
645 645
646 646 if not embedded and IP_rc.args:
647 647 name_save = IP.user_ns['__name__']
648 648 IP.user_ns['__name__'] = '__main__'
649 649 try:
650 650 # Set our own excepthook in case the user code tries to call it
651 651 # directly. This prevents triggering the IPython crash handler.
652 652 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
653 653 for run in args:
654 654 IP.safe_execfile(run,IP.user_ns)
655 655 finally:
656 656 # Reset our crash handler in place
657 657 sys.excepthook = old_excepthook
658 658
659 659 IP.user_ns['__name__'] = name_save
660 660
661 661 msg.user_exec.release_all()
662 662 if IP_rc.messages:
663 663 msg.summary += msg.user_exec.summary_all()
664 664
665 665 # since we can't specify a null string on the cmd line, 0 is the equivalent:
666 666 if IP_rc.nosep:
667 667 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
668 668 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
669 669 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
670 670 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
671 671 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
672 672 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
673 673 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
674 674
675 675 # Determine how many lines at the bottom of the screen are needed for
676 676 # showing prompts, so we can know wheter long strings are to be printed or
677 677 # paged:
678 678 num_lines_bot = IP_rc.separate_in.count('\n')+1
679 679 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
680 680
681 681 # configure startup banner
682 682 if IP_rc.c: # regular python doesn't print the banner with -c
683 683 IP_rc.banner = 0
684 684 if IP_rc.banner:
685 685 BANN_P = IP.BANNER_PARTS
686 686 else:
687 687 BANN_P = []
688 688
689 689 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
690 690
691 691 # add message log (possibly empty)
692 692 if msg.summary: BANN_P.append(msg.summary)
693 693 # Final banner is a string
694 694 IP.BANNER = '\n'.join(BANN_P)
695 695
696 696 # Finalize the IPython instance. This assumes the rc structure is fully
697 697 # in place.
698 698 IP.post_config_initialization()
699 699
700 700 return IP
701 701 #************************ end of file <ipmaker.py> **************************
@@ -1,585 +1,589 b''
1 1 # -*- coding: utf-8 -*-
2 2 #*****************************************************************************
3 3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
4 4 #
5 5 # Distributed under the terms of the BSD License. The full license is in
6 6 # the file COPYING, distributed as part of this software.
7 7 #*****************************************************************************
8 8
9 # $Id: usage.py 966 2005-12-29 08:34:07Z fperez $
9 # $Id: usage.py 990 2006-01-04 06:59:02Z fperez $
10 10
11 11 from IPython import Release
12 12 __author__ = '%s <%s>' % Release.authors['Fernando']
13 13 __license__ = Release.license
14 14 __version__ = Release.version
15 15
16 16 __doc__ = """
17 17 IPython -- An enhanced Interactive Python
18 18 =========================================
19 19
20 20 A Python shell with automatic history (input and output), dynamic object
21 21 introspection, easier configuration, command completion, access to the system
22 22 shell and more.
23 23
24 24 IPython can also be embedded in running programs. See EMBEDDING below.
25 25
26 26
27 27 USAGE
28 28 ipython [options] files
29 29
30 30 If invoked with no options, it executes all the files listed in
31 31 sequence and drops you into the interpreter while still acknowledging
32 32 any options you may have set in your ipythonrc file. This behavior is
33 33 different from standard Python, which when called as python -i will
34 34 only execute one file and will ignore your configuration setup.
35 35
36 36 Please note that some of the configuration options are not available at
37 37 the command line, simply because they are not practical here. Look into
38 38 your ipythonrc configuration file for details on those. This file
39 39 typically installed in the $HOME/.ipython directory.
40 40
41 41 For Windows users, $HOME resolves to C:\\Documents and
42 42 Settings\\YourUserName in most instances, and _ipython is used instead
43 43 of .ipython, since some Win32 programs have problems with dotted names
44 44 in directories.
45 45
46 46 In the rest of this text, we will refer to this directory as
47 47 IPYTHONDIR.
48 48
49 49
50 50 SPECIAL THREADING OPTIONS
51 51 The following special options are ONLY valid at the beginning of the
52 52 command line, and not later. This is because they control the initial-
53 53 ization of ipython itself, before the normal option-handling mechanism
54 54 is active.
55 55
56 56 -gthread, -qthread, -wthread, -pylab
57 57
58 58 Only ONE of these can be given, and it can only be given as the
59 59 first option passed to IPython (it will have no effect in any
60 60 other position). They provide threading support for the GTK, QT
61 61 and WXWidgets toolkits, and for the matplotlib library.
62 62
63 63 With any of the first three options, IPython starts running a
64 64 separate thread for the graphical toolkit's operation, so that
65 65 you can open and control graphical elements from within an
66 66 IPython command line, without blocking. All three provide
67 67 essentially the same functionality, respectively for GTK, QT and
68 68 WXWidgets (via their Python interfaces).
69 69
70 70 If -pylab is given, IPython loads special support for the mat-
71 71 plotlib library (http://matplotlib.sourceforge.net), allowing
72 72 interactive usage of any of its backends as defined in the
73 73 user's .matplotlibrc file. It automatically activates GTK, QT
74 74 or WX threading for IPyhton if the choice of matplotlib backend
75 75 requires it. It also modifies the %run command to correctly
76 76 execute (without blocking) any matplotlib-based script which
77 77 calls show() at the end.
78 78
79 79 -tk The -g/q/wthread options, and -pylab (if matplotlib is
80 80 configured to use GTK, QT or WX), will normally block Tk
81 81 graphical interfaces. This means that when GTK, QT or WX
82 82 threading is active, any attempt to open a Tk GUI will result in
83 83 a dead window, and possibly cause the Python interpreter to
84 84 crash. An extra option, -tk, is available to address this
85 85 issue. It can ONLY be given as a SECOND option after any of the
86 86 above (-gthread, -qthread, -wthread or -pylab).
87 87
88 88 If -tk is given, IPython will try to coordinate Tk threading
89 89 with GTK, QT or WX. This is however potentially unreliable, and
90 90 you will have to test on your platform and Python configuration
91 91 to determine whether it works for you. Debian users have
92 92 reported success, apparently due to the fact that Debian builds
93 93 all of Tcl, Tk, Tkinter and Python with pthreads support. Under
94 94 other Linux environments (such as Fedora Core 2/3), this option
95 95 has caused random crashes and lockups of the Python interpreter.
96 96 Under other operating systems (Mac OSX and Windows), you'll need
97 97 to try it to find out, since currently no user reports are
98 98 available.
99 99
100 100 There is unfortunately no way for IPython to determine at run-
101 101 time whether -tk will work reliably or not, so you will need to
102 102 do some experiments before relying on it for regular work.
103 103
104 104 A WARNING ABOUT SIGNALS AND THREADS
105 105
106 106 When any of the thread systems (GTK, QT or WX) are active, either
107 107 directly or via -pylab with a threaded backend, it is impossible to
108 108 interrupt long-running Python code via Ctrl-C. IPython can not pass
109 109 the KeyboardInterrupt exception (or the underlying SIGINT) across
110 110 threads, so any long-running process started from IPython will run to
111 111 completion, or will have to be killed via an external (OS-based)
112 112 mechanism.
113 113
114 114 To the best of my knowledge, this limitation is imposed by the Python
115 115 interpreter itself, and it comes from the difficulty of writing
116 116 portable signal/threaded code. If any user is an expert on this topic
117 117 and can suggest a better solution, I would love to hear about it. In
118 118 the IPython sources, look at the Shell.py module, and in particular at
119 119 the runcode() method.
120 120
121 121 REGULAR OPTIONS
122 122 After the above threading options have been given, regular options can
123 123 follow in any order. All options can be abbreviated to their shortest
124 124 non-ambiguous form and are case-sensitive. One or two dashes can be
125 125 used. Some options have an alternate short form, indicated after a |.
126 126
127 127 Most options can also be set from your ipythonrc configuration file.
128 128 See the provided examples for assistance. Options given on the comman-
129 129 dline override the values set in the ipythonrc file.
130 130
131 131 All options with a [no] prepended can be specified in negated form
132 132 (using -nooption instead of -option) to turn the feature off.
133 133
134 134 -h, --help
135 135 Show summary of options.
136 136
137 137 -pylab This can only be given as the first option passed to IPython (it
138 138 will have no effect in any other position). It adds special sup-
139 139 port for the matplotlib library (http://matplotlib.source-
140 140 forge.net), allowing interactive usage of any of its backends as
141 141 defined in the user’s .matplotlibrc file. It automatically
142 142 activates GTK or WX threading for IPyhton if the choice of mat-
143 143 plotlib backend requires it. It also modifies the @run command
144 144 to correctly execute (without blocking) any matplotlib-based
145 145 script which calls show() at the end.
146 146
147 -[no]autocall
147 -autocall <val>
148 148 Make IPython automatically call any callable object even if you
149 didnt type explicit parentheses. For example, ’str 43’ becomes
150 ’str(43)’ automatically.
149 didn't type explicit parentheses. For example, 'str 43' becomes
150 'str(43)' automatically. The value can be '0' to disable the
151 feature, '1' for 'smart' autocall, where it is not applied if
152 there are no more arguments on the line, and '2' for 'full'
153 autocall, where all callable objects are automatically called
154 (even if no arguments are present). The default is '1'.
151 155
152 156 -[no]autoindent
153 157 Turn automatic indentation on/off.
154 158
155 159 -[no]automagic
156 160 Make magic commands automatic (without needing their first char-
157 161 acter to be %). Type %magic at the IPython prompt for more
158 162 information.
159 163
160 164 -[no]autoedit_syntax
161 165 When a syntax error occurs after editing a file, automatically
162 166 open the file to the trouble causing line for convenient fixing.
163 167
164 168 -[no]banner
165 169 Print the intial information banner (default on).
166 170
167 171 -c <command>
168 172 Execute the given command string, and set sys.argv to [’c’].
169 173 This is similar to the -c option in the normal Python inter-
170 174 preter.
171 175
172 176 -cache_size|cs <n>
173 177 Size of the output cache (maximum number of entries to hold in
174 178 memory). The default is 1000, you can change it permanently in
175 179 your config file. Setting it to 0 completely disables the
176 180 caching system, and the minimum value accepted is 20 (if you
177 181 provide a value less than 20, it is reset to 0 and a warning is
178 182 issued). This limit is defined because otherwise you’ll spend
179 183 more time re-flushing a too small cache than working.
180 184
181 185 -classic|cl
182 186 Gives IPython a similar feel to the classic Python prompt.
183 187
184 188 -colors <scheme>
185 189 Color scheme for prompts and exception reporting. Currently
186 190 implemented: NoColor, Linux, and LightBG.
187 191
188 192 -[no]color_info
189 193 IPython can display information about objects via a set of func-
190 194 tions, and optionally can use colors for this, syntax highlight-
191 195 ing source code and various other elements. However, because
192 196 this information is passed through a pager (like ’less’) and
193 197 many pagers get confused with color codes, this option is off by
194 198 default. You can test it and turn it on permanently in your
195 199 ipythonrc file if it works for you. As a reference, the ’less’
196 200 pager supplied with Mandrake 8.2 works ok, but that in RedHat
197 201 7.2 doesn’t.
198 202
199 203 Test it and turn it on permanently if it works with your system.
200 204 The magic function @color_info allows you to toggle this inter-
201 205 actively for testing.
202 206
203 207 -[no]confirm_exit
204 208 Set to confirm when you try to exit IPython with an EOF (Con-
205 209 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
206 210 magic functions @Exit or @Quit you can force a direct exit,
207 211 bypassing any confirmation.
208 212
209 213 -[no]debug
210 214 Show information about the loading process. Very useful to pin
211 215 down problems with your configuration files or to get details
212 216 about session restores.
213 217
214 218 -[no]deep_reload
215 219 IPython can use the deep_reload module which reloads changes in
216 220 modules recursively (it replaces the reload() function, so you
217 221 don’t need to change anything to use it). deep_reload() forces a
218 222 full reload of modules whose code may have changed, which the
219 223 default reload() function does not.
220 224
221 225 When deep_reload is off, IPython will use the normal reload(),
222 226 but deep_reload will still be available as dreload(). This fea-
223 227 ture is off by default [which means that you have both normal
224 228 reload() and dreload()].
225 229
226 230 -editor <name>
227 231 Which editor to use with the @edit command. By default, IPython
228 232 will honor your EDITOR environment variable (if not set, vi is
229 233 the Unix default and notepad the Windows one). Since this editor
230 234 is invoked on the fly by IPython and is meant for editing small
231 235 code snippets, you may want to use a small, lightweight editor
232 236 here (in case your default EDITOR is something like Emacs).
233 237
234 238 -ipythondir <name>
235 239 The name of your IPython configuration directory IPYTHONDIR.
236 240 This can also be specified through the environment variable
237 241 IPYTHONDIR.
238 242
239 243 -log|l Generate a log file of all input. The file is named
240 244 ipython_log.py in your current directory (which prevents logs
241 245 from multiple IPython sessions from trampling each other). You
242 246 can use this to later restore a session by loading your logfile
243 247 as a file to be executed with option -logplay (see below).
244 248
245 249 -logfile|lf
246 250 Specify the name of your logfile.
247 251
248 252 -logplay|lp
249 253 Replay a previous log. For restoring a session as close as pos-
250 254 sible to the state you left it in, use this option (don’t just
251 255 run the logfile). With -logplay, IPython will try to reconstruct
252 256 the previous working environment in full, not just execute the
253 257 commands in the logfile.
254 258 When a session is restored, logging is automatically turned on
255 259 again with the name of the logfile it was invoked with (it is
256 260 read from the log header). So once you’ve turned logging on for
257 261 a session, you can quit IPython and reload it as many times as
258 262 you want and it will continue to log its history and restore
259 263 from the beginning every time.
260 264
261 265 Caveats: there are limitations in this option. The history vari-
262 266 ables _i*,_* and _dh don’t get restored properly. In the future
263 267 we will try to implement full session saving by writing and
264 268 retrieving a failed because of inherent limitations of Python’s
265 269 Pickle module, so this may have to wait.
266 270
267 271 -[no]messages
268 272 Print messages which IPython collects about its startup process
269 273 (default on).
270 274
271 275 -[no]pdb
272 276 Automatically call the pdb debugger after every uncaught excep-
273 277 tion. If you are used to debugging using pdb, this puts you
274 278 automatically inside of it after any call (either in IPython or
275 279 in code called by it) which triggers an exception which goes
276 280 uncaught.
277 281
278 282 -[no]pprint
279 283 IPython can optionally use the pprint (pretty printer) module
280 284 for displaying results. pprint tends to give a nicer display of
281 285 nested data structures. If you like it, you can turn it on per-
282 286 manently in your config file (default off).
283 287
284 288 -profile|p <name>
285 289 Assume that your config file is ipythonrc-<name> (looks in cur-
286 290 rent dir first, then in IPYTHONDIR). This is a quick way to keep
287 291 and load multiple config files for different tasks, especially
288 292 if you use the include option of config files. You can keep a
289 293 basic IPYTHONDIR/ipythonrc file and then have other ’profiles’
290 294 which include this one and load extra things for particular
291 295 tasks. For example:
292 296
293 297 1) $HOME/.ipython/ipythonrc : load basic things you always want.
294 298 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
295 299 related modules.
296 300 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
297 301 plotting modules.
298 302
299 303 Since it is possible to create an endless loop by having circu-
300 304 lar file inclusions, IPython will stop if it reaches 15 recur-
301 305 sive inclusions.
302 306
303 307 -prompt_in1|pi1 <string>
304 308 Specify the string used for input prompts. Note that if you are
305 309 using numbered prompts, the number is represented with a ’\#’ in
306 310 the string. Don’t forget to quote strings with spaces embedded
307 311 in them. Default: ’In [\#]:’.
308 312
309 313 Most bash-like escapes can be used to customize IPython’s
310 314 prompts, as well as a few additional ones which are IPython-spe-
311 315 cific. All valid prompt escapes are described in detail in the
312 316 Customization section of the IPython HTML/PDF manual.
313 317
314 318 -prompt_in2|pi2 <string>
315 319 Similar to the previous option, but used for the continuation
316 320 prompts. The special sequence ’\D’ is similar to ’\#’, but with
317 321 all digits replaced dots (so you can have your continuation
318 322 prompt aligned with your input prompt). Default: ’ .\D.:’
319 323 (note three spaces at the start for alignment with ’In [\#]’).
320 324
321 325 -prompt_out|po <string>
322 326 String used for output prompts, also uses numbers like
323 327 prompt_in1. Default: ’Out[\#]:’.
324 328
325 329 -quick Start in bare bones mode (no config file loaded).
326 330
327 331 -rcfile <name>
328 332 Name of your IPython resource configuration file. normally
329 333 IPython loads ipythonrc (from current directory) or
330 334 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
331 335 IPython starts with a bare bones configuration (no modules
332 336 loaded at all).
333 337
334 338 -[no]readline
335 339 Use the readline library, which is needed to support name com-
336 340 pletion and command history, among other things. It is enabled
337 341 by default, but may cause problems for users of X/Emacs in
338 342 Python comint or shell buffers.
339 343
340 344 Note that emacs ’eterm’ buffers (opened with M-x term) support
341 345 IPython’s readline and syntax coloring fine, only ’emacs’ (M-x
342 346 shell and C-c !) buffers do not.
343 347
344 348 -screen_length|sl <n>
345 349 Number of lines of your screen. This is used to control print-
346 350 ing of very long strings. Strings longer than this number of
347 351 lines will be sent through a pager instead of directly printed.
348 352
349 353 The default value for this is 0, which means IPython will auto-
350 354 detect your screen size every time it needs to print certain
351 355 potentially long strings (this doesn’t change the behavior of
352 356 the ’print’ keyword, it’s only triggered internally). If for
353 357 some reason this isn’t working well (it needs curses support),
354 358 specify it yourself. Otherwise don’t change the default.
355 359
356 360 -separate_in|si <string>
357 361 Separator before input prompts. Default ’0.
358 362
359 363 -separate_out|so <string>
360 364 Separator before output prompts. Default: 0 (nothing).
361 365
362 366 -separate_out2|so2 <string>
363 367 Separator after output prompts. Default: 0 (nothing).
364 368
365 369 -nosep Shorthand for ’-separate_in 0 -separate_out 0 -separate_out2 0’.
366 370 Simply removes all input/output separators.
367 371
368 372 -upgrade
369 373 Allows you to upgrade your IPYTHONDIR configuration when you
370 374 install a new version of IPython. Since new versions may
371 375 include new command lines options or example files, this copies
372 376 updated ipythonrc-type files. However, it backs up (with a .old
373 377 extension) all files which it overwrites so that you can merge
374 378 back any custimizations you might have in your personal files.
375 379
376 380 -Version
377 381 Print version information and exit.
378 382
379 383 -xmode <modename>
380 384 Mode for exception reporting. The valid modes are Plain, Con-
381 385 text, and Verbose.
382 386
383 387 - Plain: similar to python’s normal traceback printing.
384 388
385 389 - Context: prints 5 lines of context source code around each
386 390 line in the traceback.
387 391
388 392 - Verbose: similar to Context, but additionally prints the vari-
389 393 ables currently visible where the exception happened (shortening
390 394 their strings if too long). This can potentially be very slow,
391 395 if you happen to have a huge data structure whose string repre-
392 396 sentation is complex to compute. Your computer may appear to
393 397 freeze for a while with cpu usage at 100%. If this occurs, you
394 398 can cancel the traceback with Ctrl-C (maybe hitting it more than
395 399 once).
396 400
397 401
398 402 EMBEDDING
399 403 It is possible to start an IPython instance inside your own Python pro-
400 404 grams. In the documentation example files there are some illustrations
401 405 on how to do this.
402 406
403 407 This feature allows you to evalutate dynamically the state of your
404 408 code, operate with your variables, analyze them, etc. Note however
405 409 that any changes you make to values while in the shell do NOT propagate
406 410 back to the running code, so it is safe to modify your values because
407 411 you won’t break your code in bizarre ways by doing so.
408 412 """
409 413
410 414 cmd_line_usage = __doc__
411 415
412 416 #---------------------------------------------------------------------------
413 417 interactive_usage = """
414 418 IPython -- An enhanced Interactive Python
415 419 =========================================
416 420
417 421 IPython offers a combination of convenient shell features, special commands
418 422 and a history mechanism for both input (command history) and output (results
419 423 caching, similar to Mathematica). It is intended to be a fully compatible
420 424 replacement for the standard Python interpreter, while offering vastly
421 425 improved functionality and flexibility.
422 426
423 427 At your system command line, type 'ipython -help' to see the command line
424 428 options available. This document only describes interactive features.
425 429
426 430 Warning: IPython relies on the existence of a global variable called __IP which
427 431 controls the shell itself. If you redefine __IP to anything, bizarre behavior
428 432 will quickly occur.
429 433
430 434 MAIN FEATURES
431 435
432 436 * Access to the standard Python help. As of Python 2.1, a help system is
433 437 available with access to object docstrings and the Python manuals. Simply
434 438 type 'help' (no quotes) to access it.
435 439
436 440 * Magic commands: type %magic for information on the magic subsystem.
437 441
438 442 * System command aliases, via the %alias command or the ipythonrc config file.
439 443
440 444 * Dynamic object information:
441 445
442 446 Typing ?word or word? prints detailed information about an object. If
443 447 certain strings in the object are too long (docstrings, code, etc.) they get
444 448 snipped in the center for brevity.
445 449
446 450 Typing ??word or word?? gives access to the full information without
447 451 snipping long strings. Long strings are sent to the screen through the less
448 452 pager if longer than the screen, printed otherwise.
449 453
450 454 The ?/?? system gives access to the full source code for any object (if
451 455 available), shows function prototypes and other useful information.
452 456
453 457 If you just want to see an object's docstring, type '%pdoc object' (without
454 458 quotes, and without % if you have automagic on).
455 459
456 460 Both %pdoc and ?/?? give you access to documentation even on things which are
457 461 not explicitely defined. Try for example typing {}.get? or after import os,
458 462 type os.path.abspath??. The magic functions %pdef, %source and %file operate
459 463 similarly.
460 464
461 465 * Completion in the local namespace, by typing TAB at the prompt.
462 466
463 467 At any time, hitting tab will complete any available python commands or
464 468 variable names, and show you a list of the possible completions if there's
465 469 no unambiguous one. It will also complete filenames in the current directory.
466 470
467 471 This feature requires the readline and rlcomplete modules, so it won't work
468 472 if your Python lacks readline support (such as under Windows).
469 473
470 474 * Search previous command history in two ways (also requires readline):
471 475
472 476 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
473 477 search through only the history items that match what you've typed so
474 478 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
475 479 normal arrow keys.
476 480
477 481 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
478 482 your history for lines that match what you've typed so far, completing as
479 483 much as it can.
480 484
481 485 * Persistent command history across sessions (readline required).
482 486
483 487 * Logging of input with the ability to save and restore a working session.
484 488
485 489 * System escape with !. Typing !ls will run 'ls' in the current directory.
486 490
487 491 * The reload command does a 'deep' reload of a module: changes made to the
488 492 module since you imported will actually be available without having to exit.
489 493
490 494 * Verbose and colored exception traceback printouts. See the magic xmode and
491 495 xcolor functions for details (just type %magic).
492 496
493 497 * Input caching system:
494 498
495 499 IPython offers numbered prompts (In/Out) with input and output caching. All
496 500 input is saved and can be retrieved as variables (besides the usual arrow
497 501 key recall).
498 502
499 503 The following GLOBAL variables always exist (so don't overwrite them!):
500 504 _i: stores previous input.
501 505 _ii: next previous.
502 506 _iii: next-next previous.
503 507 _ih : a list of all input _ih[n] is the input from line n.
504 508
505 509 Additionally, global variables named _i<n> are dynamically created (<n>
506 510 being the prompt counter), such that _i<n> == _ih[<n>]
507 511
508 512 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
509 513
510 514 You can create macros which contain multiple input lines from this history,
511 515 for later re-execution, with the %macro function.
512 516
513 517 The history function %hist allows you to see any part of your input history
514 518 by printing a range of the _i variables. Note that inputs which contain
515 519 magic functions (%) appear in the history with a prepended comment. This is
516 520 because they aren't really valid Python code, so you can't exec them.
517 521
518 522 * Output caching system:
519 523
520 524 For output that is returned from actions, a system similar to the input
521 525 cache exists but using _ instead of _i. Only actions that produce a result
522 526 (NOT assignments, for example) are cached. If you are familiar with
523 527 Mathematica, IPython's _ variables behave exactly like Mathematica's %
524 528 variables.
525 529
526 530 The following GLOBAL variables always exist (so don't overwrite them!):
527 531 _ (one underscore): previous output.
528 532 __ (two underscores): next previous.
529 533 ___ (three underscores): next-next previous.
530 534
531 535 Global variables named _<n> are dynamically created (<n> being the prompt
532 536 counter), such that the result of output <n> is always available as _<n>.
533 537
534 538 Finally, a global dictionary named _oh exists with entries for all lines
535 539 which generated output.
536 540
537 541 * Directory history:
538 542
539 543 Your history of visited directories is kept in the global list _dh, and the
540 544 magic %cd command can be used to go to any entry in that list.
541 545
542 546 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
543 547
544 548 1. Auto-parentheses
545 549 Callable objects (i.e. functions, methods, etc) can be invoked like
546 550 this (notice the commas between the arguments):
547 551 >>> callable_ob arg1, arg2, arg3
548 552 and the input will be translated to this:
549 553 --> callable_ob(arg1, arg2, arg3)
550 554 You can force auto-parentheses by using '/' as the first character
551 555 of a line. For example:
552 556 >>> /globals # becomes 'globals()'
553 557 Note that the '/' MUST be the first character on the line! This
554 558 won't work:
555 559 >>> print /globals # syntax error
556 560
557 561 In most cases the automatic algorithm should work, so you should
558 562 rarely need to explicitly invoke /. One notable exception is if you
559 563 are trying to call a function with a list of tuples as arguments (the
560 564 parenthesis will confuse IPython):
561 565 In [1]: zip (1,2,3),(4,5,6) # won't work
562 566 but this will work:
563 567 In [2]: /zip (1,2,3),(4,5,6)
564 568 ------> zip ((1,2,3),(4,5,6))
565 569 Out[2]= [(1, 4), (2, 5), (3, 6)]
566 570
567 571 IPython tells you that it has altered your command line by
568 572 displaying the new command line preceded by -->. e.g.:
569 573 In [18]: callable list
570 574 -------> callable (list)
571 575
572 576 2. Auto-Quoting
573 577 You can force auto-quoting of a function's arguments by using ',' as
574 578 the first character of a line. For example:
575 579 >>> ,my_function /home/me # becomes my_function("/home/me")
576 580
577 581 If you use ';' instead, the whole argument is quoted as a single
578 582 string (while ',' splits on whitespace):
579 583 >>> ,my_function a b c # becomes my_function("a","b","c")
580 584 >>> ;my_function a b c # becomes my_function("a b c")
581 585
582 586 Note that the ',' MUST be the first character on the line! This
583 587 won't work:
584 588 >>> x = ,my_function /home/me # syntax error
585 589 """
@@ -1,4749 +1,4763 b''
1 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * IPython/iplib.py (handle_auto): changed autocall semantics to
4 include 'smart' mode, where the autocall transformation is NOT
5 applied if there are no arguments on the line. This allows you to
6 just type 'foo' if foo is a callable to see its internal form,
7 instead of having it called with no arguments (typically a
8 mistake). The old 'full' autocall still exists: for that, you
9 need to set the 'autocall' parameter to 2 in your ipythonrc file.
10
11 * IPython/completer.py (Completer.attr_matches): add
12 tab-completion support for Enthoughts' traits. After a report by
13 Arnd and a patch by Prabhu.
14
1 15 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
2 16
3 17 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
4 18 Schmolck's patch to fix inspect.getinnerframes().
5 19
6 20 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
7 21 for embedded instances, regarding handling of namespaces and items
8 22 added to the __builtin__ one. Multiple embedded instances and
9 23 recursive embeddings should work better now (though I'm not sure
10 24 I've got all the corner cases fixed, that code is a bit of a brain
11 25 twister).
12 26
13 27 * IPython/Magic.py (magic_edit): added support to edit in-memory
14 28 macros (automatically creates the necessary temp files). %edit
15 29 also doesn't return the file contents anymore, it's just noise.
16 30
17 31 * IPython/completer.py (Completer.attr_matches): revert change to
18 32 complete only on attributes listed in __all__. I realized it
19 33 cripples the tab-completion system as a tool for exploring the
20 34 internals of unknown libraries (it renders any non-__all__
21 35 attribute off-limits). I got bit by this when trying to see
22 36 something inside the dis module.
23 37
24 38 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
25 39
26 40 * IPython/iplib.py (InteractiveShell.__init__): add .meta
27 41 namespace for users and extension writers to hold data in. This
28 42 follows the discussion in
29 43 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
30 44
31 45 * IPython/completer.py (IPCompleter.complete): small patch to help
32 46 tab-completion under Emacs, after a suggestion by John Barnard
33 47 <barnarj-AT-ccf.org>.
34 48
35 49 * IPython/Magic.py (Magic.extract_input_slices): added support for
36 50 the slice notation in magics to use N-M to represent numbers N...M
37 51 (closed endpoints). This is used by %macro and %save.
38 52
39 53 * IPython/completer.py (Completer.attr_matches): for modules which
40 54 define __all__, complete only on those. After a patch by Jeffrey
41 55 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
42 56 speed up this routine.
43 57
44 58 * IPython/Logger.py (Logger.log): fix a history handling bug. I
45 59 don't know if this is the end of it, but the behavior now is
46 60 certainly much more correct. Note that coupled with macros,
47 61 slightly surprising (at first) behavior may occur: a macro will in
48 62 general expand to multiple lines of input, so upon exiting, the
49 63 in/out counters will both be bumped by the corresponding amount
50 64 (as if the macro's contents had been typed interactively). Typing
51 65 %hist will reveal the intermediate (silently processed) lines.
52 66
53 67 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
54 68 pickle to fail (%run was overwriting __main__ and not restoring
55 69 it, but pickle relies on __main__ to operate).
56 70
57 71 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
58 72 using properties, but forgot to make the main InteractiveShell
59 73 class a new-style class. Properties fail silently, and
60 74 misteriously, with old-style class (getters work, but
61 75 setters don't do anything).
62 76
63 77 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
64 78
65 79 * IPython/Magic.py (magic_history): fix history reporting bug (I
66 80 know some nasties are still there, I just can't seem to find a
67 81 reproducible test case to track them down; the input history is
68 82 falling out of sync...)
69 83
70 84 * IPython/iplib.py (handle_shell_escape): fix bug where both
71 85 aliases and system accesses where broken for indented code (such
72 86 as loops).
73 87
74 88 * IPython/genutils.py (shell): fix small but critical bug for
75 89 win32 system access.
76 90
77 91 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
78 92
79 93 * IPython/iplib.py (showtraceback): remove use of the
80 94 sys.last_{type/value/traceback} structures, which are non
81 95 thread-safe.
82 96 (_prefilter): change control flow to ensure that we NEVER
83 97 introspect objects when autocall is off. This will guarantee that
84 98 having an input line of the form 'x.y', where access to attribute
85 99 'y' has side effects, doesn't trigger the side effect TWICE. It
86 100 is important to note that, with autocall on, these side effects
87 101 can still happen.
88 102 (ipsystem): new builtin, to complete the ip{magic/alias/system}
89 103 trio. IPython offers these three kinds of special calls which are
90 104 not python code, and it's a good thing to have their call method
91 105 be accessible as pure python functions (not just special syntax at
92 106 the command line). It gives us a better internal implementation
93 107 structure, as well as exposing these for user scripting more
94 108 cleanly.
95 109
96 110 * IPython/macro.py (Macro.__init__): moved macros to a standalone
97 111 file. Now that they'll be more likely to be used with the
98 112 persistance system (%store), I want to make sure their module path
99 113 doesn't change in the future, so that we don't break things for
100 114 users' persisted data.
101 115
102 116 * IPython/iplib.py (autoindent_update): move indentation
103 117 management into the _text_ processing loop, not the keyboard
104 118 interactive one. This is necessary to correctly process non-typed
105 119 multiline input (such as macros).
106 120
107 121 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
108 122 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
109 123 which was producing problems in the resulting manual.
110 124 (magic_whos): improve reporting of instances (show their class,
111 125 instead of simply printing 'instance' which isn't terribly
112 126 informative).
113 127
114 128 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
115 129 (minor mods) to support network shares under win32.
116 130
117 131 * IPython/winconsole.py (get_console_size): add new winconsole
118 132 module and fixes to page_dumb() to improve its behavior under
119 133 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
120 134
121 135 * IPython/Magic.py (Macro): simplified Macro class to just
122 136 subclass list. We've had only 2.2 compatibility for a very long
123 137 time, yet I was still avoiding subclassing the builtin types. No
124 138 more (I'm also starting to use properties, though I won't shift to
125 139 2.3-specific features quite yet).
126 140 (magic_store): added Ville's patch for lightweight variable
127 141 persistence, after a request on the user list by Matt Wilkie
128 142 <maphew-AT-gmail.com>. The new %store magic's docstring has full
129 143 details.
130 144
131 145 * IPython/iplib.py (InteractiveShell.post_config_initialization):
132 146 changed the default logfile name from 'ipython.log' to
133 147 'ipython_log.py'. These logs are real python files, and now that
134 148 we have much better multiline support, people are more likely to
135 149 want to use them as such. Might as well name them correctly.
136 150
137 151 * IPython/Magic.py: substantial cleanup. While we can't stop
138 152 using magics as mixins, due to the existing customizations 'out
139 153 there' which rely on the mixin naming conventions, at least I
140 154 cleaned out all cross-class name usage. So once we are OK with
141 155 breaking compatibility, the two systems can be separated.
142 156
143 157 * IPython/Logger.py: major cleanup. This one is NOT a mixin
144 158 anymore, and the class is a fair bit less hideous as well. New
145 159 features were also introduced: timestamping of input, and logging
146 160 of output results. These are user-visible with the -t and -o
147 161 options to %logstart. Closes
148 162 http://www.scipy.net/roundup/ipython/issue11 and a request by
149 163 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
150 164
151 165 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
152 166
153 167 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
154 168 better hadnle backslashes in paths. See the thread 'More Windows
155 169 questions part 2 - \/ characters revisited' on the iypthon user
156 170 list:
157 171 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
158 172
159 173 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
160 174
161 175 (InteractiveShell.__init__): change threaded shells to not use the
162 176 ipython crash handler. This was causing more problems than not,
163 177 as exceptions in the main thread (GUI code, typically) would
164 178 always show up as a 'crash', when they really weren't.
165 179
166 180 The colors and exception mode commands (%colors/%xmode) have been
167 181 synchronized to also take this into account, so users can get
168 182 verbose exceptions for their threaded code as well. I also added
169 183 support for activating pdb inside this exception handler as well,
170 184 so now GUI authors can use IPython's enhanced pdb at runtime.
171 185
172 186 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
173 187 true by default, and add it to the shipped ipythonrc file. Since
174 188 this asks the user before proceeding, I think it's OK to make it
175 189 true by default.
176 190
177 191 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
178 192 of the previous special-casing of input in the eval loop. I think
179 193 this is cleaner, as they really are commands and shouldn't have
180 194 a special role in the middle of the core code.
181 195
182 196 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
183 197
184 198 * IPython/iplib.py (edit_syntax_error): added support for
185 199 automatically reopening the editor if the file had a syntax error
186 200 in it. Thanks to scottt who provided the patch at:
187 201 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
188 202 version committed).
189 203
190 204 * IPython/iplib.py (handle_normal): add suport for multi-line
191 205 input with emtpy lines. This fixes
192 206 http://www.scipy.net/roundup/ipython/issue43 and a similar
193 207 discussion on the user list.
194 208
195 209 WARNING: a behavior change is necessarily introduced to support
196 210 blank lines: now a single blank line with whitespace does NOT
197 211 break the input loop, which means that when autoindent is on, by
198 212 default hitting return on the next (indented) line does NOT exit.
199 213
200 214 Instead, to exit a multiline input you can either have:
201 215
202 216 - TWO whitespace lines (just hit return again), or
203 217 - a single whitespace line of a different length than provided
204 218 by the autoindent (add or remove a space).
205 219
206 220 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
207 221 module to better organize all readline-related functionality.
208 222 I've deleted FlexCompleter and put all completion clases here.
209 223
210 224 * IPython/iplib.py (raw_input): improve indentation management.
211 225 It is now possible to paste indented code with autoindent on, and
212 226 the code is interpreted correctly (though it still looks bad on
213 227 screen, due to the line-oriented nature of ipython).
214 228 (MagicCompleter.complete): change behavior so that a TAB key on an
215 229 otherwise empty line actually inserts a tab, instead of completing
216 230 on the entire global namespace. This makes it easier to use the
217 231 TAB key for indentation. After a request by Hans Meine
218 232 <hans_meine-AT-gmx.net>
219 233 (_prefilter): add support so that typing plain 'exit' or 'quit'
220 234 does a sensible thing. Originally I tried to deviate as little as
221 235 possible from the default python behavior, but even that one may
222 236 change in this direction (thread on python-dev to that effect).
223 237 Regardless, ipython should do the right thing even if CPython's
224 238 '>>>' prompt doesn't.
225 239 (InteractiveShell): removed subclassing code.InteractiveConsole
226 240 class. By now we'd overridden just about all of its methods: I've
227 241 copied the remaining two over, and now ipython is a standalone
228 242 class. This will provide a clearer picture for the chainsaw
229 243 branch refactoring.
230 244
231 245 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
232 246
233 247 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
234 248 failures for objects which break when dir() is called on them.
235 249
236 250 * IPython/FlexCompleter.py (Completer.__init__): Added support for
237 251 distinct local and global namespaces in the completer API. This
238 252 change allows us top properly handle completion with distinct
239 253 scopes, including in embedded instances (this had never really
240 254 worked correctly).
241 255
242 256 Note: this introduces a change in the constructor for
243 257 MagicCompleter, as a new global_namespace parameter is now the
244 258 second argument (the others were bumped one position).
245 259
246 260 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
247 261
248 262 * IPython/iplib.py (embed_mainloop): fix tab-completion in
249 263 embedded instances (which can be done now thanks to Vivian's
250 264 frame-handling fixes for pdb).
251 265 (InteractiveShell.__init__): Fix namespace handling problem in
252 266 embedded instances. We were overwriting __main__ unconditionally,
253 267 and this should only be done for 'full' (non-embedded) IPython;
254 268 embedded instances must respect the caller's __main__. Thanks to
255 269 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
256 270
257 271 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
258 272
259 273 * setup.py: added download_url to setup(). This registers the
260 274 download address at PyPI, which is not only useful to humans
261 275 browsing the site, but is also picked up by setuptools (the Eggs
262 276 machinery). Thanks to Ville and R. Kern for the info/discussion
263 277 on this.
264 278
265 279 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
266 280
267 281 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
268 282 This brings a lot of nice functionality to the pdb mode, which now
269 283 has tab-completion, syntax highlighting, and better stack handling
270 284 than before. Many thanks to Vivian De Smedt
271 285 <vivian-AT-vdesmedt.com> for the original patches.
272 286
273 287 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
274 288
275 289 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
276 290 sequence to consistently accept the banner argument. The
277 291 inconsistency was tripping SAGE, thanks to Gary Zablackis
278 292 <gzabl-AT-yahoo.com> for the report.
279 293
280 294 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
281 295
282 296 * IPython/iplib.py (InteractiveShell.post_config_initialization):
283 297 Fix bug where a naked 'alias' call in the ipythonrc file would
284 298 cause a crash. Bug reported by Jorgen Stenarson.
285 299
286 300 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
287 301
288 302 * IPython/ipmaker.py (make_IPython): cleanups which should improve
289 303 startup time.
290 304
291 305 * IPython/iplib.py (runcode): my globals 'fix' for embedded
292 306 instances had introduced a bug with globals in normal code. Now
293 307 it's working in all cases.
294 308
295 309 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
296 310 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
297 311 has been introduced to set the default case sensitivity of the
298 312 searches. Users can still select either mode at runtime on a
299 313 per-search basis.
300 314
301 315 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
302 316
303 317 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
304 318 attributes in wildcard searches for subclasses. Modified version
305 319 of a patch by Jorgen.
306 320
307 321 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
308 322
309 323 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
310 324 embedded instances. I added a user_global_ns attribute to the
311 325 InteractiveShell class to handle this.
312 326
313 327 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
314 328
315 329 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
316 330 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
317 331 (reported under win32, but may happen also in other platforms).
318 332 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
319 333
320 334 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
321 335
322 336 * IPython/Magic.py (magic_psearch): new support for wildcard
323 337 patterns. Now, typing ?a*b will list all names which begin with a
324 338 and end in b, for example. The %psearch magic has full
325 339 docstrings. Many thanks to Jörgen Stenarson
326 340 <jorgen.stenarson-AT-bostream.nu>, author of the patches
327 341 implementing this functionality.
328 342
329 343 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
330 344
331 345 * Manual: fixed long-standing annoyance of double-dashes (as in
332 346 --prefix=~, for example) being stripped in the HTML version. This
333 347 is a latex2html bug, but a workaround was provided. Many thanks
334 348 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
335 349 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
336 350 rolling. This seemingly small issue had tripped a number of users
337 351 when first installing, so I'm glad to see it gone.
338 352
339 353 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
340 354
341 355 * IPython/Extensions/numeric_formats.py: fix missing import,
342 356 reported by Stephen Walton.
343 357
344 358 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
345 359
346 360 * IPython/demo.py: finish demo module, fully documented now.
347 361
348 362 * IPython/genutils.py (file_read): simple little utility to read a
349 363 file and ensure it's closed afterwards.
350 364
351 365 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
352 366
353 367 * IPython/demo.py (Demo.__init__): added support for individually
354 368 tagging blocks for automatic execution.
355 369
356 370 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
357 371 syntax-highlighted python sources, requested by John.
358 372
359 373 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
360 374
361 375 * IPython/demo.py (Demo.again): fix bug where again() blocks after
362 376 finishing.
363 377
364 378 * IPython/genutils.py (shlex_split): moved from Magic to here,
365 379 where all 2.2 compatibility stuff lives. I needed it for demo.py.
366 380
367 381 * IPython/demo.py (Demo.__init__): added support for silent
368 382 blocks, improved marks as regexps, docstrings written.
369 383 (Demo.__init__): better docstring, added support for sys.argv.
370 384
371 385 * IPython/genutils.py (marquee): little utility used by the demo
372 386 code, handy in general.
373 387
374 388 * IPython/demo.py (Demo.__init__): new class for interactive
375 389 demos. Not documented yet, I just wrote it in a hurry for
376 390 scipy'05. Will docstring later.
377 391
378 392 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
379 393
380 394 * IPython/Shell.py (sigint_handler): Drastic simplification which
381 395 also seems to make Ctrl-C work correctly across threads! This is
382 396 so simple, that I can't beleive I'd missed it before. Needs more
383 397 testing, though.
384 398 (KBINT): Never mind, revert changes. I'm sure I'd tried something
385 399 like this before...
386 400
387 401 * IPython/genutils.py (get_home_dir): add protection against
388 402 non-dirs in win32 registry.
389 403
390 404 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
391 405 bug where dict was mutated while iterating (pysh crash).
392 406
393 407 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
394 408
395 409 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
396 410 spurious newlines added by this routine. After a report by
397 411 F. Mantegazza.
398 412
399 413 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
400 414
401 415 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
402 416 calls. These were a leftover from the GTK 1.x days, and can cause
403 417 problems in certain cases (after a report by John Hunter).
404 418
405 419 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
406 420 os.getcwd() fails at init time. Thanks to patch from David Remahl
407 421 <chmod007-AT-mac.com>.
408 422 (InteractiveShell.__init__): prevent certain special magics from
409 423 being shadowed by aliases. Closes
410 424 http://www.scipy.net/roundup/ipython/issue41.
411 425
412 426 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
413 427
414 428 * IPython/iplib.py (InteractiveShell.complete): Added new
415 429 top-level completion method to expose the completion mechanism
416 430 beyond readline-based environments.
417 431
418 432 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
419 433
420 434 * tools/ipsvnc (svnversion): fix svnversion capture.
421 435
422 436 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
423 437 attribute to self, which was missing. Before, it was set by a
424 438 routine which in certain cases wasn't being called, so the
425 439 instance could end up missing the attribute. This caused a crash.
426 440 Closes http://www.scipy.net/roundup/ipython/issue40.
427 441
428 442 2005-08-16 Fernando Perez <fperez@colorado.edu>
429 443
430 444 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
431 445 contains non-string attribute. Closes
432 446 http://www.scipy.net/roundup/ipython/issue38.
433 447
434 448 2005-08-14 Fernando Perez <fperez@colorado.edu>
435 449
436 450 * tools/ipsvnc: Minor improvements, to add changeset info.
437 451
438 452 2005-08-12 Fernando Perez <fperez@colorado.edu>
439 453
440 454 * IPython/iplib.py (runsource): remove self.code_to_run_src
441 455 attribute. I realized this is nothing more than
442 456 '\n'.join(self.buffer), and having the same data in two different
443 457 places is just asking for synchronization bugs. This may impact
444 458 people who have custom exception handlers, so I need to warn
445 459 ipython-dev about it (F. Mantegazza may use them).
446 460
447 461 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
448 462
449 463 * IPython/genutils.py: fix 2.2 compatibility (generators)
450 464
451 465 2005-07-18 Fernando Perez <fperez@colorado.edu>
452 466
453 467 * IPython/genutils.py (get_home_dir): fix to help users with
454 468 invalid $HOME under win32.
455 469
456 470 2005-07-17 Fernando Perez <fperez@colorado.edu>
457 471
458 472 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
459 473 some old hacks and clean up a bit other routines; code should be
460 474 simpler and a bit faster.
461 475
462 476 * IPython/iplib.py (interact): removed some last-resort attempts
463 477 to survive broken stdout/stderr. That code was only making it
464 478 harder to abstract out the i/o (necessary for gui integration),
465 479 and the crashes it could prevent were extremely rare in practice
466 480 (besides being fully user-induced in a pretty violent manner).
467 481
468 482 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
469 483 Nothing major yet, but the code is simpler to read; this should
470 484 make it easier to do more serious modifications in the future.
471 485
472 486 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
473 487 which broke in .15 (thanks to a report by Ville).
474 488
475 489 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
476 490 be quite correct, I know next to nothing about unicode). This
477 491 will allow unicode strings to be used in prompts, amongst other
478 492 cases. It also will prevent ipython from crashing when unicode
479 493 shows up unexpectedly in many places. If ascii encoding fails, we
480 494 assume utf_8. Currently the encoding is not a user-visible
481 495 setting, though it could be made so if there is demand for it.
482 496
483 497 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
484 498
485 499 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
486 500
487 501 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
488 502
489 503 * IPython/genutils.py: Add 2.2 compatibility here, so all other
490 504 code can work transparently for 2.2/2.3.
491 505
492 506 2005-07-16 Fernando Perez <fperez@colorado.edu>
493 507
494 508 * IPython/ultraTB.py (ExceptionColors): Make a global variable
495 509 out of the color scheme table used for coloring exception
496 510 tracebacks. This allows user code to add new schemes at runtime.
497 511 This is a minimally modified version of the patch at
498 512 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
499 513 for the contribution.
500 514
501 515 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
502 516 slightly modified version of the patch in
503 517 http://www.scipy.net/roundup/ipython/issue34, which also allows me
504 518 to remove the previous try/except solution (which was costlier).
505 519 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
506 520
507 521 2005-06-08 Fernando Perez <fperez@colorado.edu>
508 522
509 523 * IPython/iplib.py (write/write_err): Add methods to abstract all
510 524 I/O a bit more.
511 525
512 526 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
513 527 warning, reported by Aric Hagberg, fix by JD Hunter.
514 528
515 529 2005-06-02 *** Released version 0.6.15
516 530
517 531 2005-06-01 Fernando Perez <fperez@colorado.edu>
518 532
519 533 * IPython/iplib.py (MagicCompleter.file_matches): Fix
520 534 tab-completion of filenames within open-quoted strings. Note that
521 535 this requires that in ~/.ipython/ipythonrc, users change the
522 536 readline delimiters configuration to read:
523 537
524 538 readline_remove_delims -/~
525 539
526 540
527 541 2005-05-31 *** Released version 0.6.14
528 542
529 543 2005-05-29 Fernando Perez <fperez@colorado.edu>
530 544
531 545 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
532 546 with files not on the filesystem. Reported by Eliyahu Sandler
533 547 <eli@gondolin.net>
534 548
535 549 2005-05-22 Fernando Perez <fperez@colorado.edu>
536 550
537 551 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
538 552 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
539 553
540 554 2005-05-19 Fernando Perez <fperez@colorado.edu>
541 555
542 556 * IPython/iplib.py (safe_execfile): close a file which could be
543 557 left open (causing problems in win32, which locks open files).
544 558 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
545 559
546 560 2005-05-18 Fernando Perez <fperez@colorado.edu>
547 561
548 562 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
549 563 keyword arguments correctly to safe_execfile().
550 564
551 565 2005-05-13 Fernando Perez <fperez@colorado.edu>
552 566
553 567 * ipython.1: Added info about Qt to manpage, and threads warning
554 568 to usage page (invoked with --help).
555 569
556 570 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
557 571 new matcher (it goes at the end of the priority list) to do
558 572 tab-completion on named function arguments. Submitted by George
559 573 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
560 574 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
561 575 for more details.
562 576
563 577 * IPython/Magic.py (magic_run): Added new -e flag to ignore
564 578 SystemExit exceptions in the script being run. Thanks to a report
565 579 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
566 580 producing very annoying behavior when running unit tests.
567 581
568 582 2005-05-12 Fernando Perez <fperez@colorado.edu>
569 583
570 584 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
571 585 which I'd broken (again) due to a changed regexp. In the process,
572 586 added ';' as an escape to auto-quote the whole line without
573 587 splitting its arguments. Thanks to a report by Jerry McRae
574 588 <qrs0xyc02-AT-sneakemail.com>.
575 589
576 590 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
577 591 possible crashes caused by a TokenError. Reported by Ed Schofield
578 592 <schofield-AT-ftw.at>.
579 593
580 594 2005-05-06 Fernando Perez <fperez@colorado.edu>
581 595
582 596 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
583 597
584 598 2005-04-29 Fernando Perez <fperez@colorado.edu>
585 599
586 600 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
587 601 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
588 602 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
589 603 which provides support for Qt interactive usage (similar to the
590 604 existing one for WX and GTK). This had been often requested.
591 605
592 606 2005-04-14 *** Released version 0.6.13
593 607
594 608 2005-04-08 Fernando Perez <fperez@colorado.edu>
595 609
596 610 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
597 611 from _ofind, which gets called on almost every input line. Now,
598 612 we only try to get docstrings if they are actually going to be
599 613 used (the overhead of fetching unnecessary docstrings can be
600 614 noticeable for certain objects, such as Pyro proxies).
601 615
602 616 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
603 617 for completers. For some reason I had been passing them the state
604 618 variable, which completers never actually need, and was in
605 619 conflict with the rlcompleter API. Custom completers ONLY need to
606 620 take the text parameter.
607 621
608 622 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
609 623 work correctly in pysh. I've also moved all the logic which used
610 624 to be in pysh.py here, which will prevent problems with future
611 625 upgrades. However, this time I must warn users to update their
612 626 pysh profile to include the line
613 627
614 628 import_all IPython.Extensions.InterpreterExec
615 629
616 630 because otherwise things won't work for them. They MUST also
617 631 delete pysh.py and the line
618 632
619 633 execfile pysh.py
620 634
621 635 from their ipythonrc-pysh.
622 636
623 637 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
624 638 robust in the face of objects whose dir() returns non-strings
625 639 (which it shouldn't, but some broken libs like ITK do). Thanks to
626 640 a patch by John Hunter (implemented differently, though). Also
627 641 minor improvements by using .extend instead of + on lists.
628 642
629 643 * pysh.py:
630 644
631 645 2005-04-06 Fernando Perez <fperez@colorado.edu>
632 646
633 647 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
634 648 by default, so that all users benefit from it. Those who don't
635 649 want it can still turn it off.
636 650
637 651 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
638 652 config file, I'd forgotten about this, so users were getting it
639 653 off by default.
640 654
641 655 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
642 656 consistency. Now magics can be called in multiline statements,
643 657 and python variables can be expanded in magic calls via $var.
644 658 This makes the magic system behave just like aliases or !system
645 659 calls.
646 660
647 661 2005-03-28 Fernando Perez <fperez@colorado.edu>
648 662
649 663 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
650 664 expensive string additions for building command. Add support for
651 665 trailing ';' when autocall is used.
652 666
653 667 2005-03-26 Fernando Perez <fperez@colorado.edu>
654 668
655 669 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
656 670 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
657 671 ipython.el robust against prompts with any number of spaces
658 672 (including 0) after the ':' character.
659 673
660 674 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
661 675 continuation prompt, which misled users to think the line was
662 676 already indented. Closes debian Bug#300847, reported to me by
663 677 Norbert Tretkowski <tretkowski-AT-inittab.de>.
664 678
665 679 2005-03-23 Fernando Perez <fperez@colorado.edu>
666 680
667 681 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
668 682 properly aligned if they have embedded newlines.
669 683
670 684 * IPython/iplib.py (runlines): Add a public method to expose
671 685 IPython's code execution machinery, so that users can run strings
672 686 as if they had been typed at the prompt interactively.
673 687 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
674 688 methods which can call the system shell, but with python variable
675 689 expansion. The three such methods are: __IPYTHON__.system,
676 690 .getoutput and .getoutputerror. These need to be documented in a
677 691 'public API' section (to be written) of the manual.
678 692
679 693 2005-03-20 Fernando Perez <fperez@colorado.edu>
680 694
681 695 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
682 696 for custom exception handling. This is quite powerful, and it
683 697 allows for user-installable exception handlers which can trap
684 698 custom exceptions at runtime and treat them separately from
685 699 IPython's default mechanisms. At the request of Frédéric
686 700 Mantegazza <mantegazza-AT-ill.fr>.
687 701 (InteractiveShell.set_custom_completer): public API function to
688 702 add new completers at runtime.
689 703
690 704 2005-03-19 Fernando Perez <fperez@colorado.edu>
691 705
692 706 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
693 707 allow objects which provide their docstrings via non-standard
694 708 mechanisms (like Pyro proxies) to still be inspected by ipython's
695 709 ? system.
696 710
697 711 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
698 712 automatic capture system. I tried quite hard to make it work
699 713 reliably, and simply failed. I tried many combinations with the
700 714 subprocess module, but eventually nothing worked in all needed
701 715 cases (not blocking stdin for the child, duplicating stdout
702 716 without blocking, etc). The new %sc/%sx still do capture to these
703 717 magical list/string objects which make shell use much more
704 718 conveninent, so not all is lost.
705 719
706 720 XXX - FIX MANUAL for the change above!
707 721
708 722 (runsource): I copied code.py's runsource() into ipython to modify
709 723 it a bit. Now the code object and source to be executed are
710 724 stored in ipython. This makes this info accessible to third-party
711 725 tools, like custom exception handlers. After a request by Frédéric
712 726 Mantegazza <mantegazza-AT-ill.fr>.
713 727
714 728 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
715 729 history-search via readline (like C-p/C-n). I'd wanted this for a
716 730 long time, but only recently found out how to do it. For users
717 731 who already have their ipythonrc files made and want this, just
718 732 add:
719 733
720 734 readline_parse_and_bind "\e[A": history-search-backward
721 735 readline_parse_and_bind "\e[B": history-search-forward
722 736
723 737 2005-03-18 Fernando Perez <fperez@colorado.edu>
724 738
725 739 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
726 740 LSString and SList classes which allow transparent conversions
727 741 between list mode and whitespace-separated string.
728 742 (magic_r): Fix recursion problem in %r.
729 743
730 744 * IPython/genutils.py (LSString): New class to be used for
731 745 automatic storage of the results of all alias/system calls in _o
732 746 and _e (stdout/err). These provide a .l/.list attribute which
733 747 does automatic splitting on newlines. This means that for most
734 748 uses, you'll never need to do capturing of output with %sc/%sx
735 749 anymore, since ipython keeps this always done for you. Note that
736 750 only the LAST results are stored, the _o/e variables are
737 751 overwritten on each call. If you need to save their contents
738 752 further, simply bind them to any other name.
739 753
740 754 2005-03-17 Fernando Perez <fperez@colorado.edu>
741 755
742 756 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
743 757 prompt namespace handling.
744 758
745 759 2005-03-16 Fernando Perez <fperez@colorado.edu>
746 760
747 761 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
748 762 classic prompts to be '>>> ' (final space was missing, and it
749 763 trips the emacs python mode).
750 764 (BasePrompt.__str__): Added safe support for dynamic prompt
751 765 strings. Now you can set your prompt string to be '$x', and the
752 766 value of x will be printed from your interactive namespace. The
753 767 interpolation syntax includes the full Itpl support, so
754 768 ${foo()+x+bar()} is a valid prompt string now, and the function
755 769 calls will be made at runtime.
756 770
757 771 2005-03-15 Fernando Perez <fperez@colorado.edu>
758 772
759 773 * IPython/Magic.py (magic_history): renamed %hist to %history, to
760 774 avoid name clashes in pylab. %hist still works, it just forwards
761 775 the call to %history.
762 776
763 777 2005-03-02 *** Released version 0.6.12
764 778
765 779 2005-03-02 Fernando Perez <fperez@colorado.edu>
766 780
767 781 * IPython/iplib.py (handle_magic): log magic calls properly as
768 782 ipmagic() function calls.
769 783
770 784 * IPython/Magic.py (magic_time): Improved %time to support
771 785 statements and provide wall-clock as well as CPU time.
772 786
773 787 2005-02-27 Fernando Perez <fperez@colorado.edu>
774 788
775 789 * IPython/hooks.py: New hooks module, to expose user-modifiable
776 790 IPython functionality in a clean manner. For now only the editor
777 791 hook is actually written, and other thigns which I intend to turn
778 792 into proper hooks aren't yet there. The display and prefilter
779 793 stuff, for example, should be hooks. But at least now the
780 794 framework is in place, and the rest can be moved here with more
781 795 time later. IPython had had a .hooks variable for a long time for
782 796 this purpose, but I'd never actually used it for anything.
783 797
784 798 2005-02-26 Fernando Perez <fperez@colorado.edu>
785 799
786 800 * IPython/ipmaker.py (make_IPython): make the default ipython
787 801 directory be called _ipython under win32, to follow more the
788 802 naming peculiarities of that platform (where buggy software like
789 803 Visual Sourcesafe breaks with .named directories). Reported by
790 804 Ville Vainio.
791 805
792 806 2005-02-23 Fernando Perez <fperez@colorado.edu>
793 807
794 808 * IPython/iplib.py (InteractiveShell.__init__): removed a few
795 809 auto_aliases for win32 which were causing problems. Users can
796 810 define the ones they personally like.
797 811
798 812 2005-02-21 Fernando Perez <fperez@colorado.edu>
799 813
800 814 * IPython/Magic.py (magic_time): new magic to time execution of
801 815 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
802 816
803 817 2005-02-19 Fernando Perez <fperez@colorado.edu>
804 818
805 819 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
806 820 into keys (for prompts, for example).
807 821
808 822 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
809 823 prompts in case users want them. This introduces a small behavior
810 824 change: ipython does not automatically add a space to all prompts
811 825 anymore. To get the old prompts with a space, users should add it
812 826 manually to their ipythonrc file, so for example prompt_in1 should
813 827 now read 'In [\#]: ' instead of 'In [\#]:'.
814 828 (BasePrompt.__init__): New option prompts_pad_left (only in rc
815 829 file) to control left-padding of secondary prompts.
816 830
817 831 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
818 832 the profiler can't be imported. Fix for Debian, which removed
819 833 profile.py because of License issues. I applied a slightly
820 834 modified version of the original Debian patch at
821 835 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
822 836
823 837 2005-02-17 Fernando Perez <fperez@colorado.edu>
824 838
825 839 * IPython/genutils.py (native_line_ends): Fix bug which would
826 840 cause improper line-ends under win32 b/c I was not opening files
827 841 in binary mode. Bug report and fix thanks to Ville.
828 842
829 843 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
830 844 trying to catch spurious foo[1] autocalls. My fix actually broke
831 845 ',/' autoquote/call with explicit escape (bad regexp).
832 846
833 847 2005-02-15 *** Released version 0.6.11
834 848
835 849 2005-02-14 Fernando Perez <fperez@colorado.edu>
836 850
837 851 * IPython/background_jobs.py: New background job management
838 852 subsystem. This is implemented via a new set of classes, and
839 853 IPython now provides a builtin 'jobs' object for background job
840 854 execution. A convenience %bg magic serves as a lightweight
841 855 frontend for starting the more common type of calls. This was
842 856 inspired by discussions with B. Granger and the BackgroundCommand
843 857 class described in the book Python Scripting for Computational
844 858 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
845 859 (although ultimately no code from this text was used, as IPython's
846 860 system is a separate implementation).
847 861
848 862 * IPython/iplib.py (MagicCompleter.python_matches): add new option
849 863 to control the completion of single/double underscore names
850 864 separately. As documented in the example ipytonrc file, the
851 865 readline_omit__names variable can now be set to 2, to omit even
852 866 single underscore names. Thanks to a patch by Brian Wong
853 867 <BrianWong-AT-AirgoNetworks.Com>.
854 868 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
855 869 be autocalled as foo([1]) if foo were callable. A problem for
856 870 things which are both callable and implement __getitem__.
857 871 (init_readline): Fix autoindentation for win32. Thanks to a patch
858 872 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
859 873
860 874 2005-02-12 Fernando Perez <fperez@colorado.edu>
861 875
862 876 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
863 877 which I had written long ago to sort out user error messages which
864 878 may occur during startup. This seemed like a good idea initially,
865 879 but it has proven a disaster in retrospect. I don't want to
866 880 change much code for now, so my fix is to set the internal 'debug'
867 881 flag to true everywhere, whose only job was precisely to control
868 882 this subsystem. This closes issue 28 (as well as avoiding all
869 883 sorts of strange hangups which occur from time to time).
870 884
871 885 2005-02-07 Fernando Perez <fperez@colorado.edu>
872 886
873 887 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
874 888 previous call produced a syntax error.
875 889
876 890 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
877 891 classes without constructor.
878 892
879 893 2005-02-06 Fernando Perez <fperez@colorado.edu>
880 894
881 895 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
882 896 completions with the results of each matcher, so we return results
883 897 to the user from all namespaces. This breaks with ipython
884 898 tradition, but I think it's a nicer behavior. Now you get all
885 899 possible completions listed, from all possible namespaces (python,
886 900 filesystem, magics...) After a request by John Hunter
887 901 <jdhunter-AT-nitace.bsd.uchicago.edu>.
888 902
889 903 2005-02-05 Fernando Perez <fperez@colorado.edu>
890 904
891 905 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
892 906 the call had quote characters in it (the quotes were stripped).
893 907
894 908 2005-01-31 Fernando Perez <fperez@colorado.edu>
895 909
896 910 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
897 911 Itpl.itpl() to make the code more robust against psyco
898 912 optimizations.
899 913
900 914 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
901 915 of causing an exception. Quicker, cleaner.
902 916
903 917 2005-01-28 Fernando Perez <fperez@colorado.edu>
904 918
905 919 * scripts/ipython_win_post_install.py (install): hardcode
906 920 sys.prefix+'python.exe' as the executable path. It turns out that
907 921 during the post-installation run, sys.executable resolves to the
908 922 name of the binary installer! I should report this as a distutils
909 923 bug, I think. I updated the .10 release with this tiny fix, to
910 924 avoid annoying the lists further.
911 925
912 926 2005-01-27 *** Released version 0.6.10
913 927
914 928 2005-01-27 Fernando Perez <fperez@colorado.edu>
915 929
916 930 * IPython/numutils.py (norm): Added 'inf' as optional name for
917 931 L-infinity norm, included references to mathworld.com for vector
918 932 norm definitions.
919 933 (amin/amax): added amin/amax for array min/max. Similar to what
920 934 pylab ships with after the recent reorganization of names.
921 935 (spike/spike_odd): removed deprecated spike/spike_odd functions.
922 936
923 937 * ipython.el: committed Alex's recent fixes and improvements.
924 938 Tested with python-mode from CVS, and it looks excellent. Since
925 939 python-mode hasn't released anything in a while, I'm temporarily
926 940 putting a copy of today's CVS (v 4.70) of python-mode in:
927 941 http://ipython.scipy.org/tmp/python-mode.el
928 942
929 943 * scripts/ipython_win_post_install.py (install): Win32 fix to use
930 944 sys.executable for the executable name, instead of assuming it's
931 945 called 'python.exe' (the post-installer would have produced broken
932 946 setups on systems with a differently named python binary).
933 947
934 948 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
935 949 references to os.linesep, to make the code more
936 950 platform-independent. This is also part of the win32 coloring
937 951 fixes.
938 952
939 953 * IPython/genutils.py (page_dumb): Remove attempts to chop long
940 954 lines, which actually cause coloring bugs because the length of
941 955 the line is very difficult to correctly compute with embedded
942 956 escapes. This was the source of all the coloring problems under
943 957 Win32. I think that _finally_, Win32 users have a properly
944 958 working ipython in all respects. This would never have happened
945 959 if not for Gary Bishop and Viktor Ransmayr's great help and work.
946 960
947 961 2005-01-26 *** Released version 0.6.9
948 962
949 963 2005-01-25 Fernando Perez <fperez@colorado.edu>
950 964
951 965 * setup.py: finally, we have a true Windows installer, thanks to
952 966 the excellent work of Viktor Ransmayr
953 967 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
954 968 Windows users. The setup routine is quite a bit cleaner thanks to
955 969 this, and the post-install script uses the proper functions to
956 970 allow a clean de-installation using the standard Windows Control
957 971 Panel.
958 972
959 973 * IPython/genutils.py (get_home_dir): changed to use the $HOME
960 974 environment variable under all OSes (including win32) if
961 975 available. This will give consistency to win32 users who have set
962 976 this variable for any reason. If os.environ['HOME'] fails, the
963 977 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
964 978
965 979 2005-01-24 Fernando Perez <fperez@colorado.edu>
966 980
967 981 * IPython/numutils.py (empty_like): add empty_like(), similar to
968 982 zeros_like() but taking advantage of the new empty() Numeric routine.
969 983
970 984 2005-01-23 *** Released version 0.6.8
971 985
972 986 2005-01-22 Fernando Perez <fperez@colorado.edu>
973 987
974 988 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
975 989 automatic show() calls. After discussing things with JDH, it
976 990 turns out there are too many corner cases where this can go wrong.
977 991 It's best not to try to be 'too smart', and simply have ipython
978 992 reproduce as much as possible the default behavior of a normal
979 993 python shell.
980 994
981 995 * IPython/iplib.py (InteractiveShell.__init__): Modified the
982 996 line-splitting regexp and _prefilter() to avoid calling getattr()
983 997 on assignments. This closes
984 998 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
985 999 readline uses getattr(), so a simple <TAB> keypress is still
986 1000 enough to trigger getattr() calls on an object.
987 1001
988 1002 2005-01-21 Fernando Perez <fperez@colorado.edu>
989 1003
990 1004 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
991 1005 docstring under pylab so it doesn't mask the original.
992 1006
993 1007 2005-01-21 *** Released version 0.6.7
994 1008
995 1009 2005-01-21 Fernando Perez <fperez@colorado.edu>
996 1010
997 1011 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
998 1012 signal handling for win32 users in multithreaded mode.
999 1013
1000 1014 2005-01-17 Fernando Perez <fperez@colorado.edu>
1001 1015
1002 1016 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1003 1017 instances with no __init__. After a crash report by Norbert Nemec
1004 1018 <Norbert-AT-nemec-online.de>.
1005 1019
1006 1020 2005-01-14 Fernando Perez <fperez@colorado.edu>
1007 1021
1008 1022 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1009 1023 names for verbose exceptions, when multiple dotted names and the
1010 1024 'parent' object were present on the same line.
1011 1025
1012 1026 2005-01-11 Fernando Perez <fperez@colorado.edu>
1013 1027
1014 1028 * IPython/genutils.py (flag_calls): new utility to trap and flag
1015 1029 calls in functions. I need it to clean up matplotlib support.
1016 1030 Also removed some deprecated code in genutils.
1017 1031
1018 1032 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1019 1033 that matplotlib scripts called with %run, which don't call show()
1020 1034 themselves, still have their plotting windows open.
1021 1035
1022 1036 2005-01-05 Fernando Perez <fperez@colorado.edu>
1023 1037
1024 1038 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1025 1039 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1026 1040
1027 1041 2004-12-19 Fernando Perez <fperez@colorado.edu>
1028 1042
1029 1043 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1030 1044 parent_runcode, which was an eyesore. The same result can be
1031 1045 obtained with Python's regular superclass mechanisms.
1032 1046
1033 1047 2004-12-17 Fernando Perez <fperez@colorado.edu>
1034 1048
1035 1049 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1036 1050 reported by Prabhu.
1037 1051 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1038 1052 sys.stderr) instead of explicitly calling sys.stderr. This helps
1039 1053 maintain our I/O abstractions clean, for future GUI embeddings.
1040 1054
1041 1055 * IPython/genutils.py (info): added new utility for sys.stderr
1042 1056 unified info message handling (thin wrapper around warn()).
1043 1057
1044 1058 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1045 1059 composite (dotted) names on verbose exceptions.
1046 1060 (VerboseTB.nullrepr): harden against another kind of errors which
1047 1061 Python's inspect module can trigger, and which were crashing
1048 1062 IPython. Thanks to a report by Marco Lombardi
1049 1063 <mlombard-AT-ma010192.hq.eso.org>.
1050 1064
1051 1065 2004-12-13 *** Released version 0.6.6
1052 1066
1053 1067 2004-12-12 Fernando Perez <fperez@colorado.edu>
1054 1068
1055 1069 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1056 1070 generated by pygtk upon initialization if it was built without
1057 1071 threads (for matplotlib users). After a crash reported by
1058 1072 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1059 1073
1060 1074 * IPython/ipmaker.py (make_IPython): fix small bug in the
1061 1075 import_some parameter for multiple imports.
1062 1076
1063 1077 * IPython/iplib.py (ipmagic): simplified the interface of
1064 1078 ipmagic() to take a single string argument, just as it would be
1065 1079 typed at the IPython cmd line.
1066 1080 (ipalias): Added new ipalias() with an interface identical to
1067 1081 ipmagic(). This completes exposing a pure python interface to the
1068 1082 alias and magic system, which can be used in loops or more complex
1069 1083 code where IPython's automatic line mangling is not active.
1070 1084
1071 1085 * IPython/genutils.py (timing): changed interface of timing to
1072 1086 simply run code once, which is the most common case. timings()
1073 1087 remains unchanged, for the cases where you want multiple runs.
1074 1088
1075 1089 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1076 1090 bug where Python2.2 crashes with exec'ing code which does not end
1077 1091 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1078 1092 before.
1079 1093
1080 1094 2004-12-10 Fernando Perez <fperez@colorado.edu>
1081 1095
1082 1096 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1083 1097 -t to -T, to accomodate the new -t flag in %run (the %run and
1084 1098 %prun options are kind of intermixed, and it's not easy to change
1085 1099 this with the limitations of python's getopt).
1086 1100
1087 1101 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1088 1102 the execution of scripts. It's not as fine-tuned as timeit.py,
1089 1103 but it works from inside ipython (and under 2.2, which lacks
1090 1104 timeit.py). Optionally a number of runs > 1 can be given for
1091 1105 timing very short-running code.
1092 1106
1093 1107 * IPython/genutils.py (uniq_stable): new routine which returns a
1094 1108 list of unique elements in any iterable, but in stable order of
1095 1109 appearance. I needed this for the ultraTB fixes, and it's a handy
1096 1110 utility.
1097 1111
1098 1112 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1099 1113 dotted names in Verbose exceptions. This had been broken since
1100 1114 the very start, now x.y will properly be printed in a Verbose
1101 1115 traceback, instead of x being shown and y appearing always as an
1102 1116 'undefined global'. Getting this to work was a bit tricky,
1103 1117 because by default python tokenizers are stateless. Saved by
1104 1118 python's ability to easily add a bit of state to an arbitrary
1105 1119 function (without needing to build a full-blown callable object).
1106 1120
1107 1121 Also big cleanup of this code, which had horrendous runtime
1108 1122 lookups of zillions of attributes for colorization. Moved all
1109 1123 this code into a few templates, which make it cleaner and quicker.
1110 1124
1111 1125 Printout quality was also improved for Verbose exceptions: one
1112 1126 variable per line, and memory addresses are printed (this can be
1113 1127 quite handy in nasty debugging situations, which is what Verbose
1114 1128 is for).
1115 1129
1116 1130 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1117 1131 the command line as scripts to be loaded by embedded instances.
1118 1132 Doing so has the potential for an infinite recursion if there are
1119 1133 exceptions thrown in the process. This fixes a strange crash
1120 1134 reported by Philippe MULLER <muller-AT-irit.fr>.
1121 1135
1122 1136 2004-12-09 Fernando Perez <fperez@colorado.edu>
1123 1137
1124 1138 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1125 1139 to reflect new names in matplotlib, which now expose the
1126 1140 matlab-compatible interface via a pylab module instead of the
1127 1141 'matlab' name. The new code is backwards compatible, so users of
1128 1142 all matplotlib versions are OK. Patch by J. Hunter.
1129 1143
1130 1144 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1131 1145 of __init__ docstrings for instances (class docstrings are already
1132 1146 automatically printed). Instances with customized docstrings
1133 1147 (indep. of the class) are also recognized and all 3 separate
1134 1148 docstrings are printed (instance, class, constructor). After some
1135 1149 comments/suggestions by J. Hunter.
1136 1150
1137 1151 2004-12-05 Fernando Perez <fperez@colorado.edu>
1138 1152
1139 1153 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1140 1154 warnings when tab-completion fails and triggers an exception.
1141 1155
1142 1156 2004-12-03 Fernando Perez <fperez@colorado.edu>
1143 1157
1144 1158 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1145 1159 be triggered when using 'run -p'. An incorrect option flag was
1146 1160 being set ('d' instead of 'D').
1147 1161 (manpage): fix missing escaped \- sign.
1148 1162
1149 1163 2004-11-30 *** Released version 0.6.5
1150 1164
1151 1165 2004-11-30 Fernando Perez <fperez@colorado.edu>
1152 1166
1153 1167 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1154 1168 setting with -d option.
1155 1169
1156 1170 * setup.py (docfiles): Fix problem where the doc glob I was using
1157 1171 was COMPLETELY BROKEN. It was giving the right files by pure
1158 1172 accident, but failed once I tried to include ipython.el. Note:
1159 1173 glob() does NOT allow you to do exclusion on multiple endings!
1160 1174
1161 1175 2004-11-29 Fernando Perez <fperez@colorado.edu>
1162 1176
1163 1177 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1164 1178 the manpage as the source. Better formatting & consistency.
1165 1179
1166 1180 * IPython/Magic.py (magic_run): Added new -d option, to run
1167 1181 scripts under the control of the python pdb debugger. Note that
1168 1182 this required changing the %prun option -d to -D, to avoid a clash
1169 1183 (since %run must pass options to %prun, and getopt is too dumb to
1170 1184 handle options with string values with embedded spaces). Thanks
1171 1185 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1172 1186 (magic_who_ls): added type matching to %who and %whos, so that one
1173 1187 can filter their output to only include variables of certain
1174 1188 types. Another suggestion by Matthew.
1175 1189 (magic_whos): Added memory summaries in kb and Mb for arrays.
1176 1190 (magic_who): Improve formatting (break lines every 9 vars).
1177 1191
1178 1192 2004-11-28 Fernando Perez <fperez@colorado.edu>
1179 1193
1180 1194 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1181 1195 cache when empty lines were present.
1182 1196
1183 1197 2004-11-24 Fernando Perez <fperez@colorado.edu>
1184 1198
1185 1199 * IPython/usage.py (__doc__): document the re-activated threading
1186 1200 options for WX and GTK.
1187 1201
1188 1202 2004-11-23 Fernando Perez <fperez@colorado.edu>
1189 1203
1190 1204 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1191 1205 the -wthread and -gthread options, along with a new -tk one to try
1192 1206 and coordinate Tk threading with wx/gtk. The tk support is very
1193 1207 platform dependent, since it seems to require Tcl and Tk to be
1194 1208 built with threads (Fedora1/2 appears NOT to have it, but in
1195 1209 Prabhu's Debian boxes it works OK). But even with some Tk
1196 1210 limitations, this is a great improvement.
1197 1211
1198 1212 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1199 1213 info in user prompts. Patch by Prabhu.
1200 1214
1201 1215 2004-11-18 Fernando Perez <fperez@colorado.edu>
1202 1216
1203 1217 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1204 1218 EOFErrors and bail, to avoid infinite loops if a non-terminating
1205 1219 file is fed into ipython. Patch submitted in issue 19 by user,
1206 1220 many thanks.
1207 1221
1208 1222 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1209 1223 autoquote/parens in continuation prompts, which can cause lots of
1210 1224 problems. Closes roundup issue 20.
1211 1225
1212 1226 2004-11-17 Fernando Perez <fperez@colorado.edu>
1213 1227
1214 1228 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1215 1229 reported as debian bug #280505. I'm not sure my local changelog
1216 1230 entry has the proper debian format (Jack?).
1217 1231
1218 1232 2004-11-08 *** Released version 0.6.4
1219 1233
1220 1234 2004-11-08 Fernando Perez <fperez@colorado.edu>
1221 1235
1222 1236 * IPython/iplib.py (init_readline): Fix exit message for Windows
1223 1237 when readline is active. Thanks to a report by Eric Jones
1224 1238 <eric-AT-enthought.com>.
1225 1239
1226 1240 2004-11-07 Fernando Perez <fperez@colorado.edu>
1227 1241
1228 1242 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1229 1243 sometimes seen by win2k/cygwin users.
1230 1244
1231 1245 2004-11-06 Fernando Perez <fperez@colorado.edu>
1232 1246
1233 1247 * IPython/iplib.py (interact): Change the handling of %Exit from
1234 1248 trying to propagate a SystemExit to an internal ipython flag.
1235 1249 This is less elegant than using Python's exception mechanism, but
1236 1250 I can't get that to work reliably with threads, so under -pylab
1237 1251 %Exit was hanging IPython. Cross-thread exception handling is
1238 1252 really a bitch. Thaks to a bug report by Stephen Walton
1239 1253 <stephen.walton-AT-csun.edu>.
1240 1254
1241 1255 2004-11-04 Fernando Perez <fperez@colorado.edu>
1242 1256
1243 1257 * IPython/iplib.py (raw_input_original): store a pointer to the
1244 1258 true raw_input to harden against code which can modify it
1245 1259 (wx.py.PyShell does this and would otherwise crash ipython).
1246 1260 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1247 1261
1248 1262 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1249 1263 Ctrl-C problem, which does not mess up the input line.
1250 1264
1251 1265 2004-11-03 Fernando Perez <fperez@colorado.edu>
1252 1266
1253 1267 * IPython/Release.py: Changed licensing to BSD, in all files.
1254 1268 (name): lowercase name for tarball/RPM release.
1255 1269
1256 1270 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1257 1271 use throughout ipython.
1258 1272
1259 1273 * IPython/Magic.py (Magic._ofind): Switch to using the new
1260 1274 OInspect.getdoc() function.
1261 1275
1262 1276 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1263 1277 of the line currently being canceled via Ctrl-C. It's extremely
1264 1278 ugly, but I don't know how to do it better (the problem is one of
1265 1279 handling cross-thread exceptions).
1266 1280
1267 1281 2004-10-28 Fernando Perez <fperez@colorado.edu>
1268 1282
1269 1283 * IPython/Shell.py (signal_handler): add signal handlers to trap
1270 1284 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1271 1285 report by Francesc Alted.
1272 1286
1273 1287 2004-10-21 Fernando Perez <fperez@colorado.edu>
1274 1288
1275 1289 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1276 1290 to % for pysh syntax extensions.
1277 1291
1278 1292 2004-10-09 Fernando Perez <fperez@colorado.edu>
1279 1293
1280 1294 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1281 1295 arrays to print a more useful summary, without calling str(arr).
1282 1296 This avoids the problem of extremely lengthy computations which
1283 1297 occur if arr is large, and appear to the user as a system lockup
1284 1298 with 100% cpu activity. After a suggestion by Kristian Sandberg
1285 1299 <Kristian.Sandberg@colorado.edu>.
1286 1300 (Magic.__init__): fix bug in global magic escapes not being
1287 1301 correctly set.
1288 1302
1289 1303 2004-10-08 Fernando Perez <fperez@colorado.edu>
1290 1304
1291 1305 * IPython/Magic.py (__license__): change to absolute imports of
1292 1306 ipython's own internal packages, to start adapting to the absolute
1293 1307 import requirement of PEP-328.
1294 1308
1295 1309 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1296 1310 files, and standardize author/license marks through the Release
1297 1311 module instead of having per/file stuff (except for files with
1298 1312 particular licenses, like the MIT/PSF-licensed codes).
1299 1313
1300 1314 * IPython/Debugger.py: remove dead code for python 2.1
1301 1315
1302 1316 2004-10-04 Fernando Perez <fperez@colorado.edu>
1303 1317
1304 1318 * IPython/iplib.py (ipmagic): New function for accessing magics
1305 1319 via a normal python function call.
1306 1320
1307 1321 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1308 1322 from '@' to '%', to accomodate the new @decorator syntax of python
1309 1323 2.4.
1310 1324
1311 1325 2004-09-29 Fernando Perez <fperez@colorado.edu>
1312 1326
1313 1327 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1314 1328 matplotlib.use to prevent running scripts which try to switch
1315 1329 interactive backends from within ipython. This will just crash
1316 1330 the python interpreter, so we can't allow it (but a detailed error
1317 1331 is given to the user).
1318 1332
1319 1333 2004-09-28 Fernando Perez <fperez@colorado.edu>
1320 1334
1321 1335 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1322 1336 matplotlib-related fixes so that using @run with non-matplotlib
1323 1337 scripts doesn't pop up spurious plot windows. This requires
1324 1338 matplotlib >= 0.63, where I had to make some changes as well.
1325 1339
1326 1340 * IPython/ipmaker.py (make_IPython): update version requirement to
1327 1341 python 2.2.
1328 1342
1329 1343 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1330 1344 banner arg for embedded customization.
1331 1345
1332 1346 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1333 1347 explicit uses of __IP as the IPython's instance name. Now things
1334 1348 are properly handled via the shell.name value. The actual code
1335 1349 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1336 1350 is much better than before. I'll clean things completely when the
1337 1351 magic stuff gets a real overhaul.
1338 1352
1339 1353 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1340 1354 minor changes to debian dir.
1341 1355
1342 1356 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1343 1357 pointer to the shell itself in the interactive namespace even when
1344 1358 a user-supplied dict is provided. This is needed for embedding
1345 1359 purposes (found by tests with Michel Sanner).
1346 1360
1347 1361 2004-09-27 Fernando Perez <fperez@colorado.edu>
1348 1362
1349 1363 * IPython/UserConfig/ipythonrc: remove []{} from
1350 1364 readline_remove_delims, so that things like [modname.<TAB> do
1351 1365 proper completion. This disables [].TAB, but that's a less common
1352 1366 case than module names in list comprehensions, for example.
1353 1367 Thanks to a report by Andrea Riciputi.
1354 1368
1355 1369 2004-09-09 Fernando Perez <fperez@colorado.edu>
1356 1370
1357 1371 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1358 1372 blocking problems in win32 and osx. Fix by John.
1359 1373
1360 1374 2004-09-08 Fernando Perez <fperez@colorado.edu>
1361 1375
1362 1376 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1363 1377 for Win32 and OSX. Fix by John Hunter.
1364 1378
1365 1379 2004-08-30 *** Released version 0.6.3
1366 1380
1367 1381 2004-08-30 Fernando Perez <fperez@colorado.edu>
1368 1382
1369 1383 * setup.py (isfile): Add manpages to list of dependent files to be
1370 1384 updated.
1371 1385
1372 1386 2004-08-27 Fernando Perez <fperez@colorado.edu>
1373 1387
1374 1388 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1375 1389 for now. They don't really work with standalone WX/GTK code
1376 1390 (though matplotlib IS working fine with both of those backends).
1377 1391 This will neeed much more testing. I disabled most things with
1378 1392 comments, so turning it back on later should be pretty easy.
1379 1393
1380 1394 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1381 1395 autocalling of expressions like r'foo', by modifying the line
1382 1396 split regexp. Closes
1383 1397 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1384 1398 Riley <ipythonbugs-AT-sabi.net>.
1385 1399 (InteractiveShell.mainloop): honor --nobanner with banner
1386 1400 extensions.
1387 1401
1388 1402 * IPython/Shell.py: Significant refactoring of all classes, so
1389 1403 that we can really support ALL matplotlib backends and threading
1390 1404 models (John spotted a bug with Tk which required this). Now we
1391 1405 should support single-threaded, WX-threads and GTK-threads, both
1392 1406 for generic code and for matplotlib.
1393 1407
1394 1408 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1395 1409 -pylab, to simplify things for users. Will also remove the pylab
1396 1410 profile, since now all of matplotlib configuration is directly
1397 1411 handled here. This also reduces startup time.
1398 1412
1399 1413 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1400 1414 shell wasn't being correctly called. Also in IPShellWX.
1401 1415
1402 1416 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1403 1417 fine-tune banner.
1404 1418
1405 1419 * IPython/numutils.py (spike): Deprecate these spike functions,
1406 1420 delete (long deprecated) gnuplot_exec handler.
1407 1421
1408 1422 2004-08-26 Fernando Perez <fperez@colorado.edu>
1409 1423
1410 1424 * ipython.1: Update for threading options, plus some others which
1411 1425 were missing.
1412 1426
1413 1427 * IPython/ipmaker.py (__call__): Added -wthread option for
1414 1428 wxpython thread handling. Make sure threading options are only
1415 1429 valid at the command line.
1416 1430
1417 1431 * scripts/ipython: moved shell selection into a factory function
1418 1432 in Shell.py, to keep the starter script to a minimum.
1419 1433
1420 1434 2004-08-25 Fernando Perez <fperez@colorado.edu>
1421 1435
1422 1436 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1423 1437 John. Along with some recent changes he made to matplotlib, the
1424 1438 next versions of both systems should work very well together.
1425 1439
1426 1440 2004-08-24 Fernando Perez <fperez@colorado.edu>
1427 1441
1428 1442 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1429 1443 tried to switch the profiling to using hotshot, but I'm getting
1430 1444 strange errors from prof.runctx() there. I may be misreading the
1431 1445 docs, but it looks weird. For now the profiling code will
1432 1446 continue to use the standard profiler.
1433 1447
1434 1448 2004-08-23 Fernando Perez <fperez@colorado.edu>
1435 1449
1436 1450 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1437 1451 threaded shell, by John Hunter. It's not quite ready yet, but
1438 1452 close.
1439 1453
1440 1454 2004-08-22 Fernando Perez <fperez@colorado.edu>
1441 1455
1442 1456 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1443 1457 in Magic and ultraTB.
1444 1458
1445 1459 * ipython.1: document threading options in manpage.
1446 1460
1447 1461 * scripts/ipython: Changed name of -thread option to -gthread,
1448 1462 since this is GTK specific. I want to leave the door open for a
1449 1463 -wthread option for WX, which will most likely be necessary. This
1450 1464 change affects usage and ipmaker as well.
1451 1465
1452 1466 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1453 1467 handle the matplotlib shell issues. Code by John Hunter
1454 1468 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1455 1469 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1456 1470 broken (and disabled for end users) for now, but it puts the
1457 1471 infrastructure in place.
1458 1472
1459 1473 2004-08-21 Fernando Perez <fperez@colorado.edu>
1460 1474
1461 1475 * ipythonrc-pylab: Add matplotlib support.
1462 1476
1463 1477 * matplotlib_config.py: new files for matplotlib support, part of
1464 1478 the pylab profile.
1465 1479
1466 1480 * IPython/usage.py (__doc__): documented the threading options.
1467 1481
1468 1482 2004-08-20 Fernando Perez <fperez@colorado.edu>
1469 1483
1470 1484 * ipython: Modified the main calling routine to handle the -thread
1471 1485 and -mpthread options. This needs to be done as a top-level hack,
1472 1486 because it determines which class to instantiate for IPython
1473 1487 itself.
1474 1488
1475 1489 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1476 1490 classes to support multithreaded GTK operation without blocking,
1477 1491 and matplotlib with all backends. This is a lot of still very
1478 1492 experimental code, and threads are tricky. So it may still have a
1479 1493 few rough edges... This code owes a lot to
1480 1494 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1481 1495 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1482 1496 to John Hunter for all the matplotlib work.
1483 1497
1484 1498 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1485 1499 options for gtk thread and matplotlib support.
1486 1500
1487 1501 2004-08-16 Fernando Perez <fperez@colorado.edu>
1488 1502
1489 1503 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1490 1504 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1491 1505 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1492 1506
1493 1507 2004-08-11 Fernando Perez <fperez@colorado.edu>
1494 1508
1495 1509 * setup.py (isfile): Fix build so documentation gets updated for
1496 1510 rpms (it was only done for .tgz builds).
1497 1511
1498 1512 2004-08-10 Fernando Perez <fperez@colorado.edu>
1499 1513
1500 1514 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1501 1515
1502 1516 * iplib.py : Silence syntax error exceptions in tab-completion.
1503 1517
1504 1518 2004-08-05 Fernando Perez <fperez@colorado.edu>
1505 1519
1506 1520 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1507 1521 'color off' mark for continuation prompts. This was causing long
1508 1522 continuation lines to mis-wrap.
1509 1523
1510 1524 2004-08-01 Fernando Perez <fperez@colorado.edu>
1511 1525
1512 1526 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1513 1527 for building ipython to be a parameter. All this is necessary
1514 1528 right now to have a multithreaded version, but this insane
1515 1529 non-design will be cleaned up soon. For now, it's a hack that
1516 1530 works.
1517 1531
1518 1532 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1519 1533 args in various places. No bugs so far, but it's a dangerous
1520 1534 practice.
1521 1535
1522 1536 2004-07-31 Fernando Perez <fperez@colorado.edu>
1523 1537
1524 1538 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1525 1539 fix completion of files with dots in their names under most
1526 1540 profiles (pysh was OK because the completion order is different).
1527 1541
1528 1542 2004-07-27 Fernando Perez <fperez@colorado.edu>
1529 1543
1530 1544 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1531 1545 keywords manually, b/c the one in keyword.py was removed in python
1532 1546 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1533 1547 This is NOT a bug under python 2.3 and earlier.
1534 1548
1535 1549 2004-07-26 Fernando Perez <fperez@colorado.edu>
1536 1550
1537 1551 * IPython/ultraTB.py (VerboseTB.text): Add another
1538 1552 linecache.checkcache() call to try to prevent inspect.py from
1539 1553 crashing under python 2.3. I think this fixes
1540 1554 http://www.scipy.net/roundup/ipython/issue17.
1541 1555
1542 1556 2004-07-26 *** Released version 0.6.2
1543 1557
1544 1558 2004-07-26 Fernando Perez <fperez@colorado.edu>
1545 1559
1546 1560 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1547 1561 fail for any number.
1548 1562 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1549 1563 empty bookmarks.
1550 1564
1551 1565 2004-07-26 *** Released version 0.6.1
1552 1566
1553 1567 2004-07-26 Fernando Perez <fperez@colorado.edu>
1554 1568
1555 1569 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1556 1570
1557 1571 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1558 1572 escaping '()[]{}' in filenames.
1559 1573
1560 1574 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1561 1575 Python 2.2 users who lack a proper shlex.split.
1562 1576
1563 1577 2004-07-19 Fernando Perez <fperez@colorado.edu>
1564 1578
1565 1579 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1566 1580 for reading readline's init file. I follow the normal chain:
1567 1581 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1568 1582 report by Mike Heeter. This closes
1569 1583 http://www.scipy.net/roundup/ipython/issue16.
1570 1584
1571 1585 2004-07-18 Fernando Perez <fperez@colorado.edu>
1572 1586
1573 1587 * IPython/iplib.py (__init__): Add better handling of '\' under
1574 1588 Win32 for filenames. After a patch by Ville.
1575 1589
1576 1590 2004-07-17 Fernando Perez <fperez@colorado.edu>
1577 1591
1578 1592 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1579 1593 autocalling would be triggered for 'foo is bar' if foo is
1580 1594 callable. I also cleaned up the autocall detection code to use a
1581 1595 regexp, which is faster. Bug reported by Alexander Schmolck.
1582 1596
1583 1597 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1584 1598 '?' in them would confuse the help system. Reported by Alex
1585 1599 Schmolck.
1586 1600
1587 1601 2004-07-16 Fernando Perez <fperez@colorado.edu>
1588 1602
1589 1603 * IPython/GnuplotInteractive.py (__all__): added plot2.
1590 1604
1591 1605 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1592 1606 plotting dictionaries, lists or tuples of 1d arrays.
1593 1607
1594 1608 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1595 1609 optimizations.
1596 1610
1597 1611 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1598 1612 the information which was there from Janko's original IPP code:
1599 1613
1600 1614 03.05.99 20:53 porto.ifm.uni-kiel.de
1601 1615 --Started changelog.
1602 1616 --make clear do what it say it does
1603 1617 --added pretty output of lines from inputcache
1604 1618 --Made Logger a mixin class, simplifies handling of switches
1605 1619 --Added own completer class. .string<TAB> expands to last history
1606 1620 line which starts with string. The new expansion is also present
1607 1621 with Ctrl-r from the readline library. But this shows, who this
1608 1622 can be done for other cases.
1609 1623 --Added convention that all shell functions should accept a
1610 1624 parameter_string This opens the door for different behaviour for
1611 1625 each function. @cd is a good example of this.
1612 1626
1613 1627 04.05.99 12:12 porto.ifm.uni-kiel.de
1614 1628 --added logfile rotation
1615 1629 --added new mainloop method which freezes first the namespace
1616 1630
1617 1631 07.05.99 21:24 porto.ifm.uni-kiel.de
1618 1632 --added the docreader classes. Now there is a help system.
1619 1633 -This is only a first try. Currently it's not easy to put new
1620 1634 stuff in the indices. But this is the way to go. Info would be
1621 1635 better, but HTML is every where and not everybody has an info
1622 1636 system installed and it's not so easy to change html-docs to info.
1623 1637 --added global logfile option
1624 1638 --there is now a hook for object inspection method pinfo needs to
1625 1639 be provided for this. Can be reached by two '??'.
1626 1640
1627 1641 08.05.99 20:51 porto.ifm.uni-kiel.de
1628 1642 --added a README
1629 1643 --bug in rc file. Something has changed so functions in the rc
1630 1644 file need to reference the shell and not self. Not clear if it's a
1631 1645 bug or feature.
1632 1646 --changed rc file for new behavior
1633 1647
1634 1648 2004-07-15 Fernando Perez <fperez@colorado.edu>
1635 1649
1636 1650 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1637 1651 cache was falling out of sync in bizarre manners when multi-line
1638 1652 input was present. Minor optimizations and cleanup.
1639 1653
1640 1654 (Logger): Remove old Changelog info for cleanup. This is the
1641 1655 information which was there from Janko's original code:
1642 1656
1643 1657 Changes to Logger: - made the default log filename a parameter
1644 1658
1645 1659 - put a check for lines beginning with !@? in log(). Needed
1646 1660 (even if the handlers properly log their lines) for mid-session
1647 1661 logging activation to work properly. Without this, lines logged
1648 1662 in mid session, which get read from the cache, would end up
1649 1663 'bare' (with !@? in the open) in the log. Now they are caught
1650 1664 and prepended with a #.
1651 1665
1652 1666 * IPython/iplib.py (InteractiveShell.init_readline): added check
1653 1667 in case MagicCompleter fails to be defined, so we don't crash.
1654 1668
1655 1669 2004-07-13 Fernando Perez <fperez@colorado.edu>
1656 1670
1657 1671 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1658 1672 of EPS if the requested filename ends in '.eps'.
1659 1673
1660 1674 2004-07-04 Fernando Perez <fperez@colorado.edu>
1661 1675
1662 1676 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1663 1677 escaping of quotes when calling the shell.
1664 1678
1665 1679 2004-07-02 Fernando Perez <fperez@colorado.edu>
1666 1680
1667 1681 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1668 1682 gettext not working because we were clobbering '_'. Fixes
1669 1683 http://www.scipy.net/roundup/ipython/issue6.
1670 1684
1671 1685 2004-07-01 Fernando Perez <fperez@colorado.edu>
1672 1686
1673 1687 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1674 1688 into @cd. Patch by Ville.
1675 1689
1676 1690 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1677 1691 new function to store things after ipmaker runs. Patch by Ville.
1678 1692 Eventually this will go away once ipmaker is removed and the class
1679 1693 gets cleaned up, but for now it's ok. Key functionality here is
1680 1694 the addition of the persistent storage mechanism, a dict for
1681 1695 keeping data across sessions (for now just bookmarks, but more can
1682 1696 be implemented later).
1683 1697
1684 1698 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1685 1699 persistent across sections. Patch by Ville, I modified it
1686 1700 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1687 1701 added a '-l' option to list all bookmarks.
1688 1702
1689 1703 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1690 1704 center for cleanup. Registered with atexit.register(). I moved
1691 1705 here the old exit_cleanup(). After a patch by Ville.
1692 1706
1693 1707 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1694 1708 characters in the hacked shlex_split for python 2.2.
1695 1709
1696 1710 * IPython/iplib.py (file_matches): more fixes to filenames with
1697 1711 whitespace in them. It's not perfect, but limitations in python's
1698 1712 readline make it impossible to go further.
1699 1713
1700 1714 2004-06-29 Fernando Perez <fperez@colorado.edu>
1701 1715
1702 1716 * IPython/iplib.py (file_matches): escape whitespace correctly in
1703 1717 filename completions. Bug reported by Ville.
1704 1718
1705 1719 2004-06-28 Fernando Perez <fperez@colorado.edu>
1706 1720
1707 1721 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1708 1722 the history file will be called 'history-PROFNAME' (or just
1709 1723 'history' if no profile is loaded). I was getting annoyed at
1710 1724 getting my Numerical work history clobbered by pysh sessions.
1711 1725
1712 1726 * IPython/iplib.py (InteractiveShell.__init__): Internal
1713 1727 getoutputerror() function so that we can honor the system_verbose
1714 1728 flag for _all_ system calls. I also added escaping of #
1715 1729 characters here to avoid confusing Itpl.
1716 1730
1717 1731 * IPython/Magic.py (shlex_split): removed call to shell in
1718 1732 parse_options and replaced it with shlex.split(). The annoying
1719 1733 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1720 1734 to backport it from 2.3, with several frail hacks (the shlex
1721 1735 module is rather limited in 2.2). Thanks to a suggestion by Ville
1722 1736 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1723 1737 problem.
1724 1738
1725 1739 (Magic.magic_system_verbose): new toggle to print the actual
1726 1740 system calls made by ipython. Mainly for debugging purposes.
1727 1741
1728 1742 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1729 1743 doesn't support persistence. Reported (and fix suggested) by
1730 1744 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1731 1745
1732 1746 2004-06-26 Fernando Perez <fperez@colorado.edu>
1733 1747
1734 1748 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1735 1749 continue prompts.
1736 1750
1737 1751 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1738 1752 function (basically a big docstring) and a few more things here to
1739 1753 speedup startup. pysh.py is now very lightweight. We want because
1740 1754 it gets execfile'd, while InterpreterExec gets imported, so
1741 1755 byte-compilation saves time.
1742 1756
1743 1757 2004-06-25 Fernando Perez <fperez@colorado.edu>
1744 1758
1745 1759 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1746 1760 -NUM', which was recently broken.
1747 1761
1748 1762 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1749 1763 in multi-line input (but not !!, which doesn't make sense there).
1750 1764
1751 1765 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1752 1766 It's just too useful, and people can turn it off in the less
1753 1767 common cases where it's a problem.
1754 1768
1755 1769 2004-06-24 Fernando Perez <fperez@colorado.edu>
1756 1770
1757 1771 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1758 1772 special syntaxes (like alias calling) is now allied in multi-line
1759 1773 input. This is still _very_ experimental, but it's necessary for
1760 1774 efficient shell usage combining python looping syntax with system
1761 1775 calls. For now it's restricted to aliases, I don't think it
1762 1776 really even makes sense to have this for magics.
1763 1777
1764 1778 2004-06-23 Fernando Perez <fperez@colorado.edu>
1765 1779
1766 1780 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1767 1781 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1768 1782
1769 1783 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1770 1784 extensions under Windows (after code sent by Gary Bishop). The
1771 1785 extensions considered 'executable' are stored in IPython's rc
1772 1786 structure as win_exec_ext.
1773 1787
1774 1788 * IPython/genutils.py (shell): new function, like system() but
1775 1789 without return value. Very useful for interactive shell work.
1776 1790
1777 1791 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1778 1792 delete aliases.
1779 1793
1780 1794 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1781 1795 sure that the alias table doesn't contain python keywords.
1782 1796
1783 1797 2004-06-21 Fernando Perez <fperez@colorado.edu>
1784 1798
1785 1799 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1786 1800 non-existent items are found in $PATH. Reported by Thorsten.
1787 1801
1788 1802 2004-06-20 Fernando Perez <fperez@colorado.edu>
1789 1803
1790 1804 * IPython/iplib.py (complete): modified the completer so that the
1791 1805 order of priorities can be easily changed at runtime.
1792 1806
1793 1807 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1794 1808 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1795 1809
1796 1810 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1797 1811 expand Python variables prepended with $ in all system calls. The
1798 1812 same was done to InteractiveShell.handle_shell_escape. Now all
1799 1813 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1800 1814 expansion of python variables and expressions according to the
1801 1815 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1802 1816
1803 1817 Though PEP-215 has been rejected, a similar (but simpler) one
1804 1818 seems like it will go into Python 2.4, PEP-292 -
1805 1819 http://www.python.org/peps/pep-0292.html.
1806 1820
1807 1821 I'll keep the full syntax of PEP-215, since IPython has since the
1808 1822 start used Ka-Ping Yee's reference implementation discussed there
1809 1823 (Itpl), and I actually like the powerful semantics it offers.
1810 1824
1811 1825 In order to access normal shell variables, the $ has to be escaped
1812 1826 via an extra $. For example:
1813 1827
1814 1828 In [7]: PATH='a python variable'
1815 1829
1816 1830 In [8]: !echo $PATH
1817 1831 a python variable
1818 1832
1819 1833 In [9]: !echo $$PATH
1820 1834 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1821 1835
1822 1836 (Magic.parse_options): escape $ so the shell doesn't evaluate
1823 1837 things prematurely.
1824 1838
1825 1839 * IPython/iplib.py (InteractiveShell.call_alias): added the
1826 1840 ability for aliases to expand python variables via $.
1827 1841
1828 1842 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1829 1843 system, now there's a @rehash/@rehashx pair of magics. These work
1830 1844 like the csh rehash command, and can be invoked at any time. They
1831 1845 build a table of aliases to everything in the user's $PATH
1832 1846 (@rehash uses everything, @rehashx is slower but only adds
1833 1847 executable files). With this, the pysh.py-based shell profile can
1834 1848 now simply call rehash upon startup, and full access to all
1835 1849 programs in the user's path is obtained.
1836 1850
1837 1851 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1838 1852 functionality is now fully in place. I removed the old dynamic
1839 1853 code generation based approach, in favor of a much lighter one
1840 1854 based on a simple dict. The advantage is that this allows me to
1841 1855 now have thousands of aliases with negligible cost (unthinkable
1842 1856 with the old system).
1843 1857
1844 1858 2004-06-19 Fernando Perez <fperez@colorado.edu>
1845 1859
1846 1860 * IPython/iplib.py (__init__): extended MagicCompleter class to
1847 1861 also complete (last in priority) on user aliases.
1848 1862
1849 1863 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1850 1864 call to eval.
1851 1865 (ItplNS.__init__): Added a new class which functions like Itpl,
1852 1866 but allows configuring the namespace for the evaluation to occur
1853 1867 in.
1854 1868
1855 1869 2004-06-18 Fernando Perez <fperez@colorado.edu>
1856 1870
1857 1871 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1858 1872 better message when 'exit' or 'quit' are typed (a common newbie
1859 1873 confusion).
1860 1874
1861 1875 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1862 1876 check for Windows users.
1863 1877
1864 1878 * IPython/iplib.py (InteractiveShell.user_setup): removed
1865 1879 disabling of colors for Windows. I'll test at runtime and issue a
1866 1880 warning if Gary's readline isn't found, as to nudge users to
1867 1881 download it.
1868 1882
1869 1883 2004-06-16 Fernando Perez <fperez@colorado.edu>
1870 1884
1871 1885 * IPython/genutils.py (Stream.__init__): changed to print errors
1872 1886 to sys.stderr. I had a circular dependency here. Now it's
1873 1887 possible to run ipython as IDLE's shell (consider this pre-alpha,
1874 1888 since true stdout things end up in the starting terminal instead
1875 1889 of IDLE's out).
1876 1890
1877 1891 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1878 1892 users who haven't # updated their prompt_in2 definitions. Remove
1879 1893 eventually.
1880 1894 (multiple_replace): added credit to original ASPN recipe.
1881 1895
1882 1896 2004-06-15 Fernando Perez <fperez@colorado.edu>
1883 1897
1884 1898 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1885 1899 list of auto-defined aliases.
1886 1900
1887 1901 2004-06-13 Fernando Perez <fperez@colorado.edu>
1888 1902
1889 1903 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1890 1904 install was really requested (so setup.py can be used for other
1891 1905 things under Windows).
1892 1906
1893 1907 2004-06-10 Fernando Perez <fperez@colorado.edu>
1894 1908
1895 1909 * IPython/Logger.py (Logger.create_log): Manually remove any old
1896 1910 backup, since os.remove may fail under Windows. Fixes bug
1897 1911 reported by Thorsten.
1898 1912
1899 1913 2004-06-09 Fernando Perez <fperez@colorado.edu>
1900 1914
1901 1915 * examples/example-embed.py: fixed all references to %n (replaced
1902 1916 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1903 1917 for all examples and the manual as well.
1904 1918
1905 1919 2004-06-08 Fernando Perez <fperez@colorado.edu>
1906 1920
1907 1921 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1908 1922 alignment and color management. All 3 prompt subsystems now
1909 1923 inherit from BasePrompt.
1910 1924
1911 1925 * tools/release: updates for windows installer build and tag rpms
1912 1926 with python version (since paths are fixed).
1913 1927
1914 1928 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1915 1929 which will become eventually obsolete. Also fixed the default
1916 1930 prompt_in2 to use \D, so at least new users start with the correct
1917 1931 defaults.
1918 1932 WARNING: Users with existing ipythonrc files will need to apply
1919 1933 this fix manually!
1920 1934
1921 1935 * setup.py: make windows installer (.exe). This is finally the
1922 1936 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1923 1937 which I hadn't included because it required Python 2.3 (or recent
1924 1938 distutils).
1925 1939
1926 1940 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1927 1941 usage of new '\D' escape.
1928 1942
1929 1943 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1930 1944 lacks os.getuid())
1931 1945 (CachedOutput.set_colors): Added the ability to turn coloring
1932 1946 on/off with @colors even for manually defined prompt colors. It
1933 1947 uses a nasty global, but it works safely and via the generic color
1934 1948 handling mechanism.
1935 1949 (Prompt2.__init__): Introduced new escape '\D' for continuation
1936 1950 prompts. It represents the counter ('\#') as dots.
1937 1951 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1938 1952 need to update their ipythonrc files and replace '%n' with '\D' in
1939 1953 their prompt_in2 settings everywhere. Sorry, but there's
1940 1954 otherwise no clean way to get all prompts to properly align. The
1941 1955 ipythonrc shipped with IPython has been updated.
1942 1956
1943 1957 2004-06-07 Fernando Perez <fperez@colorado.edu>
1944 1958
1945 1959 * setup.py (isfile): Pass local_icons option to latex2html, so the
1946 1960 resulting HTML file is self-contained. Thanks to
1947 1961 dryice-AT-liu.com.cn for the tip.
1948 1962
1949 1963 * pysh.py: I created a new profile 'shell', which implements a
1950 1964 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1951 1965 system shell, nor will it become one anytime soon. It's mainly
1952 1966 meant to illustrate the use of the new flexible bash-like prompts.
1953 1967 I guess it could be used by hardy souls for true shell management,
1954 1968 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1955 1969 profile. This uses the InterpreterExec extension provided by
1956 1970 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1957 1971
1958 1972 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1959 1973 auto-align itself with the length of the previous input prompt
1960 1974 (taking into account the invisible color escapes).
1961 1975 (CachedOutput.__init__): Large restructuring of this class. Now
1962 1976 all three prompts (primary1, primary2, output) are proper objects,
1963 1977 managed by the 'parent' CachedOutput class. The code is still a
1964 1978 bit hackish (all prompts share state via a pointer to the cache),
1965 1979 but it's overall far cleaner than before.
1966 1980
1967 1981 * IPython/genutils.py (getoutputerror): modified to add verbose,
1968 1982 debug and header options. This makes the interface of all getout*
1969 1983 functions uniform.
1970 1984 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1971 1985
1972 1986 * IPython/Magic.py (Magic.default_option): added a function to
1973 1987 allow registering default options for any magic command. This
1974 1988 makes it easy to have profiles which customize the magics globally
1975 1989 for a certain use. The values set through this function are
1976 1990 picked up by the parse_options() method, which all magics should
1977 1991 use to parse their options.
1978 1992
1979 1993 * IPython/genutils.py (warn): modified the warnings framework to
1980 1994 use the Term I/O class. I'm trying to slowly unify all of
1981 1995 IPython's I/O operations to pass through Term.
1982 1996
1983 1997 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1984 1998 the secondary prompt to correctly match the length of the primary
1985 1999 one for any prompt. Now multi-line code will properly line up
1986 2000 even for path dependent prompts, such as the new ones available
1987 2001 via the prompt_specials.
1988 2002
1989 2003 2004-06-06 Fernando Perez <fperez@colorado.edu>
1990 2004
1991 2005 * IPython/Prompts.py (prompt_specials): Added the ability to have
1992 2006 bash-like special sequences in the prompts, which get
1993 2007 automatically expanded. Things like hostname, current working
1994 2008 directory and username are implemented already, but it's easy to
1995 2009 add more in the future. Thanks to a patch by W.J. van der Laan
1996 2010 <gnufnork-AT-hetdigitalegat.nl>
1997 2011 (prompt_specials): Added color support for prompt strings, so
1998 2012 users can define arbitrary color setups for their prompts.
1999 2013
2000 2014 2004-06-05 Fernando Perez <fperez@colorado.edu>
2001 2015
2002 2016 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2003 2017 code to load Gary Bishop's readline and configure it
2004 2018 automatically. Thanks to Gary for help on this.
2005 2019
2006 2020 2004-06-01 Fernando Perez <fperez@colorado.edu>
2007 2021
2008 2022 * IPython/Logger.py (Logger.create_log): fix bug for logging
2009 2023 with no filename (previous fix was incomplete).
2010 2024
2011 2025 2004-05-25 Fernando Perez <fperez@colorado.edu>
2012 2026
2013 2027 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2014 2028 parens would get passed to the shell.
2015 2029
2016 2030 2004-05-20 Fernando Perez <fperez@colorado.edu>
2017 2031
2018 2032 * IPython/Magic.py (Magic.magic_prun): changed default profile
2019 2033 sort order to 'time' (the more common profiling need).
2020 2034
2021 2035 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2022 2036 so that source code shown is guaranteed in sync with the file on
2023 2037 disk (also changed in psource). Similar fix to the one for
2024 2038 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2025 2039 <yann.ledu-AT-noos.fr>.
2026 2040
2027 2041 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2028 2042 with a single option would not be correctly parsed. Closes
2029 2043 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2030 2044 introduced in 0.6.0 (on 2004-05-06).
2031 2045
2032 2046 2004-05-13 *** Released version 0.6.0
2033 2047
2034 2048 2004-05-13 Fernando Perez <fperez@colorado.edu>
2035 2049
2036 2050 * debian/: Added debian/ directory to CVS, so that debian support
2037 2051 is publicly accessible. The debian package is maintained by Jack
2038 2052 Moffit <jack-AT-xiph.org>.
2039 2053
2040 2054 * Documentation: included the notes about an ipython-based system
2041 2055 shell (the hypothetical 'pysh') into the new_design.pdf document,
2042 2056 so that these ideas get distributed to users along with the
2043 2057 official documentation.
2044 2058
2045 2059 2004-05-10 Fernando Perez <fperez@colorado.edu>
2046 2060
2047 2061 * IPython/Logger.py (Logger.create_log): fix recently introduced
2048 2062 bug (misindented line) where logstart would fail when not given an
2049 2063 explicit filename.
2050 2064
2051 2065 2004-05-09 Fernando Perez <fperez@colorado.edu>
2052 2066
2053 2067 * IPython/Magic.py (Magic.parse_options): skip system call when
2054 2068 there are no options to look for. Faster, cleaner for the common
2055 2069 case.
2056 2070
2057 2071 * Documentation: many updates to the manual: describing Windows
2058 2072 support better, Gnuplot updates, credits, misc small stuff. Also
2059 2073 updated the new_design doc a bit.
2060 2074
2061 2075 2004-05-06 *** Released version 0.6.0.rc1
2062 2076
2063 2077 2004-05-06 Fernando Perez <fperez@colorado.edu>
2064 2078
2065 2079 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2066 2080 operations to use the vastly more efficient list/''.join() method.
2067 2081 (FormattedTB.text): Fix
2068 2082 http://www.scipy.net/roundup/ipython/issue12 - exception source
2069 2083 extract not updated after reload. Thanks to Mike Salib
2070 2084 <msalib-AT-mit.edu> for pinning the source of the problem.
2071 2085 Fortunately, the solution works inside ipython and doesn't require
2072 2086 any changes to python proper.
2073 2087
2074 2088 * IPython/Magic.py (Magic.parse_options): Improved to process the
2075 2089 argument list as a true shell would (by actually using the
2076 2090 underlying system shell). This way, all @magics automatically get
2077 2091 shell expansion for variables. Thanks to a comment by Alex
2078 2092 Schmolck.
2079 2093
2080 2094 2004-04-04 Fernando Perez <fperez@colorado.edu>
2081 2095
2082 2096 * IPython/iplib.py (InteractiveShell.interact): Added a special
2083 2097 trap for a debugger quit exception, which is basically impossible
2084 2098 to handle by normal mechanisms, given what pdb does to the stack.
2085 2099 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2086 2100
2087 2101 2004-04-03 Fernando Perez <fperez@colorado.edu>
2088 2102
2089 2103 * IPython/genutils.py (Term): Standardized the names of the Term
2090 2104 class streams to cin/cout/cerr, following C++ naming conventions
2091 2105 (I can't use in/out/err because 'in' is not a valid attribute
2092 2106 name).
2093 2107
2094 2108 * IPython/iplib.py (InteractiveShell.interact): don't increment
2095 2109 the prompt if there's no user input. By Daniel 'Dang' Griffith
2096 2110 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2097 2111 Francois Pinard.
2098 2112
2099 2113 2004-04-02 Fernando Perez <fperez@colorado.edu>
2100 2114
2101 2115 * IPython/genutils.py (Stream.__init__): Modified to survive at
2102 2116 least importing in contexts where stdin/out/err aren't true file
2103 2117 objects, such as PyCrust (they lack fileno() and mode). However,
2104 2118 the recovery facilities which rely on these things existing will
2105 2119 not work.
2106 2120
2107 2121 2004-04-01 Fernando Perez <fperez@colorado.edu>
2108 2122
2109 2123 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2110 2124 use the new getoutputerror() function, so it properly
2111 2125 distinguishes stdout/err.
2112 2126
2113 2127 * IPython/genutils.py (getoutputerror): added a function to
2114 2128 capture separately the standard output and error of a command.
2115 2129 After a comment from dang on the mailing lists. This code is
2116 2130 basically a modified version of commands.getstatusoutput(), from
2117 2131 the standard library.
2118 2132
2119 2133 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2120 2134 '!!' as a special syntax (shorthand) to access @sx.
2121 2135
2122 2136 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2123 2137 command and return its output as a list split on '\n'.
2124 2138
2125 2139 2004-03-31 Fernando Perez <fperez@colorado.edu>
2126 2140
2127 2141 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2128 2142 method to dictionaries used as FakeModule instances if they lack
2129 2143 it. At least pydoc in python2.3 breaks for runtime-defined
2130 2144 functions without this hack. At some point I need to _really_
2131 2145 understand what FakeModule is doing, because it's a gross hack.
2132 2146 But it solves Arnd's problem for now...
2133 2147
2134 2148 2004-02-27 Fernando Perez <fperez@colorado.edu>
2135 2149
2136 2150 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2137 2151 mode would behave erratically. Also increased the number of
2138 2152 possible logs in rotate mod to 999. Thanks to Rod Holland
2139 2153 <rhh@StructureLABS.com> for the report and fixes.
2140 2154
2141 2155 2004-02-26 Fernando Perez <fperez@colorado.edu>
2142 2156
2143 2157 * IPython/genutils.py (page): Check that the curses module really
2144 2158 has the initscr attribute before trying to use it. For some
2145 2159 reason, the Solaris curses module is missing this. I think this
2146 2160 should be considered a Solaris python bug, but I'm not sure.
2147 2161
2148 2162 2004-01-17 Fernando Perez <fperez@colorado.edu>
2149 2163
2150 2164 * IPython/genutils.py (Stream.__init__): Changes to try to make
2151 2165 ipython robust against stdin/out/err being closed by the user.
2152 2166 This is 'user error' (and blocks a normal python session, at least
2153 2167 the stdout case). However, Ipython should be able to survive such
2154 2168 instances of abuse as gracefully as possible. To simplify the
2155 2169 coding and maintain compatibility with Gary Bishop's Term
2156 2170 contributions, I've made use of classmethods for this. I think
2157 2171 this introduces a dependency on python 2.2.
2158 2172
2159 2173 2004-01-13 Fernando Perez <fperez@colorado.edu>
2160 2174
2161 2175 * IPython/numutils.py (exp_safe): simplified the code a bit and
2162 2176 removed the need for importing the kinds module altogether.
2163 2177
2164 2178 2004-01-06 Fernando Perez <fperez@colorado.edu>
2165 2179
2166 2180 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2167 2181 a magic function instead, after some community feedback. No
2168 2182 special syntax will exist for it, but its name is deliberately
2169 2183 very short.
2170 2184
2171 2185 2003-12-20 Fernando Perez <fperez@colorado.edu>
2172 2186
2173 2187 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2174 2188 new functionality, to automagically assign the result of a shell
2175 2189 command to a variable. I'll solicit some community feedback on
2176 2190 this before making it permanent.
2177 2191
2178 2192 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2179 2193 requested about callables for which inspect couldn't obtain a
2180 2194 proper argspec. Thanks to a crash report sent by Etienne
2181 2195 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2182 2196
2183 2197 2003-12-09 Fernando Perez <fperez@colorado.edu>
2184 2198
2185 2199 * IPython/genutils.py (page): patch for the pager to work across
2186 2200 various versions of Windows. By Gary Bishop.
2187 2201
2188 2202 2003-12-04 Fernando Perez <fperez@colorado.edu>
2189 2203
2190 2204 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2191 2205 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2192 2206 While I tested this and it looks ok, there may still be corner
2193 2207 cases I've missed.
2194 2208
2195 2209 2003-12-01 Fernando Perez <fperez@colorado.edu>
2196 2210
2197 2211 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2198 2212 where a line like 'p,q=1,2' would fail because the automagic
2199 2213 system would be triggered for @p.
2200 2214
2201 2215 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2202 2216 cleanups, code unmodified.
2203 2217
2204 2218 * IPython/genutils.py (Term): added a class for IPython to handle
2205 2219 output. In most cases it will just be a proxy for stdout/err, but
2206 2220 having this allows modifications to be made for some platforms,
2207 2221 such as handling color escapes under Windows. All of this code
2208 2222 was contributed by Gary Bishop, with minor modifications by me.
2209 2223 The actual changes affect many files.
2210 2224
2211 2225 2003-11-30 Fernando Perez <fperez@colorado.edu>
2212 2226
2213 2227 * IPython/iplib.py (file_matches): new completion code, courtesy
2214 2228 of Jeff Collins. This enables filename completion again under
2215 2229 python 2.3, which disabled it at the C level.
2216 2230
2217 2231 2003-11-11 Fernando Perez <fperez@colorado.edu>
2218 2232
2219 2233 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2220 2234 for Numeric.array(map(...)), but often convenient.
2221 2235
2222 2236 2003-11-05 Fernando Perez <fperez@colorado.edu>
2223 2237
2224 2238 * IPython/numutils.py (frange): Changed a call from int() to
2225 2239 int(round()) to prevent a problem reported with arange() in the
2226 2240 numpy list.
2227 2241
2228 2242 2003-10-06 Fernando Perez <fperez@colorado.edu>
2229 2243
2230 2244 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2231 2245 prevent crashes if sys lacks an argv attribute (it happens with
2232 2246 embedded interpreters which build a bare-bones sys module).
2233 2247 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2234 2248
2235 2249 2003-09-24 Fernando Perez <fperez@colorado.edu>
2236 2250
2237 2251 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2238 2252 to protect against poorly written user objects where __getattr__
2239 2253 raises exceptions other than AttributeError. Thanks to a bug
2240 2254 report by Oliver Sander <osander-AT-gmx.de>.
2241 2255
2242 2256 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2243 2257 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2244 2258
2245 2259 2003-09-09 Fernando Perez <fperez@colorado.edu>
2246 2260
2247 2261 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2248 2262 unpacking a list whith a callable as first element would
2249 2263 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2250 2264 Collins.
2251 2265
2252 2266 2003-08-25 *** Released version 0.5.0
2253 2267
2254 2268 2003-08-22 Fernando Perez <fperez@colorado.edu>
2255 2269
2256 2270 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2257 2271 improperly defined user exceptions. Thanks to feedback from Mark
2258 2272 Russell <mrussell-AT-verio.net>.
2259 2273
2260 2274 2003-08-20 Fernando Perez <fperez@colorado.edu>
2261 2275
2262 2276 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2263 2277 printing so that it would print multi-line string forms starting
2264 2278 with a new line. This way the formatting is better respected for
2265 2279 objects which work hard to make nice string forms.
2266 2280
2267 2281 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2268 2282 autocall would overtake data access for objects with both
2269 2283 __getitem__ and __call__.
2270 2284
2271 2285 2003-08-19 *** Released version 0.5.0-rc1
2272 2286
2273 2287 2003-08-19 Fernando Perez <fperez@colorado.edu>
2274 2288
2275 2289 * IPython/deep_reload.py (load_tail): single tiny change here
2276 2290 seems to fix the long-standing bug of dreload() failing to work
2277 2291 for dotted names. But this module is pretty tricky, so I may have
2278 2292 missed some subtlety. Needs more testing!.
2279 2293
2280 2294 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2281 2295 exceptions which have badly implemented __str__ methods.
2282 2296 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2283 2297 which I've been getting reports about from Python 2.3 users. I
2284 2298 wish I had a simple test case to reproduce the problem, so I could
2285 2299 either write a cleaner workaround or file a bug report if
2286 2300 necessary.
2287 2301
2288 2302 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2289 2303 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2290 2304 a bug report by Tjabo Kloppenburg.
2291 2305
2292 2306 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2293 2307 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2294 2308 seems rather unstable. Thanks to a bug report by Tjabo
2295 2309 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2296 2310
2297 2311 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2298 2312 this out soon because of the critical fixes in the inner loop for
2299 2313 generators.
2300 2314
2301 2315 * IPython/Magic.py (Magic.getargspec): removed. This (and
2302 2316 _get_def) have been obsoleted by OInspect for a long time, I
2303 2317 hadn't noticed that they were dead code.
2304 2318 (Magic._ofind): restored _ofind functionality for a few literals
2305 2319 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2306 2320 for things like "hello".capitalize?, since that would require a
2307 2321 potentially dangerous eval() again.
2308 2322
2309 2323 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2310 2324 logic a bit more to clean up the escapes handling and minimize the
2311 2325 use of _ofind to only necessary cases. The interactive 'feel' of
2312 2326 IPython should have improved quite a bit with the changes in
2313 2327 _prefilter and _ofind (besides being far safer than before).
2314 2328
2315 2329 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2316 2330 obscure, never reported). Edit would fail to find the object to
2317 2331 edit under some circumstances.
2318 2332 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2319 2333 which were causing double-calling of generators. Those eval calls
2320 2334 were _very_ dangerous, since code with side effects could be
2321 2335 triggered. As they say, 'eval is evil'... These were the
2322 2336 nastiest evals in IPython. Besides, _ofind is now far simpler,
2323 2337 and it should also be quite a bit faster. Its use of inspect is
2324 2338 also safer, so perhaps some of the inspect-related crashes I've
2325 2339 seen lately with Python 2.3 might be taken care of. That will
2326 2340 need more testing.
2327 2341
2328 2342 2003-08-17 Fernando Perez <fperez@colorado.edu>
2329 2343
2330 2344 * IPython/iplib.py (InteractiveShell._prefilter): significant
2331 2345 simplifications to the logic for handling user escapes. Faster
2332 2346 and simpler code.
2333 2347
2334 2348 2003-08-14 Fernando Perez <fperez@colorado.edu>
2335 2349
2336 2350 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2337 2351 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2338 2352 but it should be quite a bit faster. And the recursive version
2339 2353 generated O(log N) intermediate storage for all rank>1 arrays,
2340 2354 even if they were contiguous.
2341 2355 (l1norm): Added this function.
2342 2356 (norm): Added this function for arbitrary norms (including
2343 2357 l-infinity). l1 and l2 are still special cases for convenience
2344 2358 and speed.
2345 2359
2346 2360 2003-08-03 Fernando Perez <fperez@colorado.edu>
2347 2361
2348 2362 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2349 2363 exceptions, which now raise PendingDeprecationWarnings in Python
2350 2364 2.3. There were some in Magic and some in Gnuplot2.
2351 2365
2352 2366 2003-06-30 Fernando Perez <fperez@colorado.edu>
2353 2367
2354 2368 * IPython/genutils.py (page): modified to call curses only for
2355 2369 terminals where TERM=='xterm'. After problems under many other
2356 2370 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2357 2371
2358 2372 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2359 2373 would be triggered when readline was absent. This was just an old
2360 2374 debugging statement I'd forgotten to take out.
2361 2375
2362 2376 2003-06-20 Fernando Perez <fperez@colorado.edu>
2363 2377
2364 2378 * IPython/genutils.py (clock): modified to return only user time
2365 2379 (not counting system time), after a discussion on scipy. While
2366 2380 system time may be a useful quantity occasionally, it may much
2367 2381 more easily be skewed by occasional swapping or other similar
2368 2382 activity.
2369 2383
2370 2384 2003-06-05 Fernando Perez <fperez@colorado.edu>
2371 2385
2372 2386 * IPython/numutils.py (identity): new function, for building
2373 2387 arbitrary rank Kronecker deltas (mostly backwards compatible with
2374 2388 Numeric.identity)
2375 2389
2376 2390 2003-06-03 Fernando Perez <fperez@colorado.edu>
2377 2391
2378 2392 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2379 2393 arguments passed to magics with spaces, to allow trailing '\' to
2380 2394 work normally (mainly for Windows users).
2381 2395
2382 2396 2003-05-29 Fernando Perez <fperez@colorado.edu>
2383 2397
2384 2398 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2385 2399 instead of pydoc.help. This fixes a bizarre behavior where
2386 2400 printing '%s' % locals() would trigger the help system. Now
2387 2401 ipython behaves like normal python does.
2388 2402
2389 2403 Note that if one does 'from pydoc import help', the bizarre
2390 2404 behavior returns, but this will also happen in normal python, so
2391 2405 it's not an ipython bug anymore (it has to do with how pydoc.help
2392 2406 is implemented).
2393 2407
2394 2408 2003-05-22 Fernando Perez <fperez@colorado.edu>
2395 2409
2396 2410 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2397 2411 return [] instead of None when nothing matches, also match to end
2398 2412 of line. Patch by Gary Bishop.
2399 2413
2400 2414 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2401 2415 protection as before, for files passed on the command line. This
2402 2416 prevents the CrashHandler from kicking in if user files call into
2403 2417 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2404 2418 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2405 2419
2406 2420 2003-05-20 *** Released version 0.4.0
2407 2421
2408 2422 2003-05-20 Fernando Perez <fperez@colorado.edu>
2409 2423
2410 2424 * setup.py: added support for manpages. It's a bit hackish b/c of
2411 2425 a bug in the way the bdist_rpm distutils target handles gzipped
2412 2426 manpages, but it works. After a patch by Jack.
2413 2427
2414 2428 2003-05-19 Fernando Perez <fperez@colorado.edu>
2415 2429
2416 2430 * IPython/numutils.py: added a mockup of the kinds module, since
2417 2431 it was recently removed from Numeric. This way, numutils will
2418 2432 work for all users even if they are missing kinds.
2419 2433
2420 2434 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2421 2435 failure, which can occur with SWIG-wrapped extensions. After a
2422 2436 crash report from Prabhu.
2423 2437
2424 2438 2003-05-16 Fernando Perez <fperez@colorado.edu>
2425 2439
2426 2440 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2427 2441 protect ipython from user code which may call directly
2428 2442 sys.excepthook (this looks like an ipython crash to the user, even
2429 2443 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2430 2444 This is especially important to help users of WxWindows, but may
2431 2445 also be useful in other cases.
2432 2446
2433 2447 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2434 2448 an optional tb_offset to be specified, and to preserve exception
2435 2449 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2436 2450
2437 2451 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2438 2452
2439 2453 2003-05-15 Fernando Perez <fperez@colorado.edu>
2440 2454
2441 2455 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2442 2456 installing for a new user under Windows.
2443 2457
2444 2458 2003-05-12 Fernando Perez <fperez@colorado.edu>
2445 2459
2446 2460 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2447 2461 handler for Emacs comint-based lines. Currently it doesn't do
2448 2462 much (but importantly, it doesn't update the history cache). In
2449 2463 the future it may be expanded if Alex needs more functionality
2450 2464 there.
2451 2465
2452 2466 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2453 2467 info to crash reports.
2454 2468
2455 2469 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2456 2470 just like Python's -c. Also fixed crash with invalid -color
2457 2471 option value at startup. Thanks to Will French
2458 2472 <wfrench-AT-bestweb.net> for the bug report.
2459 2473
2460 2474 2003-05-09 Fernando Perez <fperez@colorado.edu>
2461 2475
2462 2476 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2463 2477 to EvalDict (it's a mapping, after all) and simplified its code
2464 2478 quite a bit, after a nice discussion on c.l.py where Gustavo
2465 2479 Córdova <gcordova-AT-sismex.com> suggested the new version.
2466 2480
2467 2481 2003-04-30 Fernando Perez <fperez@colorado.edu>
2468 2482
2469 2483 * IPython/genutils.py (timings_out): modified it to reduce its
2470 2484 overhead in the common reps==1 case.
2471 2485
2472 2486 2003-04-29 Fernando Perez <fperez@colorado.edu>
2473 2487
2474 2488 * IPython/genutils.py (timings_out): Modified to use the resource
2475 2489 module, which avoids the wraparound problems of time.clock().
2476 2490
2477 2491 2003-04-17 *** Released version 0.2.15pre4
2478 2492
2479 2493 2003-04-17 Fernando Perez <fperez@colorado.edu>
2480 2494
2481 2495 * setup.py (scriptfiles): Split windows-specific stuff over to a
2482 2496 separate file, in an attempt to have a Windows GUI installer.
2483 2497 That didn't work, but part of the groundwork is done.
2484 2498
2485 2499 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2486 2500 indent/unindent with 4 spaces. Particularly useful in combination
2487 2501 with the new auto-indent option.
2488 2502
2489 2503 2003-04-16 Fernando Perez <fperez@colorado.edu>
2490 2504
2491 2505 * IPython/Magic.py: various replacements of self.rc for
2492 2506 self.shell.rc. A lot more remains to be done to fully disentangle
2493 2507 this class from the main Shell class.
2494 2508
2495 2509 * IPython/GnuplotRuntime.py: added checks for mouse support so
2496 2510 that we don't try to enable it if the current gnuplot doesn't
2497 2511 really support it. Also added checks so that we don't try to
2498 2512 enable persist under Windows (where Gnuplot doesn't recognize the
2499 2513 option).
2500 2514
2501 2515 * IPython/iplib.py (InteractiveShell.interact): Added optional
2502 2516 auto-indenting code, after a patch by King C. Shu
2503 2517 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2504 2518 get along well with pasting indented code. If I ever figure out
2505 2519 how to make that part go well, it will become on by default.
2506 2520
2507 2521 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2508 2522 crash ipython if there was an unmatched '%' in the user's prompt
2509 2523 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2510 2524
2511 2525 * IPython/iplib.py (InteractiveShell.interact): removed the
2512 2526 ability to ask the user whether he wants to crash or not at the
2513 2527 'last line' exception handler. Calling functions at that point
2514 2528 changes the stack, and the error reports would have incorrect
2515 2529 tracebacks.
2516 2530
2517 2531 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2518 2532 pass through a peger a pretty-printed form of any object. After a
2519 2533 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2520 2534
2521 2535 2003-04-14 Fernando Perez <fperez@colorado.edu>
2522 2536
2523 2537 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2524 2538 all files in ~ would be modified at first install (instead of
2525 2539 ~/.ipython). This could be potentially disastrous, as the
2526 2540 modification (make line-endings native) could damage binary files.
2527 2541
2528 2542 2003-04-10 Fernando Perez <fperez@colorado.edu>
2529 2543
2530 2544 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2531 2545 handle only lines which are invalid python. This now means that
2532 2546 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2533 2547 for the bug report.
2534 2548
2535 2549 2003-04-01 Fernando Perez <fperez@colorado.edu>
2536 2550
2537 2551 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2538 2552 where failing to set sys.last_traceback would crash pdb.pm().
2539 2553 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2540 2554 report.
2541 2555
2542 2556 2003-03-25 Fernando Perez <fperez@colorado.edu>
2543 2557
2544 2558 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2545 2559 before printing it (it had a lot of spurious blank lines at the
2546 2560 end).
2547 2561
2548 2562 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2549 2563 output would be sent 21 times! Obviously people don't use this
2550 2564 too often, or I would have heard about it.
2551 2565
2552 2566 2003-03-24 Fernando Perez <fperez@colorado.edu>
2553 2567
2554 2568 * setup.py (scriptfiles): renamed the data_files parameter from
2555 2569 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2556 2570 for the patch.
2557 2571
2558 2572 2003-03-20 Fernando Perez <fperez@colorado.edu>
2559 2573
2560 2574 * IPython/genutils.py (error): added error() and fatal()
2561 2575 functions.
2562 2576
2563 2577 2003-03-18 *** Released version 0.2.15pre3
2564 2578
2565 2579 2003-03-18 Fernando Perez <fperez@colorado.edu>
2566 2580
2567 2581 * setupext/install_data_ext.py
2568 2582 (install_data_ext.initialize_options): Class contributed by Jack
2569 2583 Moffit for fixing the old distutils hack. He is sending this to
2570 2584 the distutils folks so in the future we may not need it as a
2571 2585 private fix.
2572 2586
2573 2587 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2574 2588 changes for Debian packaging. See his patch for full details.
2575 2589 The old distutils hack of making the ipythonrc* files carry a
2576 2590 bogus .py extension is gone, at last. Examples were moved to a
2577 2591 separate subdir under doc/, and the separate executable scripts
2578 2592 now live in their own directory. Overall a great cleanup. The
2579 2593 manual was updated to use the new files, and setup.py has been
2580 2594 fixed for this setup.
2581 2595
2582 2596 * IPython/PyColorize.py (Parser.usage): made non-executable and
2583 2597 created a pycolor wrapper around it to be included as a script.
2584 2598
2585 2599 2003-03-12 *** Released version 0.2.15pre2
2586 2600
2587 2601 2003-03-12 Fernando Perez <fperez@colorado.edu>
2588 2602
2589 2603 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2590 2604 long-standing problem with garbage characters in some terminals.
2591 2605 The issue was really that the \001 and \002 escapes must _only_ be
2592 2606 passed to input prompts (which call readline), but _never_ to
2593 2607 normal text to be printed on screen. I changed ColorANSI to have
2594 2608 two classes: TermColors and InputTermColors, each with the
2595 2609 appropriate escapes for input prompts or normal text. The code in
2596 2610 Prompts.py got slightly more complicated, but this very old and
2597 2611 annoying bug is finally fixed.
2598 2612
2599 2613 All the credit for nailing down the real origin of this problem
2600 2614 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2601 2615 *Many* thanks to him for spending quite a bit of effort on this.
2602 2616
2603 2617 2003-03-05 *** Released version 0.2.15pre1
2604 2618
2605 2619 2003-03-03 Fernando Perez <fperez@colorado.edu>
2606 2620
2607 2621 * IPython/FakeModule.py: Moved the former _FakeModule to a
2608 2622 separate file, because it's also needed by Magic (to fix a similar
2609 2623 pickle-related issue in @run).
2610 2624
2611 2625 2003-03-02 Fernando Perez <fperez@colorado.edu>
2612 2626
2613 2627 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2614 2628 the autocall option at runtime.
2615 2629 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2616 2630 across Magic.py to start separating Magic from InteractiveShell.
2617 2631 (Magic._ofind): Fixed to return proper namespace for dotted
2618 2632 names. Before, a dotted name would always return 'not currently
2619 2633 defined', because it would find the 'parent'. s.x would be found,
2620 2634 but since 'x' isn't defined by itself, it would get confused.
2621 2635 (Magic.magic_run): Fixed pickling problems reported by Ralf
2622 2636 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2623 2637 that I'd used when Mike Heeter reported similar issues at the
2624 2638 top-level, but now for @run. It boils down to injecting the
2625 2639 namespace where code is being executed with something that looks
2626 2640 enough like a module to fool pickle.dump(). Since a pickle stores
2627 2641 a named reference to the importing module, we need this for
2628 2642 pickles to save something sensible.
2629 2643
2630 2644 * IPython/ipmaker.py (make_IPython): added an autocall option.
2631 2645
2632 2646 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2633 2647 the auto-eval code. Now autocalling is an option, and the code is
2634 2648 also vastly safer. There is no more eval() involved at all.
2635 2649
2636 2650 2003-03-01 Fernando Perez <fperez@colorado.edu>
2637 2651
2638 2652 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2639 2653 dict with named keys instead of a tuple.
2640 2654
2641 2655 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2642 2656
2643 2657 * setup.py (make_shortcut): Fixed message about directories
2644 2658 created during Windows installation (the directories were ok, just
2645 2659 the printed message was misleading). Thanks to Chris Liechti
2646 2660 <cliechti-AT-gmx.net> for the heads up.
2647 2661
2648 2662 2003-02-21 Fernando Perez <fperez@colorado.edu>
2649 2663
2650 2664 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2651 2665 of ValueError exception when checking for auto-execution. This
2652 2666 one is raised by things like Numeric arrays arr.flat when the
2653 2667 array is non-contiguous.
2654 2668
2655 2669 2003-01-31 Fernando Perez <fperez@colorado.edu>
2656 2670
2657 2671 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2658 2672 not return any value at all (even though the command would get
2659 2673 executed).
2660 2674 (xsys): Flush stdout right after printing the command to ensure
2661 2675 proper ordering of commands and command output in the total
2662 2676 output.
2663 2677 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2664 2678 system/getoutput as defaults. The old ones are kept for
2665 2679 compatibility reasons, so no code which uses this library needs
2666 2680 changing.
2667 2681
2668 2682 2003-01-27 *** Released version 0.2.14
2669 2683
2670 2684 2003-01-25 Fernando Perez <fperez@colorado.edu>
2671 2685
2672 2686 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2673 2687 functions defined in previous edit sessions could not be re-edited
2674 2688 (because the temp files were immediately removed). Now temp files
2675 2689 are removed only at IPython's exit.
2676 2690 (Magic.magic_run): Improved @run to perform shell-like expansions
2677 2691 on its arguments (~users and $VARS). With this, @run becomes more
2678 2692 like a normal command-line.
2679 2693
2680 2694 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2681 2695 bugs related to embedding and cleaned up that code. A fairly
2682 2696 important one was the impossibility to access the global namespace
2683 2697 through the embedded IPython (only local variables were visible).
2684 2698
2685 2699 2003-01-14 Fernando Perez <fperez@colorado.edu>
2686 2700
2687 2701 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2688 2702 auto-calling to be a bit more conservative. Now it doesn't get
2689 2703 triggered if any of '!=()<>' are in the rest of the input line, to
2690 2704 allow comparing callables. Thanks to Alex for the heads up.
2691 2705
2692 2706 2003-01-07 Fernando Perez <fperez@colorado.edu>
2693 2707
2694 2708 * IPython/genutils.py (page): fixed estimation of the number of
2695 2709 lines in a string to be paged to simply count newlines. This
2696 2710 prevents over-guessing due to embedded escape sequences. A better
2697 2711 long-term solution would involve stripping out the control chars
2698 2712 for the count, but it's potentially so expensive I just don't
2699 2713 think it's worth doing.
2700 2714
2701 2715 2002-12-19 *** Released version 0.2.14pre50
2702 2716
2703 2717 2002-12-19 Fernando Perez <fperez@colorado.edu>
2704 2718
2705 2719 * tools/release (version): Changed release scripts to inform
2706 2720 Andrea and build a NEWS file with a list of recent changes.
2707 2721
2708 2722 * IPython/ColorANSI.py (__all__): changed terminal detection
2709 2723 code. Seems to work better for xterms without breaking
2710 2724 konsole. Will need more testing to determine if WinXP and Mac OSX
2711 2725 also work ok.
2712 2726
2713 2727 2002-12-18 *** Released version 0.2.14pre49
2714 2728
2715 2729 2002-12-18 Fernando Perez <fperez@colorado.edu>
2716 2730
2717 2731 * Docs: added new info about Mac OSX, from Andrea.
2718 2732
2719 2733 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2720 2734 allow direct plotting of python strings whose format is the same
2721 2735 of gnuplot data files.
2722 2736
2723 2737 2002-12-16 Fernando Perez <fperez@colorado.edu>
2724 2738
2725 2739 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2726 2740 value of exit question to be acknowledged.
2727 2741
2728 2742 2002-12-03 Fernando Perez <fperez@colorado.edu>
2729 2743
2730 2744 * IPython/ipmaker.py: removed generators, which had been added
2731 2745 by mistake in an earlier debugging run. This was causing trouble
2732 2746 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2733 2747 for pointing this out.
2734 2748
2735 2749 2002-11-17 Fernando Perez <fperez@colorado.edu>
2736 2750
2737 2751 * Manual: updated the Gnuplot section.
2738 2752
2739 2753 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2740 2754 a much better split of what goes in Runtime and what goes in
2741 2755 Interactive.
2742 2756
2743 2757 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2744 2758 being imported from iplib.
2745 2759
2746 2760 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2747 2761 for command-passing. Now the global Gnuplot instance is called
2748 2762 'gp' instead of 'g', which was really a far too fragile and
2749 2763 common name.
2750 2764
2751 2765 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2752 2766 bounding boxes generated by Gnuplot for square plots.
2753 2767
2754 2768 * IPython/genutils.py (popkey): new function added. I should
2755 2769 suggest this on c.l.py as a dict method, it seems useful.
2756 2770
2757 2771 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2758 2772 to transparently handle PostScript generation. MUCH better than
2759 2773 the previous plot_eps/replot_eps (which I removed now). The code
2760 2774 is also fairly clean and well documented now (including
2761 2775 docstrings).
2762 2776
2763 2777 2002-11-13 Fernando Perez <fperez@colorado.edu>
2764 2778
2765 2779 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2766 2780 (inconsistent with options).
2767 2781
2768 2782 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2769 2783 manually disabled, I don't know why. Fixed it.
2770 2784 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2771 2785 eps output.
2772 2786
2773 2787 2002-11-12 Fernando Perez <fperez@colorado.edu>
2774 2788
2775 2789 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2776 2790 don't propagate up to caller. Fixes crash reported by François
2777 2791 Pinard.
2778 2792
2779 2793 2002-11-09 Fernando Perez <fperez@colorado.edu>
2780 2794
2781 2795 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2782 2796 history file for new users.
2783 2797 (make_IPython): fixed bug where initial install would leave the
2784 2798 user running in the .ipython dir.
2785 2799 (make_IPython): fixed bug where config dir .ipython would be
2786 2800 created regardless of the given -ipythondir option. Thanks to Cory
2787 2801 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2788 2802
2789 2803 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2790 2804 type confirmations. Will need to use it in all of IPython's code
2791 2805 consistently.
2792 2806
2793 2807 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2794 2808 context to print 31 lines instead of the default 5. This will make
2795 2809 the crash reports extremely detailed in case the problem is in
2796 2810 libraries I don't have access to.
2797 2811
2798 2812 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2799 2813 line of defense' code to still crash, but giving users fair
2800 2814 warning. I don't want internal errors to go unreported: if there's
2801 2815 an internal problem, IPython should crash and generate a full
2802 2816 report.
2803 2817
2804 2818 2002-11-08 Fernando Perez <fperez@colorado.edu>
2805 2819
2806 2820 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2807 2821 otherwise uncaught exceptions which can appear if people set
2808 2822 sys.stdout to something badly broken. Thanks to a crash report
2809 2823 from henni-AT-mail.brainbot.com.
2810 2824
2811 2825 2002-11-04 Fernando Perez <fperez@colorado.edu>
2812 2826
2813 2827 * IPython/iplib.py (InteractiveShell.interact): added
2814 2828 __IPYTHON__active to the builtins. It's a flag which goes on when
2815 2829 the interaction starts and goes off again when it stops. This
2816 2830 allows embedding code to detect being inside IPython. Before this
2817 2831 was done via __IPYTHON__, but that only shows that an IPython
2818 2832 instance has been created.
2819 2833
2820 2834 * IPython/Magic.py (Magic.magic_env): I realized that in a
2821 2835 UserDict, instance.data holds the data as a normal dict. So I
2822 2836 modified @env to return os.environ.data instead of rebuilding a
2823 2837 dict by hand.
2824 2838
2825 2839 2002-11-02 Fernando Perez <fperez@colorado.edu>
2826 2840
2827 2841 * IPython/genutils.py (warn): changed so that level 1 prints no
2828 2842 header. Level 2 is now the default (with 'WARNING' header, as
2829 2843 before). I think I tracked all places where changes were needed in
2830 2844 IPython, but outside code using the old level numbering may have
2831 2845 broken.
2832 2846
2833 2847 * IPython/iplib.py (InteractiveShell.runcode): added this to
2834 2848 handle the tracebacks in SystemExit traps correctly. The previous
2835 2849 code (through interact) was printing more of the stack than
2836 2850 necessary, showing IPython internal code to the user.
2837 2851
2838 2852 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2839 2853 default. Now that the default at the confirmation prompt is yes,
2840 2854 it's not so intrusive. François' argument that ipython sessions
2841 2855 tend to be complex enough not to lose them from an accidental C-d,
2842 2856 is a valid one.
2843 2857
2844 2858 * IPython/iplib.py (InteractiveShell.interact): added a
2845 2859 showtraceback() call to the SystemExit trap, and modified the exit
2846 2860 confirmation to have yes as the default.
2847 2861
2848 2862 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2849 2863 this file. It's been gone from the code for a long time, this was
2850 2864 simply leftover junk.
2851 2865
2852 2866 2002-11-01 Fernando Perez <fperez@colorado.edu>
2853 2867
2854 2868 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2855 2869 added. If set, IPython now traps EOF and asks for
2856 2870 confirmation. After a request by François Pinard.
2857 2871
2858 2872 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2859 2873 of @abort, and with a new (better) mechanism for handling the
2860 2874 exceptions.
2861 2875
2862 2876 2002-10-27 Fernando Perez <fperez@colorado.edu>
2863 2877
2864 2878 * IPython/usage.py (__doc__): updated the --help information and
2865 2879 the ipythonrc file to indicate that -log generates
2866 2880 ./ipython.log. Also fixed the corresponding info in @logstart.
2867 2881 This and several other fixes in the manuals thanks to reports by
2868 2882 François Pinard <pinard-AT-iro.umontreal.ca>.
2869 2883
2870 2884 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2871 2885 refer to @logstart (instead of @log, which doesn't exist).
2872 2886
2873 2887 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2874 2888 AttributeError crash. Thanks to Christopher Armstrong
2875 2889 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2876 2890 introduced recently (in 0.2.14pre37) with the fix to the eval
2877 2891 problem mentioned below.
2878 2892
2879 2893 2002-10-17 Fernando Perez <fperez@colorado.edu>
2880 2894
2881 2895 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2882 2896 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2883 2897
2884 2898 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2885 2899 this function to fix a problem reported by Alex Schmolck. He saw
2886 2900 it with list comprehensions and generators, which were getting
2887 2901 called twice. The real problem was an 'eval' call in testing for
2888 2902 automagic which was evaluating the input line silently.
2889 2903
2890 2904 This is a potentially very nasty bug, if the input has side
2891 2905 effects which must not be repeated. The code is much cleaner now,
2892 2906 without any blanket 'except' left and with a regexp test for
2893 2907 actual function names.
2894 2908
2895 2909 But an eval remains, which I'm not fully comfortable with. I just
2896 2910 don't know how to find out if an expression could be a callable in
2897 2911 the user's namespace without doing an eval on the string. However
2898 2912 that string is now much more strictly checked so that no code
2899 2913 slips by, so the eval should only happen for things that can
2900 2914 really be only function/method names.
2901 2915
2902 2916 2002-10-15 Fernando Perez <fperez@colorado.edu>
2903 2917
2904 2918 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2905 2919 OSX information to main manual, removed README_Mac_OSX file from
2906 2920 distribution. Also updated credits for recent additions.
2907 2921
2908 2922 2002-10-10 Fernando Perez <fperez@colorado.edu>
2909 2923
2910 2924 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2911 2925 terminal-related issues. Many thanks to Andrea Riciputi
2912 2926 <andrea.riciputi-AT-libero.it> for writing it.
2913 2927
2914 2928 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2915 2929 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2916 2930
2917 2931 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2918 2932 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2919 2933 <syver-en-AT-online.no> who both submitted patches for this problem.
2920 2934
2921 2935 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2922 2936 global embedding to make sure that things don't overwrite user
2923 2937 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2924 2938
2925 2939 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2926 2940 compatibility. Thanks to Hayden Callow
2927 2941 <h.callow-AT-elec.canterbury.ac.nz>
2928 2942
2929 2943 2002-10-04 Fernando Perez <fperez@colorado.edu>
2930 2944
2931 2945 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2932 2946 Gnuplot.File objects.
2933 2947
2934 2948 2002-07-23 Fernando Perez <fperez@colorado.edu>
2935 2949
2936 2950 * IPython/genutils.py (timing): Added timings() and timing() for
2937 2951 quick access to the most commonly needed data, the execution
2938 2952 times. Old timing() renamed to timings_out().
2939 2953
2940 2954 2002-07-18 Fernando Perez <fperez@colorado.edu>
2941 2955
2942 2956 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2943 2957 bug with nested instances disrupting the parent's tab completion.
2944 2958
2945 2959 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2946 2960 all_completions code to begin the emacs integration.
2947 2961
2948 2962 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2949 2963 argument to allow titling individual arrays when plotting.
2950 2964
2951 2965 2002-07-15 Fernando Perez <fperez@colorado.edu>
2952 2966
2953 2967 * setup.py (make_shortcut): changed to retrieve the value of
2954 2968 'Program Files' directory from the registry (this value changes in
2955 2969 non-english versions of Windows). Thanks to Thomas Fanslau
2956 2970 <tfanslau-AT-gmx.de> for the report.
2957 2971
2958 2972 2002-07-10 Fernando Perez <fperez@colorado.edu>
2959 2973
2960 2974 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2961 2975 a bug in pdb, which crashes if a line with only whitespace is
2962 2976 entered. Bug report submitted to sourceforge.
2963 2977
2964 2978 2002-07-09 Fernando Perez <fperez@colorado.edu>
2965 2979
2966 2980 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2967 2981 reporting exceptions (it's a bug in inspect.py, I just set a
2968 2982 workaround).
2969 2983
2970 2984 2002-07-08 Fernando Perez <fperez@colorado.edu>
2971 2985
2972 2986 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2973 2987 __IPYTHON__ in __builtins__ to show up in user_ns.
2974 2988
2975 2989 2002-07-03 Fernando Perez <fperez@colorado.edu>
2976 2990
2977 2991 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2978 2992 name from @gp_set_instance to @gp_set_default.
2979 2993
2980 2994 * IPython/ipmaker.py (make_IPython): default editor value set to
2981 2995 '0' (a string), to match the rc file. Otherwise will crash when
2982 2996 .strip() is called on it.
2983 2997
2984 2998
2985 2999 2002-06-28 Fernando Perez <fperez@colorado.edu>
2986 3000
2987 3001 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2988 3002 of files in current directory when a file is executed via
2989 3003 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2990 3004
2991 3005 * setup.py (manfiles): fix for rpm builds, submitted by RA
2992 3006 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2993 3007
2994 3008 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2995 3009 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2996 3010 string!). A. Schmolck caught this one.
2997 3011
2998 3012 2002-06-27 Fernando Perez <fperez@colorado.edu>
2999 3013
3000 3014 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3001 3015 defined files at the cmd line. __name__ wasn't being set to
3002 3016 __main__.
3003 3017
3004 3018 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3005 3019 regular lists and tuples besides Numeric arrays.
3006 3020
3007 3021 * IPython/Prompts.py (CachedOutput.__call__): Added output
3008 3022 supression for input ending with ';'. Similar to Mathematica and
3009 3023 Matlab. The _* vars and Out[] list are still updated, just like
3010 3024 Mathematica behaves.
3011 3025
3012 3026 2002-06-25 Fernando Perez <fperez@colorado.edu>
3013 3027
3014 3028 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3015 3029 .ini extensions for profiels under Windows.
3016 3030
3017 3031 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3018 3032 string form. Fix contributed by Alexander Schmolck
3019 3033 <a.schmolck-AT-gmx.net>
3020 3034
3021 3035 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3022 3036 pre-configured Gnuplot instance.
3023 3037
3024 3038 2002-06-21 Fernando Perez <fperez@colorado.edu>
3025 3039
3026 3040 * IPython/numutils.py (exp_safe): new function, works around the
3027 3041 underflow problems in Numeric.
3028 3042 (log2): New fn. Safe log in base 2: returns exact integer answer
3029 3043 for exact integer powers of 2.
3030 3044
3031 3045 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3032 3046 properly.
3033 3047
3034 3048 2002-06-20 Fernando Perez <fperez@colorado.edu>
3035 3049
3036 3050 * IPython/genutils.py (timing): new function like
3037 3051 Mathematica's. Similar to time_test, but returns more info.
3038 3052
3039 3053 2002-06-18 Fernando Perez <fperez@colorado.edu>
3040 3054
3041 3055 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3042 3056 according to Mike Heeter's suggestions.
3043 3057
3044 3058 2002-06-16 Fernando Perez <fperez@colorado.edu>
3045 3059
3046 3060 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3047 3061 system. GnuplotMagic is gone as a user-directory option. New files
3048 3062 make it easier to use all the gnuplot stuff both from external
3049 3063 programs as well as from IPython. Had to rewrite part of
3050 3064 hardcopy() b/c of a strange bug: often the ps files simply don't
3051 3065 get created, and require a repeat of the command (often several
3052 3066 times).
3053 3067
3054 3068 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3055 3069 resolve output channel at call time, so that if sys.stderr has
3056 3070 been redirected by user this gets honored.
3057 3071
3058 3072 2002-06-13 Fernando Perez <fperez@colorado.edu>
3059 3073
3060 3074 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3061 3075 IPShell. Kept a copy with the old names to avoid breaking people's
3062 3076 embedded code.
3063 3077
3064 3078 * IPython/ipython: simplified it to the bare minimum after
3065 3079 Holger's suggestions. Added info about how to use it in
3066 3080 PYTHONSTARTUP.
3067 3081
3068 3082 * IPython/Shell.py (IPythonShell): changed the options passing
3069 3083 from a string with funky %s replacements to a straight list. Maybe
3070 3084 a bit more typing, but it follows sys.argv conventions, so there's
3071 3085 less special-casing to remember.
3072 3086
3073 3087 2002-06-12 Fernando Perez <fperez@colorado.edu>
3074 3088
3075 3089 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3076 3090 command. Thanks to a suggestion by Mike Heeter.
3077 3091 (Magic.magic_pfile): added behavior to look at filenames if given
3078 3092 arg is not a defined object.
3079 3093 (Magic.magic_save): New @save function to save code snippets. Also
3080 3094 a Mike Heeter idea.
3081 3095
3082 3096 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3083 3097 plot() and replot(). Much more convenient now, especially for
3084 3098 interactive use.
3085 3099
3086 3100 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3087 3101 filenames.
3088 3102
3089 3103 2002-06-02 Fernando Perez <fperez@colorado.edu>
3090 3104
3091 3105 * IPython/Struct.py (Struct.__init__): modified to admit
3092 3106 initialization via another struct.
3093 3107
3094 3108 * IPython/genutils.py (SystemExec.__init__): New stateful
3095 3109 interface to xsys and bq. Useful for writing system scripts.
3096 3110
3097 3111 2002-05-30 Fernando Perez <fperez@colorado.edu>
3098 3112
3099 3113 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3100 3114 documents. This will make the user download smaller (it's getting
3101 3115 too big).
3102 3116
3103 3117 2002-05-29 Fernando Perez <fperez@colorado.edu>
3104 3118
3105 3119 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3106 3120 fix problems with shelve and pickle. Seems to work, but I don't
3107 3121 know if corner cases break it. Thanks to Mike Heeter
3108 3122 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3109 3123
3110 3124 2002-05-24 Fernando Perez <fperez@colorado.edu>
3111 3125
3112 3126 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3113 3127 macros having broken.
3114 3128
3115 3129 2002-05-21 Fernando Perez <fperez@colorado.edu>
3116 3130
3117 3131 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3118 3132 introduced logging bug: all history before logging started was
3119 3133 being written one character per line! This came from the redesign
3120 3134 of the input history as a special list which slices to strings,
3121 3135 not to lists.
3122 3136
3123 3137 2002-05-20 Fernando Perez <fperez@colorado.edu>
3124 3138
3125 3139 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3126 3140 be an attribute of all classes in this module. The design of these
3127 3141 classes needs some serious overhauling.
3128 3142
3129 3143 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3130 3144 which was ignoring '_' in option names.
3131 3145
3132 3146 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3133 3147 'Verbose_novars' to 'Context' and made it the new default. It's a
3134 3148 bit more readable and also safer than verbose.
3135 3149
3136 3150 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3137 3151 triple-quoted strings.
3138 3152
3139 3153 * IPython/OInspect.py (__all__): new module exposing the object
3140 3154 introspection facilities. Now the corresponding magics are dummy
3141 3155 wrappers around this. Having this module will make it much easier
3142 3156 to put these functions into our modified pdb.
3143 3157 This new object inspector system uses the new colorizing module,
3144 3158 so source code and other things are nicely syntax highlighted.
3145 3159
3146 3160 2002-05-18 Fernando Perez <fperez@colorado.edu>
3147 3161
3148 3162 * IPython/ColorANSI.py: Split the coloring tools into a separate
3149 3163 module so I can use them in other code easier (they were part of
3150 3164 ultraTB).
3151 3165
3152 3166 2002-05-17 Fernando Perez <fperez@colorado.edu>
3153 3167
3154 3168 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3155 3169 fixed it to set the global 'g' also to the called instance, as
3156 3170 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3157 3171 user's 'g' variables).
3158 3172
3159 3173 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3160 3174 global variables (aliases to _ih,_oh) so that users which expect
3161 3175 In[5] or Out[7] to work aren't unpleasantly surprised.
3162 3176 (InputList.__getslice__): new class to allow executing slices of
3163 3177 input history directly. Very simple class, complements the use of
3164 3178 macros.
3165 3179
3166 3180 2002-05-16 Fernando Perez <fperez@colorado.edu>
3167 3181
3168 3182 * setup.py (docdirbase): make doc directory be just doc/IPython
3169 3183 without version numbers, it will reduce clutter for users.
3170 3184
3171 3185 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3172 3186 execfile call to prevent possible memory leak. See for details:
3173 3187 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3174 3188
3175 3189 2002-05-15 Fernando Perez <fperez@colorado.edu>
3176 3190
3177 3191 * IPython/Magic.py (Magic.magic_psource): made the object
3178 3192 introspection names be more standard: pdoc, pdef, pfile and
3179 3193 psource. They all print/page their output, and it makes
3180 3194 remembering them easier. Kept old names for compatibility as
3181 3195 aliases.
3182 3196
3183 3197 2002-05-14 Fernando Perez <fperez@colorado.edu>
3184 3198
3185 3199 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3186 3200 what the mouse problem was. The trick is to use gnuplot with temp
3187 3201 files and NOT with pipes (for data communication), because having
3188 3202 both pipes and the mouse on is bad news.
3189 3203
3190 3204 2002-05-13 Fernando Perez <fperez@colorado.edu>
3191 3205
3192 3206 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3193 3207 bug. Information would be reported about builtins even when
3194 3208 user-defined functions overrode them.
3195 3209
3196 3210 2002-05-11 Fernando Perez <fperez@colorado.edu>
3197 3211
3198 3212 * IPython/__init__.py (__all__): removed FlexCompleter from
3199 3213 __all__ so that things don't fail in platforms without readline.
3200 3214
3201 3215 2002-05-10 Fernando Perez <fperez@colorado.edu>
3202 3216
3203 3217 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3204 3218 it requires Numeric, effectively making Numeric a dependency for
3205 3219 IPython.
3206 3220
3207 3221 * Released 0.2.13
3208 3222
3209 3223 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3210 3224 profiler interface. Now all the major options from the profiler
3211 3225 module are directly supported in IPython, both for single
3212 3226 expressions (@prun) and for full programs (@run -p).
3213 3227
3214 3228 2002-05-09 Fernando Perez <fperez@colorado.edu>
3215 3229
3216 3230 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3217 3231 magic properly formatted for screen.
3218 3232
3219 3233 * setup.py (make_shortcut): Changed things to put pdf version in
3220 3234 doc/ instead of doc/manual (had to change lyxport a bit).
3221 3235
3222 3236 * IPython/Magic.py (Profile.string_stats): made profile runs go
3223 3237 through pager (they are long and a pager allows searching, saving,
3224 3238 etc.)
3225 3239
3226 3240 2002-05-08 Fernando Perez <fperez@colorado.edu>
3227 3241
3228 3242 * Released 0.2.12
3229 3243
3230 3244 2002-05-06 Fernando Perez <fperez@colorado.edu>
3231 3245
3232 3246 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3233 3247 introduced); 'hist n1 n2' was broken.
3234 3248 (Magic.magic_pdb): added optional on/off arguments to @pdb
3235 3249 (Magic.magic_run): added option -i to @run, which executes code in
3236 3250 the IPython namespace instead of a clean one. Also added @irun as
3237 3251 an alias to @run -i.
3238 3252
3239 3253 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3240 3254 fixed (it didn't really do anything, the namespaces were wrong).
3241 3255
3242 3256 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3243 3257
3244 3258 * IPython/__init__.py (__all__): Fixed package namespace, now
3245 3259 'import IPython' does give access to IPython.<all> as
3246 3260 expected. Also renamed __release__ to Release.
3247 3261
3248 3262 * IPython/Debugger.py (__license__): created new Pdb class which
3249 3263 functions like a drop-in for the normal pdb.Pdb but does NOT
3250 3264 import readline by default. This way it doesn't muck up IPython's
3251 3265 readline handling, and now tab-completion finally works in the
3252 3266 debugger -- sort of. It completes things globally visible, but the
3253 3267 completer doesn't track the stack as pdb walks it. That's a bit
3254 3268 tricky, and I'll have to implement it later.
3255 3269
3256 3270 2002-05-05 Fernando Perez <fperez@colorado.edu>
3257 3271
3258 3272 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3259 3273 magic docstrings when printed via ? (explicit \'s were being
3260 3274 printed).
3261 3275
3262 3276 * IPython/ipmaker.py (make_IPython): fixed namespace
3263 3277 identification bug. Now variables loaded via logs or command-line
3264 3278 files are recognized in the interactive namespace by @who.
3265 3279
3266 3280 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3267 3281 log replay system stemming from the string form of Structs.
3268 3282
3269 3283 * IPython/Magic.py (Macro.__init__): improved macros to properly
3270 3284 handle magic commands in them.
3271 3285 (Magic.magic_logstart): usernames are now expanded so 'logstart
3272 3286 ~/mylog' now works.
3273 3287
3274 3288 * IPython/iplib.py (complete): fixed bug where paths starting with
3275 3289 '/' would be completed as magic names.
3276 3290
3277 3291 2002-05-04 Fernando Perez <fperez@colorado.edu>
3278 3292
3279 3293 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3280 3294 allow running full programs under the profiler's control.
3281 3295
3282 3296 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3283 3297 mode to report exceptions verbosely but without formatting
3284 3298 variables. This addresses the issue of ipython 'freezing' (it's
3285 3299 not frozen, but caught in an expensive formatting loop) when huge
3286 3300 variables are in the context of an exception.
3287 3301 (VerboseTB.text): Added '--->' markers at line where exception was
3288 3302 triggered. Much clearer to read, especially in NoColor modes.
3289 3303
3290 3304 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3291 3305 implemented in reverse when changing to the new parse_options().
3292 3306
3293 3307 2002-05-03 Fernando Perez <fperez@colorado.edu>
3294 3308
3295 3309 * IPython/Magic.py (Magic.parse_options): new function so that
3296 3310 magics can parse options easier.
3297 3311 (Magic.magic_prun): new function similar to profile.run(),
3298 3312 suggested by Chris Hart.
3299 3313 (Magic.magic_cd): fixed behavior so that it only changes if
3300 3314 directory actually is in history.
3301 3315
3302 3316 * IPython/usage.py (__doc__): added information about potential
3303 3317 slowness of Verbose exception mode when there are huge data
3304 3318 structures to be formatted (thanks to Archie Paulson).
3305 3319
3306 3320 * IPython/ipmaker.py (make_IPython): Changed default logging
3307 3321 (when simply called with -log) to use curr_dir/ipython.log in
3308 3322 rotate mode. Fixed crash which was occuring with -log before
3309 3323 (thanks to Jim Boyle).
3310 3324
3311 3325 2002-05-01 Fernando Perez <fperez@colorado.edu>
3312 3326
3313 3327 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3314 3328 was nasty -- though somewhat of a corner case).
3315 3329
3316 3330 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3317 3331 text (was a bug).
3318 3332
3319 3333 2002-04-30 Fernando Perez <fperez@colorado.edu>
3320 3334
3321 3335 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3322 3336 a print after ^D or ^C from the user so that the In[] prompt
3323 3337 doesn't over-run the gnuplot one.
3324 3338
3325 3339 2002-04-29 Fernando Perez <fperez@colorado.edu>
3326 3340
3327 3341 * Released 0.2.10
3328 3342
3329 3343 * IPython/__release__.py (version): get date dynamically.
3330 3344
3331 3345 * Misc. documentation updates thanks to Arnd's comments. Also ran
3332 3346 a full spellcheck on the manual (hadn't been done in a while).
3333 3347
3334 3348 2002-04-27 Fernando Perez <fperez@colorado.edu>
3335 3349
3336 3350 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3337 3351 starting a log in mid-session would reset the input history list.
3338 3352
3339 3353 2002-04-26 Fernando Perez <fperez@colorado.edu>
3340 3354
3341 3355 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3342 3356 all files were being included in an update. Now anything in
3343 3357 UserConfig that matches [A-Za-z]*.py will go (this excludes
3344 3358 __init__.py)
3345 3359
3346 3360 2002-04-25 Fernando Perez <fperez@colorado.edu>
3347 3361
3348 3362 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3349 3363 to __builtins__ so that any form of embedded or imported code can
3350 3364 test for being inside IPython.
3351 3365
3352 3366 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3353 3367 changed to GnuplotMagic because it's now an importable module,
3354 3368 this makes the name follow that of the standard Gnuplot module.
3355 3369 GnuplotMagic can now be loaded at any time in mid-session.
3356 3370
3357 3371 2002-04-24 Fernando Perez <fperez@colorado.edu>
3358 3372
3359 3373 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3360 3374 the globals (IPython has its own namespace) and the
3361 3375 PhysicalQuantity stuff is much better anyway.
3362 3376
3363 3377 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3364 3378 embedding example to standard user directory for
3365 3379 distribution. Also put it in the manual.
3366 3380
3367 3381 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3368 3382 instance as first argument (so it doesn't rely on some obscure
3369 3383 hidden global).
3370 3384
3371 3385 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3372 3386 delimiters. While it prevents ().TAB from working, it allows
3373 3387 completions in open (... expressions. This is by far a more common
3374 3388 case.
3375 3389
3376 3390 2002-04-23 Fernando Perez <fperez@colorado.edu>
3377 3391
3378 3392 * IPython/Extensions/InterpreterPasteInput.py: new
3379 3393 syntax-processing module for pasting lines with >>> or ... at the
3380 3394 start.
3381 3395
3382 3396 * IPython/Extensions/PhysicalQ_Interactive.py
3383 3397 (PhysicalQuantityInteractive.__int__): fixed to work with either
3384 3398 Numeric or math.
3385 3399
3386 3400 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3387 3401 provided profiles. Now we have:
3388 3402 -math -> math module as * and cmath with its own namespace.
3389 3403 -numeric -> Numeric as *, plus gnuplot & grace
3390 3404 -physics -> same as before
3391 3405
3392 3406 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3393 3407 user-defined magics wouldn't be found by @magic if they were
3394 3408 defined as class methods. Also cleaned up the namespace search
3395 3409 logic and the string building (to use %s instead of many repeated
3396 3410 string adds).
3397 3411
3398 3412 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3399 3413 of user-defined magics to operate with class methods (cleaner, in
3400 3414 line with the gnuplot code).
3401 3415
3402 3416 2002-04-22 Fernando Perez <fperez@colorado.edu>
3403 3417
3404 3418 * setup.py: updated dependency list so that manual is updated when
3405 3419 all included files change.
3406 3420
3407 3421 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3408 3422 the delimiter removal option (the fix is ugly right now).
3409 3423
3410 3424 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3411 3425 all of the math profile (quicker loading, no conflict between
3412 3426 g-9.8 and g-gnuplot).
3413 3427
3414 3428 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3415 3429 name of post-mortem files to IPython_crash_report.txt.
3416 3430
3417 3431 * Cleanup/update of the docs. Added all the new readline info and
3418 3432 formatted all lists as 'real lists'.
3419 3433
3420 3434 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3421 3435 tab-completion options, since the full readline parse_and_bind is
3422 3436 now accessible.
3423 3437
3424 3438 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3425 3439 handling of readline options. Now users can specify any string to
3426 3440 be passed to parse_and_bind(), as well as the delimiters to be
3427 3441 removed.
3428 3442 (InteractiveShell.__init__): Added __name__ to the global
3429 3443 namespace so that things like Itpl which rely on its existence
3430 3444 don't crash.
3431 3445 (InteractiveShell._prefilter): Defined the default with a _ so
3432 3446 that prefilter() is easier to override, while the default one
3433 3447 remains available.
3434 3448
3435 3449 2002-04-18 Fernando Perez <fperez@colorado.edu>
3436 3450
3437 3451 * Added information about pdb in the docs.
3438 3452
3439 3453 2002-04-17 Fernando Perez <fperez@colorado.edu>
3440 3454
3441 3455 * IPython/ipmaker.py (make_IPython): added rc_override option to
3442 3456 allow passing config options at creation time which may override
3443 3457 anything set in the config files or command line. This is
3444 3458 particularly useful for configuring embedded instances.
3445 3459
3446 3460 2002-04-15 Fernando Perez <fperez@colorado.edu>
3447 3461
3448 3462 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3449 3463 crash embedded instances because of the input cache falling out of
3450 3464 sync with the output counter.
3451 3465
3452 3466 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3453 3467 mode which calls pdb after an uncaught exception in IPython itself.
3454 3468
3455 3469 2002-04-14 Fernando Perez <fperez@colorado.edu>
3456 3470
3457 3471 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3458 3472 readline, fix it back after each call.
3459 3473
3460 3474 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3461 3475 method to force all access via __call__(), which guarantees that
3462 3476 traceback references are properly deleted.
3463 3477
3464 3478 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3465 3479 improve printing when pprint is in use.
3466 3480
3467 3481 2002-04-13 Fernando Perez <fperez@colorado.edu>
3468 3482
3469 3483 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3470 3484 exceptions aren't caught anymore. If the user triggers one, he
3471 3485 should know why he's doing it and it should go all the way up,
3472 3486 just like any other exception. So now @abort will fully kill the
3473 3487 embedded interpreter and the embedding code (unless that happens
3474 3488 to catch SystemExit).
3475 3489
3476 3490 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3477 3491 and a debugger() method to invoke the interactive pdb debugger
3478 3492 after printing exception information. Also added the corresponding
3479 3493 -pdb option and @pdb magic to control this feature, and updated
3480 3494 the docs. After a suggestion from Christopher Hart
3481 3495 (hart-AT-caltech.edu).
3482 3496
3483 3497 2002-04-12 Fernando Perez <fperez@colorado.edu>
3484 3498
3485 3499 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3486 3500 the exception handlers defined by the user (not the CrashHandler)
3487 3501 so that user exceptions don't trigger an ipython bug report.
3488 3502
3489 3503 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3490 3504 configurable (it should have always been so).
3491 3505
3492 3506 2002-03-26 Fernando Perez <fperez@colorado.edu>
3493 3507
3494 3508 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3495 3509 and there to fix embedding namespace issues. This should all be
3496 3510 done in a more elegant way.
3497 3511
3498 3512 2002-03-25 Fernando Perez <fperez@colorado.edu>
3499 3513
3500 3514 * IPython/genutils.py (get_home_dir): Try to make it work under
3501 3515 win9x also.
3502 3516
3503 3517 2002-03-20 Fernando Perez <fperez@colorado.edu>
3504 3518
3505 3519 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3506 3520 sys.displayhook untouched upon __init__.
3507 3521
3508 3522 2002-03-19 Fernando Perez <fperez@colorado.edu>
3509 3523
3510 3524 * Released 0.2.9 (for embedding bug, basically).
3511 3525
3512 3526 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3513 3527 exceptions so that enclosing shell's state can be restored.
3514 3528
3515 3529 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3516 3530 naming conventions in the .ipython/ dir.
3517 3531
3518 3532 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3519 3533 from delimiters list so filenames with - in them get expanded.
3520 3534
3521 3535 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3522 3536 sys.displayhook not being properly restored after an embedded call.
3523 3537
3524 3538 2002-03-18 Fernando Perez <fperez@colorado.edu>
3525 3539
3526 3540 * Released 0.2.8
3527 3541
3528 3542 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3529 3543 some files weren't being included in a -upgrade.
3530 3544 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3531 3545 on' so that the first tab completes.
3532 3546 (InteractiveShell.handle_magic): fixed bug with spaces around
3533 3547 quotes breaking many magic commands.
3534 3548
3535 3549 * setup.py: added note about ignoring the syntax error messages at
3536 3550 installation.
3537 3551
3538 3552 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3539 3553 streamlining the gnuplot interface, now there's only one magic @gp.
3540 3554
3541 3555 2002-03-17 Fernando Perez <fperez@colorado.edu>
3542 3556
3543 3557 * IPython/UserConfig/magic_gnuplot.py: new name for the
3544 3558 example-magic_pm.py file. Much enhanced system, now with a shell
3545 3559 for communicating directly with gnuplot, one command at a time.
3546 3560
3547 3561 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3548 3562 setting __name__=='__main__'.
3549 3563
3550 3564 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3551 3565 mini-shell for accessing gnuplot from inside ipython. Should
3552 3566 extend it later for grace access too. Inspired by Arnd's
3553 3567 suggestion.
3554 3568
3555 3569 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3556 3570 calling magic functions with () in their arguments. Thanks to Arnd
3557 3571 Baecker for pointing this to me.
3558 3572
3559 3573 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3560 3574 infinitely for integer or complex arrays (only worked with floats).
3561 3575
3562 3576 2002-03-16 Fernando Perez <fperez@colorado.edu>
3563 3577
3564 3578 * setup.py: Merged setup and setup_windows into a single script
3565 3579 which properly handles things for windows users.
3566 3580
3567 3581 2002-03-15 Fernando Perez <fperez@colorado.edu>
3568 3582
3569 3583 * Big change to the manual: now the magics are all automatically
3570 3584 documented. This information is generated from their docstrings
3571 3585 and put in a latex file included by the manual lyx file. This way
3572 3586 we get always up to date information for the magics. The manual
3573 3587 now also has proper version information, also auto-synced.
3574 3588
3575 3589 For this to work, an undocumented --magic_docstrings option was added.
3576 3590
3577 3591 2002-03-13 Fernando Perez <fperez@colorado.edu>
3578 3592
3579 3593 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3580 3594 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3581 3595
3582 3596 2002-03-12 Fernando Perez <fperez@colorado.edu>
3583 3597
3584 3598 * IPython/ultraTB.py (TermColors): changed color escapes again to
3585 3599 fix the (old, reintroduced) line-wrapping bug. Basically, if
3586 3600 \001..\002 aren't given in the color escapes, lines get wrapped
3587 3601 weirdly. But giving those screws up old xterms and emacs terms. So
3588 3602 I added some logic for emacs terms to be ok, but I can't identify old
3589 3603 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3590 3604
3591 3605 2002-03-10 Fernando Perez <fperez@colorado.edu>
3592 3606
3593 3607 * IPython/usage.py (__doc__): Various documentation cleanups and
3594 3608 updates, both in usage docstrings and in the manual.
3595 3609
3596 3610 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3597 3611 handling of caching. Set minimum acceptabe value for having a
3598 3612 cache at 20 values.
3599 3613
3600 3614 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3601 3615 install_first_time function to a method, renamed it and added an
3602 3616 'upgrade' mode. Now people can update their config directory with
3603 3617 a simple command line switch (-upgrade, also new).
3604 3618
3605 3619 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3606 3620 @file (convenient for automagic users under Python >= 2.2).
3607 3621 Removed @files (it seemed more like a plural than an abbrev. of
3608 3622 'file show').
3609 3623
3610 3624 * IPython/iplib.py (install_first_time): Fixed crash if there were
3611 3625 backup files ('~') in .ipython/ install directory.
3612 3626
3613 3627 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3614 3628 system. Things look fine, but these changes are fairly
3615 3629 intrusive. Test them for a few days.
3616 3630
3617 3631 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3618 3632 the prompts system. Now all in/out prompt strings are user
3619 3633 controllable. This is particularly useful for embedding, as one
3620 3634 can tag embedded instances with particular prompts.
3621 3635
3622 3636 Also removed global use of sys.ps1/2, which now allows nested
3623 3637 embeddings without any problems. Added command-line options for
3624 3638 the prompt strings.
3625 3639
3626 3640 2002-03-08 Fernando Perez <fperez@colorado.edu>
3627 3641
3628 3642 * IPython/UserConfig/example-embed-short.py (ipshell): added
3629 3643 example file with the bare minimum code for embedding.
3630 3644
3631 3645 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3632 3646 functionality for the embeddable shell to be activated/deactivated
3633 3647 either globally or at each call.
3634 3648
3635 3649 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3636 3650 rewriting the prompt with '--->' for auto-inputs with proper
3637 3651 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3638 3652 this is handled by the prompts class itself, as it should.
3639 3653
3640 3654 2002-03-05 Fernando Perez <fperez@colorado.edu>
3641 3655
3642 3656 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3643 3657 @logstart to avoid name clashes with the math log function.
3644 3658
3645 3659 * Big updates to X/Emacs section of the manual.
3646 3660
3647 3661 * Removed ipython_emacs. Milan explained to me how to pass
3648 3662 arguments to ipython through Emacs. Some day I'm going to end up
3649 3663 learning some lisp...
3650 3664
3651 3665 2002-03-04 Fernando Perez <fperez@colorado.edu>
3652 3666
3653 3667 * IPython/ipython_emacs: Created script to be used as the
3654 3668 py-python-command Emacs variable so we can pass IPython
3655 3669 parameters. I can't figure out how to tell Emacs directly to pass
3656 3670 parameters to IPython, so a dummy shell script will do it.
3657 3671
3658 3672 Other enhancements made for things to work better under Emacs'
3659 3673 various types of terminals. Many thanks to Milan Zamazal
3660 3674 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3661 3675
3662 3676 2002-03-01 Fernando Perez <fperez@colorado.edu>
3663 3677
3664 3678 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3665 3679 that loading of readline is now optional. This gives better
3666 3680 control to emacs users.
3667 3681
3668 3682 * IPython/ultraTB.py (__date__): Modified color escape sequences
3669 3683 and now things work fine under xterm and in Emacs' term buffers
3670 3684 (though not shell ones). Well, in emacs you get colors, but all
3671 3685 seem to be 'light' colors (no difference between dark and light
3672 3686 ones). But the garbage chars are gone, and also in xterms. It
3673 3687 seems that now I'm using 'cleaner' ansi sequences.
3674 3688
3675 3689 2002-02-21 Fernando Perez <fperez@colorado.edu>
3676 3690
3677 3691 * Released 0.2.7 (mainly to publish the scoping fix).
3678 3692
3679 3693 * IPython/Logger.py (Logger.logstate): added. A corresponding
3680 3694 @logstate magic was created.
3681 3695
3682 3696 * IPython/Magic.py: fixed nested scoping problem under Python
3683 3697 2.1.x (automagic wasn't working).
3684 3698
3685 3699 2002-02-20 Fernando Perez <fperez@colorado.edu>
3686 3700
3687 3701 * Released 0.2.6.
3688 3702
3689 3703 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3690 3704 option so that logs can come out without any headers at all.
3691 3705
3692 3706 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3693 3707 SciPy.
3694 3708
3695 3709 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3696 3710 that embedded IPython calls don't require vars() to be explicitly
3697 3711 passed. Now they are extracted from the caller's frame (code
3698 3712 snatched from Eric Jones' weave). Added better documentation to
3699 3713 the section on embedding and the example file.
3700 3714
3701 3715 * IPython/genutils.py (page): Changed so that under emacs, it just
3702 3716 prints the string. You can then page up and down in the emacs
3703 3717 buffer itself. This is how the builtin help() works.
3704 3718
3705 3719 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3706 3720 macro scoping: macros need to be executed in the user's namespace
3707 3721 to work as if they had been typed by the user.
3708 3722
3709 3723 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3710 3724 execute automatically (no need to type 'exec...'). They then
3711 3725 behave like 'true macros'. The printing system was also modified
3712 3726 for this to work.
3713 3727
3714 3728 2002-02-19 Fernando Perez <fperez@colorado.edu>
3715 3729
3716 3730 * IPython/genutils.py (page_file): new function for paging files
3717 3731 in an OS-independent way. Also necessary for file viewing to work
3718 3732 well inside Emacs buffers.
3719 3733 (page): Added checks for being in an emacs buffer.
3720 3734 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3721 3735 same bug in iplib.
3722 3736
3723 3737 2002-02-18 Fernando Perez <fperez@colorado.edu>
3724 3738
3725 3739 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3726 3740 of readline so that IPython can work inside an Emacs buffer.
3727 3741
3728 3742 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3729 3743 method signatures (they weren't really bugs, but it looks cleaner
3730 3744 and keeps PyChecker happy).
3731 3745
3732 3746 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3733 3747 for implementing various user-defined hooks. Currently only
3734 3748 display is done.
3735 3749
3736 3750 * IPython/Prompts.py (CachedOutput._display): changed display
3737 3751 functions so that they can be dynamically changed by users easily.
3738 3752
3739 3753 * IPython/Extensions/numeric_formats.py (num_display): added an
3740 3754 extension for printing NumPy arrays in flexible manners. It
3741 3755 doesn't do anything yet, but all the structure is in
3742 3756 place. Ultimately the plan is to implement output format control
3743 3757 like in Octave.
3744 3758
3745 3759 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3746 3760 methods are found at run-time by all the automatic machinery.
3747 3761
3748 3762 2002-02-17 Fernando Perez <fperez@colorado.edu>
3749 3763
3750 3764 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3751 3765 whole file a little.
3752 3766
3753 3767 * ToDo: closed this document. Now there's a new_design.lyx
3754 3768 document for all new ideas. Added making a pdf of it for the
3755 3769 end-user distro.
3756 3770
3757 3771 * IPython/Logger.py (Logger.switch_log): Created this to replace
3758 3772 logon() and logoff(). It also fixes a nasty crash reported by
3759 3773 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3760 3774
3761 3775 * IPython/iplib.py (complete): got auto-completion to work with
3762 3776 automagic (I had wanted this for a long time).
3763 3777
3764 3778 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3765 3779 to @file, since file() is now a builtin and clashes with automagic
3766 3780 for @file.
3767 3781
3768 3782 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3769 3783 of this was previously in iplib, which had grown to more than 2000
3770 3784 lines, way too long. No new functionality, but it makes managing
3771 3785 the code a bit easier.
3772 3786
3773 3787 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3774 3788 information to crash reports.
3775 3789
3776 3790 2002-02-12 Fernando Perez <fperez@colorado.edu>
3777 3791
3778 3792 * Released 0.2.5.
3779 3793
3780 3794 2002-02-11 Fernando Perez <fperez@colorado.edu>
3781 3795
3782 3796 * Wrote a relatively complete Windows installer. It puts
3783 3797 everything in place, creates Start Menu entries and fixes the
3784 3798 color issues. Nothing fancy, but it works.
3785 3799
3786 3800 2002-02-10 Fernando Perez <fperez@colorado.edu>
3787 3801
3788 3802 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3789 3803 os.path.expanduser() call so that we can type @run ~/myfile.py and
3790 3804 have thigs work as expected.
3791 3805
3792 3806 * IPython/genutils.py (page): fixed exception handling so things
3793 3807 work both in Unix and Windows correctly. Quitting a pager triggers
3794 3808 an IOError/broken pipe in Unix, and in windows not finding a pager
3795 3809 is also an IOError, so I had to actually look at the return value
3796 3810 of the exception, not just the exception itself. Should be ok now.
3797 3811
3798 3812 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3799 3813 modified to allow case-insensitive color scheme changes.
3800 3814
3801 3815 2002-02-09 Fernando Perez <fperez@colorado.edu>
3802 3816
3803 3817 * IPython/genutils.py (native_line_ends): new function to leave
3804 3818 user config files with os-native line-endings.
3805 3819
3806 3820 * README and manual updates.
3807 3821
3808 3822 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3809 3823 instead of StringType to catch Unicode strings.
3810 3824
3811 3825 * IPython/genutils.py (filefind): fixed bug for paths with
3812 3826 embedded spaces (very common in Windows).
3813 3827
3814 3828 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3815 3829 files under Windows, so that they get automatically associated
3816 3830 with a text editor. Windows makes it a pain to handle
3817 3831 extension-less files.
3818 3832
3819 3833 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3820 3834 warning about readline only occur for Posix. In Windows there's no
3821 3835 way to get readline, so why bother with the warning.
3822 3836
3823 3837 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3824 3838 for __str__ instead of dir(self), since dir() changed in 2.2.
3825 3839
3826 3840 * Ported to Windows! Tested on XP, I suspect it should work fine
3827 3841 on NT/2000, but I don't think it will work on 98 et al. That
3828 3842 series of Windows is such a piece of junk anyway that I won't try
3829 3843 porting it there. The XP port was straightforward, showed a few
3830 3844 bugs here and there (fixed all), in particular some string
3831 3845 handling stuff which required considering Unicode strings (which
3832 3846 Windows uses). This is good, but hasn't been too tested :) No
3833 3847 fancy installer yet, I'll put a note in the manual so people at
3834 3848 least make manually a shortcut.
3835 3849
3836 3850 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3837 3851 into a single one, "colors". This now controls both prompt and
3838 3852 exception color schemes, and can be changed both at startup
3839 3853 (either via command-line switches or via ipythonrc files) and at
3840 3854 runtime, with @colors.
3841 3855 (Magic.magic_run): renamed @prun to @run and removed the old
3842 3856 @run. The two were too similar to warrant keeping both.
3843 3857
3844 3858 2002-02-03 Fernando Perez <fperez@colorado.edu>
3845 3859
3846 3860 * IPython/iplib.py (install_first_time): Added comment on how to
3847 3861 configure the color options for first-time users. Put a <return>
3848 3862 request at the end so that small-terminal users get a chance to
3849 3863 read the startup info.
3850 3864
3851 3865 2002-01-23 Fernando Perez <fperez@colorado.edu>
3852 3866
3853 3867 * IPython/iplib.py (CachedOutput.update): Changed output memory
3854 3868 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3855 3869 input history we still use _i. Did this b/c these variable are
3856 3870 very commonly used in interactive work, so the less we need to
3857 3871 type the better off we are.
3858 3872 (Magic.magic_prun): updated @prun to better handle the namespaces
3859 3873 the file will run in, including a fix for __name__ not being set
3860 3874 before.
3861 3875
3862 3876 2002-01-20 Fernando Perez <fperez@colorado.edu>
3863 3877
3864 3878 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3865 3879 extra garbage for Python 2.2. Need to look more carefully into
3866 3880 this later.
3867 3881
3868 3882 2002-01-19 Fernando Perez <fperez@colorado.edu>
3869 3883
3870 3884 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3871 3885 display SyntaxError exceptions properly formatted when they occur
3872 3886 (they can be triggered by imported code).
3873 3887
3874 3888 2002-01-18 Fernando Perez <fperez@colorado.edu>
3875 3889
3876 3890 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3877 3891 SyntaxError exceptions are reported nicely formatted, instead of
3878 3892 spitting out only offset information as before.
3879 3893 (Magic.magic_prun): Added the @prun function for executing
3880 3894 programs with command line args inside IPython.
3881 3895
3882 3896 2002-01-16 Fernando Perez <fperez@colorado.edu>
3883 3897
3884 3898 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3885 3899 to *not* include the last item given in a range. This brings their
3886 3900 behavior in line with Python's slicing:
3887 3901 a[n1:n2] -> a[n1]...a[n2-1]
3888 3902 It may be a bit less convenient, but I prefer to stick to Python's
3889 3903 conventions *everywhere*, so users never have to wonder.
3890 3904 (Magic.magic_macro): Added @macro function to ease the creation of
3891 3905 macros.
3892 3906
3893 3907 2002-01-05 Fernando Perez <fperez@colorado.edu>
3894 3908
3895 3909 * Released 0.2.4.
3896 3910
3897 3911 * IPython/iplib.py (Magic.magic_pdef):
3898 3912 (InteractiveShell.safe_execfile): report magic lines and error
3899 3913 lines without line numbers so one can easily copy/paste them for
3900 3914 re-execution.
3901 3915
3902 3916 * Updated manual with recent changes.
3903 3917
3904 3918 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3905 3919 docstring printing when class? is called. Very handy for knowing
3906 3920 how to create class instances (as long as __init__ is well
3907 3921 documented, of course :)
3908 3922 (Magic.magic_doc): print both class and constructor docstrings.
3909 3923 (Magic.magic_pdef): give constructor info if passed a class and
3910 3924 __call__ info for callable object instances.
3911 3925
3912 3926 2002-01-04 Fernando Perez <fperez@colorado.edu>
3913 3927
3914 3928 * Made deep_reload() off by default. It doesn't always work
3915 3929 exactly as intended, so it's probably safer to have it off. It's
3916 3930 still available as dreload() anyway, so nothing is lost.
3917 3931
3918 3932 2002-01-02 Fernando Perez <fperez@colorado.edu>
3919 3933
3920 3934 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3921 3935 so I wanted an updated release).
3922 3936
3923 3937 2001-12-27 Fernando Perez <fperez@colorado.edu>
3924 3938
3925 3939 * IPython/iplib.py (InteractiveShell.interact): Added the original
3926 3940 code from 'code.py' for this module in order to change the
3927 3941 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3928 3942 the history cache would break when the user hit Ctrl-C, and
3929 3943 interact() offers no way to add any hooks to it.
3930 3944
3931 3945 2001-12-23 Fernando Perez <fperez@colorado.edu>
3932 3946
3933 3947 * setup.py: added check for 'MANIFEST' before trying to remove
3934 3948 it. Thanks to Sean Reifschneider.
3935 3949
3936 3950 2001-12-22 Fernando Perez <fperez@colorado.edu>
3937 3951
3938 3952 * Released 0.2.2.
3939 3953
3940 3954 * Finished (reasonably) writing the manual. Later will add the
3941 3955 python-standard navigation stylesheets, but for the time being
3942 3956 it's fairly complete. Distribution will include html and pdf
3943 3957 versions.
3944 3958
3945 3959 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3946 3960 (MayaVi author).
3947 3961
3948 3962 2001-12-21 Fernando Perez <fperez@colorado.edu>
3949 3963
3950 3964 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3951 3965 good public release, I think (with the manual and the distutils
3952 3966 installer). The manual can use some work, but that can go
3953 3967 slowly. Otherwise I think it's quite nice for end users. Next
3954 3968 summer, rewrite the guts of it...
3955 3969
3956 3970 * Changed format of ipythonrc files to use whitespace as the
3957 3971 separator instead of an explicit '='. Cleaner.
3958 3972
3959 3973 2001-12-20 Fernando Perez <fperez@colorado.edu>
3960 3974
3961 3975 * Started a manual in LyX. For now it's just a quick merge of the
3962 3976 various internal docstrings and READMEs. Later it may grow into a
3963 3977 nice, full-blown manual.
3964 3978
3965 3979 * Set up a distutils based installer. Installation should now be
3966 3980 trivially simple for end-users.
3967 3981
3968 3982 2001-12-11 Fernando Perez <fperez@colorado.edu>
3969 3983
3970 3984 * Released 0.2.0. First public release, announced it at
3971 3985 comp.lang.python. From now on, just bugfixes...
3972 3986
3973 3987 * Went through all the files, set copyright/license notices and
3974 3988 cleaned up things. Ready for release.
3975 3989
3976 3990 2001-12-10 Fernando Perez <fperez@colorado.edu>
3977 3991
3978 3992 * Changed the first-time installer not to use tarfiles. It's more
3979 3993 robust now and less unix-dependent. Also makes it easier for
3980 3994 people to later upgrade versions.
3981 3995
3982 3996 * Changed @exit to @abort to reflect the fact that it's pretty
3983 3997 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3984 3998 becomes significant only when IPyhton is embedded: in that case,
3985 3999 C-D closes IPython only, but @abort kills the enclosing program
3986 4000 too (unless it had called IPython inside a try catching
3987 4001 SystemExit).
3988 4002
3989 4003 * Created Shell module which exposes the actuall IPython Shell
3990 4004 classes, currently the normal and the embeddable one. This at
3991 4005 least offers a stable interface we won't need to change when
3992 4006 (later) the internals are rewritten. That rewrite will be confined
3993 4007 to iplib and ipmaker, but the Shell interface should remain as is.
3994 4008
3995 4009 * Added embed module which offers an embeddable IPShell object,
3996 4010 useful to fire up IPython *inside* a running program. Great for
3997 4011 debugging or dynamical data analysis.
3998 4012
3999 4013 2001-12-08 Fernando Perez <fperez@colorado.edu>
4000 4014
4001 4015 * Fixed small bug preventing seeing info from methods of defined
4002 4016 objects (incorrect namespace in _ofind()).
4003 4017
4004 4018 * Documentation cleanup. Moved the main usage docstrings to a
4005 4019 separate file, usage.py (cleaner to maintain, and hopefully in the
4006 4020 future some perlpod-like way of producing interactive, man and
4007 4021 html docs out of it will be found).
4008 4022
4009 4023 * Added @profile to see your profile at any time.
4010 4024
4011 4025 * Added @p as an alias for 'print'. It's especially convenient if
4012 4026 using automagic ('p x' prints x).
4013 4027
4014 4028 * Small cleanups and fixes after a pychecker run.
4015 4029
4016 4030 * Changed the @cd command to handle @cd - and @cd -<n> for
4017 4031 visiting any directory in _dh.
4018 4032
4019 4033 * Introduced _dh, a history of visited directories. @dhist prints
4020 4034 it out with numbers.
4021 4035
4022 4036 2001-12-07 Fernando Perez <fperez@colorado.edu>
4023 4037
4024 4038 * Released 0.1.22
4025 4039
4026 4040 * Made initialization a bit more robust against invalid color
4027 4041 options in user input (exit, not traceback-crash).
4028 4042
4029 4043 * Changed the bug crash reporter to write the report only in the
4030 4044 user's .ipython directory. That way IPython won't litter people's
4031 4045 hard disks with crash files all over the place. Also print on
4032 4046 screen the necessary mail command.
4033 4047
4034 4048 * With the new ultraTB, implemented LightBG color scheme for light
4035 4049 background terminals. A lot of people like white backgrounds, so I
4036 4050 guess we should at least give them something readable.
4037 4051
4038 4052 2001-12-06 Fernando Perez <fperez@colorado.edu>
4039 4053
4040 4054 * Modified the structure of ultraTB. Now there's a proper class
4041 4055 for tables of color schemes which allow adding schemes easily and
4042 4056 switching the active scheme without creating a new instance every
4043 4057 time (which was ridiculous). The syntax for creating new schemes
4044 4058 is also cleaner. I think ultraTB is finally done, with a clean
4045 4059 class structure. Names are also much cleaner (now there's proper
4046 4060 color tables, no need for every variable to also have 'color' in
4047 4061 its name).
4048 4062
4049 4063 * Broke down genutils into separate files. Now genutils only
4050 4064 contains utility functions, and classes have been moved to their
4051 4065 own files (they had enough independent functionality to warrant
4052 4066 it): ConfigLoader, OutputTrap, Struct.
4053 4067
4054 4068 2001-12-05 Fernando Perez <fperez@colorado.edu>
4055 4069
4056 4070 * IPython turns 21! Released version 0.1.21, as a candidate for
4057 4071 public consumption. If all goes well, release in a few days.
4058 4072
4059 4073 * Fixed path bug (files in Extensions/ directory wouldn't be found
4060 4074 unless IPython/ was explicitly in sys.path).
4061 4075
4062 4076 * Extended the FlexCompleter class as MagicCompleter to allow
4063 4077 completion of @-starting lines.
4064 4078
4065 4079 * Created __release__.py file as a central repository for release
4066 4080 info that other files can read from.
4067 4081
4068 4082 * Fixed small bug in logging: when logging was turned on in
4069 4083 mid-session, old lines with special meanings (!@?) were being
4070 4084 logged without the prepended comment, which is necessary since
4071 4085 they are not truly valid python syntax. This should make session
4072 4086 restores produce less errors.
4073 4087
4074 4088 * The namespace cleanup forced me to make a FlexCompleter class
4075 4089 which is nothing but a ripoff of rlcompleter, but with selectable
4076 4090 namespace (rlcompleter only works in __main__.__dict__). I'll try
4077 4091 to submit a note to the authors to see if this change can be
4078 4092 incorporated in future rlcompleter releases (Dec.6: done)
4079 4093
4080 4094 * More fixes to namespace handling. It was a mess! Now all
4081 4095 explicit references to __main__.__dict__ are gone (except when
4082 4096 really needed) and everything is handled through the namespace
4083 4097 dicts in the IPython instance. We seem to be getting somewhere
4084 4098 with this, finally...
4085 4099
4086 4100 * Small documentation updates.
4087 4101
4088 4102 * Created the Extensions directory under IPython (with an
4089 4103 __init__.py). Put the PhysicalQ stuff there. This directory should
4090 4104 be used for all special-purpose extensions.
4091 4105
4092 4106 * File renaming:
4093 4107 ipythonlib --> ipmaker
4094 4108 ipplib --> iplib
4095 4109 This makes a bit more sense in terms of what these files actually do.
4096 4110
4097 4111 * Moved all the classes and functions in ipythonlib to ipplib, so
4098 4112 now ipythonlib only has make_IPython(). This will ease up its
4099 4113 splitting in smaller functional chunks later.
4100 4114
4101 4115 * Cleaned up (done, I think) output of @whos. Better column
4102 4116 formatting, and now shows str(var) for as much as it can, which is
4103 4117 typically what one gets with a 'print var'.
4104 4118
4105 4119 2001-12-04 Fernando Perez <fperez@colorado.edu>
4106 4120
4107 4121 * Fixed namespace problems. Now builtin/IPyhton/user names get
4108 4122 properly reported in their namespace. Internal namespace handling
4109 4123 is finally getting decent (not perfect yet, but much better than
4110 4124 the ad-hoc mess we had).
4111 4125
4112 4126 * Removed -exit option. If people just want to run a python
4113 4127 script, that's what the normal interpreter is for. Less
4114 4128 unnecessary options, less chances for bugs.
4115 4129
4116 4130 * Added a crash handler which generates a complete post-mortem if
4117 4131 IPython crashes. This will help a lot in tracking bugs down the
4118 4132 road.
4119 4133
4120 4134 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4121 4135 which were boud to functions being reassigned would bypass the
4122 4136 logger, breaking the sync of _il with the prompt counter. This
4123 4137 would then crash IPython later when a new line was logged.
4124 4138
4125 4139 2001-12-02 Fernando Perez <fperez@colorado.edu>
4126 4140
4127 4141 * Made IPython a package. This means people don't have to clutter
4128 4142 their sys.path with yet another directory. Changed the INSTALL
4129 4143 file accordingly.
4130 4144
4131 4145 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4132 4146 sorts its output (so @who shows it sorted) and @whos formats the
4133 4147 table according to the width of the first column. Nicer, easier to
4134 4148 read. Todo: write a generic table_format() which takes a list of
4135 4149 lists and prints it nicely formatted, with optional row/column
4136 4150 separators and proper padding and justification.
4137 4151
4138 4152 * Released 0.1.20
4139 4153
4140 4154 * Fixed bug in @log which would reverse the inputcache list (a
4141 4155 copy operation was missing).
4142 4156
4143 4157 * Code cleanup. @config was changed to use page(). Better, since
4144 4158 its output is always quite long.
4145 4159
4146 4160 * Itpl is back as a dependency. I was having too many problems
4147 4161 getting the parametric aliases to work reliably, and it's just
4148 4162 easier to code weird string operations with it than playing %()s
4149 4163 games. It's only ~6k, so I don't think it's too big a deal.
4150 4164
4151 4165 * Found (and fixed) a very nasty bug with history. !lines weren't
4152 4166 getting cached, and the out of sync caches would crash
4153 4167 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4154 4168 division of labor a bit better. Bug fixed, cleaner structure.
4155 4169
4156 4170 2001-12-01 Fernando Perez <fperez@colorado.edu>
4157 4171
4158 4172 * Released 0.1.19
4159 4173
4160 4174 * Added option -n to @hist to prevent line number printing. Much
4161 4175 easier to copy/paste code this way.
4162 4176
4163 4177 * Created global _il to hold the input list. Allows easy
4164 4178 re-execution of blocks of code by slicing it (inspired by Janko's
4165 4179 comment on 'macros').
4166 4180
4167 4181 * Small fixes and doc updates.
4168 4182
4169 4183 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4170 4184 much too fragile with automagic. Handles properly multi-line
4171 4185 statements and takes parameters.
4172 4186
4173 4187 2001-11-30 Fernando Perez <fperez@colorado.edu>
4174 4188
4175 4189 * Version 0.1.18 released.
4176 4190
4177 4191 * Fixed nasty namespace bug in initial module imports.
4178 4192
4179 4193 * Added copyright/license notes to all code files (except
4180 4194 DPyGetOpt). For the time being, LGPL. That could change.
4181 4195
4182 4196 * Rewrote a much nicer README, updated INSTALL, cleaned up
4183 4197 ipythonrc-* samples.
4184 4198
4185 4199 * Overall code/documentation cleanup. Basically ready for
4186 4200 release. Only remaining thing: licence decision (LGPL?).
4187 4201
4188 4202 * Converted load_config to a class, ConfigLoader. Now recursion
4189 4203 control is better organized. Doesn't include the same file twice.
4190 4204
4191 4205 2001-11-29 Fernando Perez <fperez@colorado.edu>
4192 4206
4193 4207 * Got input history working. Changed output history variables from
4194 4208 _p to _o so that _i is for input and _o for output. Just cleaner
4195 4209 convention.
4196 4210
4197 4211 * Implemented parametric aliases. This pretty much allows the
4198 4212 alias system to offer full-blown shell convenience, I think.
4199 4213
4200 4214 * Version 0.1.17 released, 0.1.18 opened.
4201 4215
4202 4216 * dot_ipython/ipythonrc (alias): added documentation.
4203 4217 (xcolor): Fixed small bug (xcolors -> xcolor)
4204 4218
4205 4219 * Changed the alias system. Now alias is a magic command to define
4206 4220 aliases just like the shell. Rationale: the builtin magics should
4207 4221 be there for things deeply connected to IPython's
4208 4222 architecture. And this is a much lighter system for what I think
4209 4223 is the really important feature: allowing users to define quickly
4210 4224 magics that will do shell things for them, so they can customize
4211 4225 IPython easily to match their work habits. If someone is really
4212 4226 desperate to have another name for a builtin alias, they can
4213 4227 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4214 4228 works.
4215 4229
4216 4230 2001-11-28 Fernando Perez <fperez@colorado.edu>
4217 4231
4218 4232 * Changed @file so that it opens the source file at the proper
4219 4233 line. Since it uses less, if your EDITOR environment is
4220 4234 configured, typing v will immediately open your editor of choice
4221 4235 right at the line where the object is defined. Not as quick as
4222 4236 having a direct @edit command, but for all intents and purposes it
4223 4237 works. And I don't have to worry about writing @edit to deal with
4224 4238 all the editors, less does that.
4225 4239
4226 4240 * Version 0.1.16 released, 0.1.17 opened.
4227 4241
4228 4242 * Fixed some nasty bugs in the page/page_dumb combo that could
4229 4243 crash IPython.
4230 4244
4231 4245 2001-11-27 Fernando Perez <fperez@colorado.edu>
4232 4246
4233 4247 * Version 0.1.15 released, 0.1.16 opened.
4234 4248
4235 4249 * Finally got ? and ?? to work for undefined things: now it's
4236 4250 possible to type {}.get? and get information about the get method
4237 4251 of dicts, or os.path? even if only os is defined (so technically
4238 4252 os.path isn't). Works at any level. For example, after import os,
4239 4253 os?, os.path?, os.path.abspath? all work. This is great, took some
4240 4254 work in _ofind.
4241 4255
4242 4256 * Fixed more bugs with logging. The sanest way to do it was to add
4243 4257 to @log a 'mode' parameter. Killed two in one shot (this mode
4244 4258 option was a request of Janko's). I think it's finally clean
4245 4259 (famous last words).
4246 4260
4247 4261 * Added a page_dumb() pager which does a decent job of paging on
4248 4262 screen, if better things (like less) aren't available. One less
4249 4263 unix dependency (someday maybe somebody will port this to
4250 4264 windows).
4251 4265
4252 4266 * Fixed problem in magic_log: would lock of logging out if log
4253 4267 creation failed (because it would still think it had succeeded).
4254 4268
4255 4269 * Improved the page() function using curses to auto-detect screen
4256 4270 size. Now it can make a much better decision on whether to print
4257 4271 or page a string. Option screen_length was modified: a value 0
4258 4272 means auto-detect, and that's the default now.
4259 4273
4260 4274 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4261 4275 go out. I'll test it for a few days, then talk to Janko about
4262 4276 licences and announce it.
4263 4277
4264 4278 * Fixed the length of the auto-generated ---> prompt which appears
4265 4279 for auto-parens and auto-quotes. Getting this right isn't trivial,
4266 4280 with all the color escapes, different prompt types and optional
4267 4281 separators. But it seems to be working in all the combinations.
4268 4282
4269 4283 2001-11-26 Fernando Perez <fperez@colorado.edu>
4270 4284
4271 4285 * Wrote a regexp filter to get option types from the option names
4272 4286 string. This eliminates the need to manually keep two duplicate
4273 4287 lists.
4274 4288
4275 4289 * Removed the unneeded check_option_names. Now options are handled
4276 4290 in a much saner manner and it's easy to visually check that things
4277 4291 are ok.
4278 4292
4279 4293 * Updated version numbers on all files I modified to carry a
4280 4294 notice so Janko and Nathan have clear version markers.
4281 4295
4282 4296 * Updated docstring for ultraTB with my changes. I should send
4283 4297 this to Nathan.
4284 4298
4285 4299 * Lots of small fixes. Ran everything through pychecker again.
4286 4300
4287 4301 * Made loading of deep_reload an cmd line option. If it's not too
4288 4302 kosher, now people can just disable it. With -nodeep_reload it's
4289 4303 still available as dreload(), it just won't overwrite reload().
4290 4304
4291 4305 * Moved many options to the no| form (-opt and -noopt
4292 4306 accepted). Cleaner.
4293 4307
4294 4308 * Changed magic_log so that if called with no parameters, it uses
4295 4309 'rotate' mode. That way auto-generated logs aren't automatically
4296 4310 over-written. For normal logs, now a backup is made if it exists
4297 4311 (only 1 level of backups). A new 'backup' mode was added to the
4298 4312 Logger class to support this. This was a request by Janko.
4299 4313
4300 4314 * Added @logoff/@logon to stop/restart an active log.
4301 4315
4302 4316 * Fixed a lot of bugs in log saving/replay. It was pretty
4303 4317 broken. Now special lines (!@,/) appear properly in the command
4304 4318 history after a log replay.
4305 4319
4306 4320 * Tried and failed to implement full session saving via pickle. My
4307 4321 idea was to pickle __main__.__dict__, but modules can't be
4308 4322 pickled. This would be a better alternative to replaying logs, but
4309 4323 seems quite tricky to get to work. Changed -session to be called
4310 4324 -logplay, which more accurately reflects what it does. And if we
4311 4325 ever get real session saving working, -session is now available.
4312 4326
4313 4327 * Implemented color schemes for prompts also. As for tracebacks,
4314 4328 currently only NoColor and Linux are supported. But now the
4315 4329 infrastructure is in place, based on a generic ColorScheme
4316 4330 class. So writing and activating new schemes both for the prompts
4317 4331 and the tracebacks should be straightforward.
4318 4332
4319 4333 * Version 0.1.13 released, 0.1.14 opened.
4320 4334
4321 4335 * Changed handling of options for output cache. Now counter is
4322 4336 hardwired starting at 1 and one specifies the maximum number of
4323 4337 entries *in the outcache* (not the max prompt counter). This is
4324 4338 much better, since many statements won't increase the cache
4325 4339 count. It also eliminated some confusing options, now there's only
4326 4340 one: cache_size.
4327 4341
4328 4342 * Added 'alias' magic function and magic_alias option in the
4329 4343 ipythonrc file. Now the user can easily define whatever names he
4330 4344 wants for the magic functions without having to play weird
4331 4345 namespace games. This gives IPython a real shell-like feel.
4332 4346
4333 4347 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4334 4348 @ or not).
4335 4349
4336 4350 This was one of the last remaining 'visible' bugs (that I know
4337 4351 of). I think if I can clean up the session loading so it works
4338 4352 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4339 4353 about licensing).
4340 4354
4341 4355 2001-11-25 Fernando Perez <fperez@colorado.edu>
4342 4356
4343 4357 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4344 4358 there's a cleaner distinction between what ? and ?? show.
4345 4359
4346 4360 * Added screen_length option. Now the user can define his own
4347 4361 screen size for page() operations.
4348 4362
4349 4363 * Implemented magic shell-like functions with automatic code
4350 4364 generation. Now adding another function is just a matter of adding
4351 4365 an entry to a dict, and the function is dynamically generated at
4352 4366 run-time. Python has some really cool features!
4353 4367
4354 4368 * Renamed many options to cleanup conventions a little. Now all
4355 4369 are lowercase, and only underscores where needed. Also in the code
4356 4370 option name tables are clearer.
4357 4371
4358 4372 * Changed prompts a little. Now input is 'In [n]:' instead of
4359 4373 'In[n]:='. This allows it the numbers to be aligned with the
4360 4374 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4361 4375 Python (it was a Mathematica thing). The '...' continuation prompt
4362 4376 was also changed a little to align better.
4363 4377
4364 4378 * Fixed bug when flushing output cache. Not all _p<n> variables
4365 4379 exist, so their deletion needs to be wrapped in a try:
4366 4380
4367 4381 * Figured out how to properly use inspect.formatargspec() (it
4368 4382 requires the args preceded by *). So I removed all the code from
4369 4383 _get_pdef in Magic, which was just replicating that.
4370 4384
4371 4385 * Added test to prefilter to allow redefining magic function names
4372 4386 as variables. This is ok, since the @ form is always available,
4373 4387 but whe should allow the user to define a variable called 'ls' if
4374 4388 he needs it.
4375 4389
4376 4390 * Moved the ToDo information from README into a separate ToDo.
4377 4391
4378 4392 * General code cleanup and small bugfixes. I think it's close to a
4379 4393 state where it can be released, obviously with a big 'beta'
4380 4394 warning on it.
4381 4395
4382 4396 * Got the magic function split to work. Now all magics are defined
4383 4397 in a separate class. It just organizes things a bit, and now
4384 4398 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4385 4399 was too long).
4386 4400
4387 4401 * Changed @clear to @reset to avoid potential confusions with
4388 4402 the shell command clear. Also renamed @cl to @clear, which does
4389 4403 exactly what people expect it to from their shell experience.
4390 4404
4391 4405 Added a check to the @reset command (since it's so
4392 4406 destructive, it's probably a good idea to ask for confirmation).
4393 4407 But now reset only works for full namespace resetting. Since the
4394 4408 del keyword is already there for deleting a few specific
4395 4409 variables, I don't see the point of having a redundant magic
4396 4410 function for the same task.
4397 4411
4398 4412 2001-11-24 Fernando Perez <fperez@colorado.edu>
4399 4413
4400 4414 * Updated the builtin docs (esp. the ? ones).
4401 4415
4402 4416 * Ran all the code through pychecker. Not terribly impressed with
4403 4417 it: lots of spurious warnings and didn't really find anything of
4404 4418 substance (just a few modules being imported and not used).
4405 4419
4406 4420 * Implemented the new ultraTB functionality into IPython. New
4407 4421 option: xcolors. This chooses color scheme. xmode now only selects
4408 4422 between Plain and Verbose. Better orthogonality.
4409 4423
4410 4424 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4411 4425 mode and color scheme for the exception handlers. Now it's
4412 4426 possible to have the verbose traceback with no coloring.
4413 4427
4414 4428 2001-11-23 Fernando Perez <fperez@colorado.edu>
4415 4429
4416 4430 * Version 0.1.12 released, 0.1.13 opened.
4417 4431
4418 4432 * Removed option to set auto-quote and auto-paren escapes by
4419 4433 user. The chances of breaking valid syntax are just too high. If
4420 4434 someone *really* wants, they can always dig into the code.
4421 4435
4422 4436 * Made prompt separators configurable.
4423 4437
4424 4438 2001-11-22 Fernando Perez <fperez@colorado.edu>
4425 4439
4426 4440 * Small bugfixes in many places.
4427 4441
4428 4442 * Removed the MyCompleter class from ipplib. It seemed redundant
4429 4443 with the C-p,C-n history search functionality. Less code to
4430 4444 maintain.
4431 4445
4432 4446 * Moved all the original ipython.py code into ipythonlib.py. Right
4433 4447 now it's just one big dump into a function called make_IPython, so
4434 4448 no real modularity has been gained. But at least it makes the
4435 4449 wrapper script tiny, and since ipythonlib is a module, it gets
4436 4450 compiled and startup is much faster.
4437 4451
4438 4452 This is a reasobably 'deep' change, so we should test it for a
4439 4453 while without messing too much more with the code.
4440 4454
4441 4455 2001-11-21 Fernando Perez <fperez@colorado.edu>
4442 4456
4443 4457 * Version 0.1.11 released, 0.1.12 opened for further work.
4444 4458
4445 4459 * Removed dependency on Itpl. It was only needed in one place. It
4446 4460 would be nice if this became part of python, though. It makes life
4447 4461 *a lot* easier in some cases.
4448 4462
4449 4463 * Simplified the prefilter code a bit. Now all handlers are
4450 4464 expected to explicitly return a value (at least a blank string).
4451 4465
4452 4466 * Heavy edits in ipplib. Removed the help system altogether. Now
4453 4467 obj?/?? is used for inspecting objects, a magic @doc prints
4454 4468 docstrings, and full-blown Python help is accessed via the 'help'
4455 4469 keyword. This cleans up a lot of code (less to maintain) and does
4456 4470 the job. Since 'help' is now a standard Python component, might as
4457 4471 well use it and remove duplicate functionality.
4458 4472
4459 4473 Also removed the option to use ipplib as a standalone program. By
4460 4474 now it's too dependent on other parts of IPython to function alone.
4461 4475
4462 4476 * Fixed bug in genutils.pager. It would crash if the pager was
4463 4477 exited immediately after opening (broken pipe).
4464 4478
4465 4479 * Trimmed down the VerboseTB reporting a little. The header is
4466 4480 much shorter now and the repeated exception arguments at the end
4467 4481 have been removed. For interactive use the old header seemed a bit
4468 4482 excessive.
4469 4483
4470 4484 * Fixed small bug in output of @whos for variables with multi-word
4471 4485 types (only first word was displayed).
4472 4486
4473 4487 2001-11-17 Fernando Perez <fperez@colorado.edu>
4474 4488
4475 4489 * Version 0.1.10 released, 0.1.11 opened for further work.
4476 4490
4477 4491 * Modified dirs and friends. dirs now *returns* the stack (not
4478 4492 prints), so one can manipulate it as a variable. Convenient to
4479 4493 travel along many directories.
4480 4494
4481 4495 * Fixed bug in magic_pdef: would only work with functions with
4482 4496 arguments with default values.
4483 4497
4484 4498 2001-11-14 Fernando Perez <fperez@colorado.edu>
4485 4499
4486 4500 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4487 4501 example with IPython. Various other minor fixes and cleanups.
4488 4502
4489 4503 * Version 0.1.9 released, 0.1.10 opened for further work.
4490 4504
4491 4505 * Added sys.path to the list of directories searched in the
4492 4506 execfile= option. It used to be the current directory and the
4493 4507 user's IPYTHONDIR only.
4494 4508
4495 4509 2001-11-13 Fernando Perez <fperez@colorado.edu>
4496 4510
4497 4511 * Reinstated the raw_input/prefilter separation that Janko had
4498 4512 initially. This gives a more convenient setup for extending the
4499 4513 pre-processor from the outside: raw_input always gets a string,
4500 4514 and prefilter has to process it. We can then redefine prefilter
4501 4515 from the outside and implement extensions for special
4502 4516 purposes.
4503 4517
4504 4518 Today I got one for inputting PhysicalQuantity objects
4505 4519 (from Scientific) without needing any function calls at
4506 4520 all. Extremely convenient, and it's all done as a user-level
4507 4521 extension (no IPython code was touched). Now instead of:
4508 4522 a = PhysicalQuantity(4.2,'m/s**2')
4509 4523 one can simply say
4510 4524 a = 4.2 m/s**2
4511 4525 or even
4512 4526 a = 4.2 m/s^2
4513 4527
4514 4528 I use this, but it's also a proof of concept: IPython really is
4515 4529 fully user-extensible, even at the level of the parsing of the
4516 4530 command line. It's not trivial, but it's perfectly doable.
4517 4531
4518 4532 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4519 4533 the problem of modules being loaded in the inverse order in which
4520 4534 they were defined in
4521 4535
4522 4536 * Version 0.1.8 released, 0.1.9 opened for further work.
4523 4537
4524 4538 * Added magics pdef, source and file. They respectively show the
4525 4539 definition line ('prototype' in C), source code and full python
4526 4540 file for any callable object. The object inspector oinfo uses
4527 4541 these to show the same information.
4528 4542
4529 4543 * Version 0.1.7 released, 0.1.8 opened for further work.
4530 4544
4531 4545 * Separated all the magic functions into a class called Magic. The
4532 4546 InteractiveShell class was becoming too big for Xemacs to handle
4533 4547 (de-indenting a line would lock it up for 10 seconds while it
4534 4548 backtracked on the whole class!)
4535 4549
4536 4550 FIXME: didn't work. It can be done, but right now namespaces are
4537 4551 all messed up. Do it later (reverted it for now, so at least
4538 4552 everything works as before).
4539 4553
4540 4554 * Got the object introspection system (magic_oinfo) working! I
4541 4555 think this is pretty much ready for release to Janko, so he can
4542 4556 test it for a while and then announce it. Pretty much 100% of what
4543 4557 I wanted for the 'phase 1' release is ready. Happy, tired.
4544 4558
4545 4559 2001-11-12 Fernando Perez <fperez@colorado.edu>
4546 4560
4547 4561 * Version 0.1.6 released, 0.1.7 opened for further work.
4548 4562
4549 4563 * Fixed bug in printing: it used to test for truth before
4550 4564 printing, so 0 wouldn't print. Now checks for None.
4551 4565
4552 4566 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4553 4567 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4554 4568 reaches by hand into the outputcache. Think of a better way to do
4555 4569 this later.
4556 4570
4557 4571 * Various small fixes thanks to Nathan's comments.
4558 4572
4559 4573 * Changed magic_pprint to magic_Pprint. This way it doesn't
4560 4574 collide with pprint() and the name is consistent with the command
4561 4575 line option.
4562 4576
4563 4577 * Changed prompt counter behavior to be fully like
4564 4578 Mathematica's. That is, even input that doesn't return a result
4565 4579 raises the prompt counter. The old behavior was kind of confusing
4566 4580 (getting the same prompt number several times if the operation
4567 4581 didn't return a result).
4568 4582
4569 4583 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4570 4584
4571 4585 * Fixed -Classic mode (wasn't working anymore).
4572 4586
4573 4587 * Added colored prompts using Nathan's new code. Colors are
4574 4588 currently hardwired, they can be user-configurable. For
4575 4589 developers, they can be chosen in file ipythonlib.py, at the
4576 4590 beginning of the CachedOutput class def.
4577 4591
4578 4592 2001-11-11 Fernando Perez <fperez@colorado.edu>
4579 4593
4580 4594 * Version 0.1.5 released, 0.1.6 opened for further work.
4581 4595
4582 4596 * Changed magic_env to *return* the environment as a dict (not to
4583 4597 print it). This way it prints, but it can also be processed.
4584 4598
4585 4599 * Added Verbose exception reporting to interactive
4586 4600 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4587 4601 traceback. Had to make some changes to the ultraTB file. This is
4588 4602 probably the last 'big' thing in my mental todo list. This ties
4589 4603 in with the next entry:
4590 4604
4591 4605 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4592 4606 has to specify is Plain, Color or Verbose for all exception
4593 4607 handling.
4594 4608
4595 4609 * Removed ShellServices option. All this can really be done via
4596 4610 the magic system. It's easier to extend, cleaner and has automatic
4597 4611 namespace protection and documentation.
4598 4612
4599 4613 2001-11-09 Fernando Perez <fperez@colorado.edu>
4600 4614
4601 4615 * Fixed bug in output cache flushing (missing parameter to
4602 4616 __init__). Other small bugs fixed (found using pychecker).
4603 4617
4604 4618 * Version 0.1.4 opened for bugfixing.
4605 4619
4606 4620 2001-11-07 Fernando Perez <fperez@colorado.edu>
4607 4621
4608 4622 * Version 0.1.3 released, mainly because of the raw_input bug.
4609 4623
4610 4624 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4611 4625 and when testing for whether things were callable, a call could
4612 4626 actually be made to certain functions. They would get called again
4613 4627 once 'really' executed, with a resulting double call. A disaster
4614 4628 in many cases (list.reverse() would never work!).
4615 4629
4616 4630 * Removed prefilter() function, moved its code to raw_input (which
4617 4631 after all was just a near-empty caller for prefilter). This saves
4618 4632 a function call on every prompt, and simplifies the class a tiny bit.
4619 4633
4620 4634 * Fix _ip to __ip name in magic example file.
4621 4635
4622 4636 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4623 4637 work with non-gnu versions of tar.
4624 4638
4625 4639 2001-11-06 Fernando Perez <fperez@colorado.edu>
4626 4640
4627 4641 * Version 0.1.2. Just to keep track of the recent changes.
4628 4642
4629 4643 * Fixed nasty bug in output prompt routine. It used to check 'if
4630 4644 arg != None...'. Problem is, this fails if arg implements a
4631 4645 special comparison (__cmp__) which disallows comparing to
4632 4646 None. Found it when trying to use the PhysicalQuantity module from
4633 4647 ScientificPython.
4634 4648
4635 4649 2001-11-05 Fernando Perez <fperez@colorado.edu>
4636 4650
4637 4651 * Also added dirs. Now the pushd/popd/dirs family functions
4638 4652 basically like the shell, with the added convenience of going home
4639 4653 when called with no args.
4640 4654
4641 4655 * pushd/popd slightly modified to mimic shell behavior more
4642 4656 closely.
4643 4657
4644 4658 * Added env,pushd,popd from ShellServices as magic functions. I
4645 4659 think the cleanest will be to port all desired functions from
4646 4660 ShellServices as magics and remove ShellServices altogether. This
4647 4661 will provide a single, clean way of adding functionality
4648 4662 (shell-type or otherwise) to IP.
4649 4663
4650 4664 2001-11-04 Fernando Perez <fperez@colorado.edu>
4651 4665
4652 4666 * Added .ipython/ directory to sys.path. This way users can keep
4653 4667 customizations there and access them via import.
4654 4668
4655 4669 2001-11-03 Fernando Perez <fperez@colorado.edu>
4656 4670
4657 4671 * Opened version 0.1.1 for new changes.
4658 4672
4659 4673 * Changed version number to 0.1.0: first 'public' release, sent to
4660 4674 Nathan and Janko.
4661 4675
4662 4676 * Lots of small fixes and tweaks.
4663 4677
4664 4678 * Minor changes to whos format. Now strings are shown, snipped if
4665 4679 too long.
4666 4680
4667 4681 * Changed ShellServices to work on __main__ so they show up in @who
4668 4682
4669 4683 * Help also works with ? at the end of a line:
4670 4684 ?sin and sin?
4671 4685 both produce the same effect. This is nice, as often I use the
4672 4686 tab-complete to find the name of a method, but I used to then have
4673 4687 to go to the beginning of the line to put a ? if I wanted more
4674 4688 info. Now I can just add the ? and hit return. Convenient.
4675 4689
4676 4690 2001-11-02 Fernando Perez <fperez@colorado.edu>
4677 4691
4678 4692 * Python version check (>=2.1) added.
4679 4693
4680 4694 * Added LazyPython documentation. At this point the docs are quite
4681 4695 a mess. A cleanup is in order.
4682 4696
4683 4697 * Auto-installer created. For some bizarre reason, the zipfiles
4684 4698 module isn't working on my system. So I made a tar version
4685 4699 (hopefully the command line options in various systems won't kill
4686 4700 me).
4687 4701
4688 4702 * Fixes to Struct in genutils. Now all dictionary-like methods are
4689 4703 protected (reasonably).
4690 4704
4691 4705 * Added pager function to genutils and changed ? to print usage
4692 4706 note through it (it was too long).
4693 4707
4694 4708 * Added the LazyPython functionality. Works great! I changed the
4695 4709 auto-quote escape to ';', it's on home row and next to '. But
4696 4710 both auto-quote and auto-paren (still /) escapes are command-line
4697 4711 parameters.
4698 4712
4699 4713
4700 4714 2001-11-01 Fernando Perez <fperez@colorado.edu>
4701 4715
4702 4716 * Version changed to 0.0.7. Fairly large change: configuration now
4703 4717 is all stored in a directory, by default .ipython. There, all
4704 4718 config files have normal looking names (not .names)
4705 4719
4706 4720 * Version 0.0.6 Released first to Lucas and Archie as a test
4707 4721 run. Since it's the first 'semi-public' release, change version to
4708 4722 > 0.0.6 for any changes now.
4709 4723
4710 4724 * Stuff I had put in the ipplib.py changelog:
4711 4725
4712 4726 Changes to InteractiveShell:
4713 4727
4714 4728 - Made the usage message a parameter.
4715 4729
4716 4730 - Require the name of the shell variable to be given. It's a bit
4717 4731 of a hack, but allows the name 'shell' not to be hardwire in the
4718 4732 magic (@) handler, which is problematic b/c it requires
4719 4733 polluting the global namespace with 'shell'. This in turn is
4720 4734 fragile: if a user redefines a variable called shell, things
4721 4735 break.
4722 4736
4723 4737 - magic @: all functions available through @ need to be defined
4724 4738 as magic_<name>, even though they can be called simply as
4725 4739 @<name>. This allows the special command @magic to gather
4726 4740 information automatically about all existing magic functions,
4727 4741 even if they are run-time user extensions, by parsing the shell
4728 4742 instance __dict__ looking for special magic_ names.
4729 4743
4730 4744 - mainloop: added *two* local namespace parameters. This allows
4731 4745 the class to differentiate between parameters which were there
4732 4746 before and after command line initialization was processed. This
4733 4747 way, later @who can show things loaded at startup by the
4734 4748 user. This trick was necessary to make session saving/reloading
4735 4749 really work: ideally after saving/exiting/reloading a session,
4736 4750 *everythin* should look the same, including the output of @who. I
4737 4751 was only able to make this work with this double namespace
4738 4752 trick.
4739 4753
4740 4754 - added a header to the logfile which allows (almost) full
4741 4755 session restoring.
4742 4756
4743 4757 - prepend lines beginning with @ or !, with a and log
4744 4758 them. Why? !lines: may be useful to know what you did @lines:
4745 4759 they may affect session state. So when restoring a session, at
4746 4760 least inform the user of their presence. I couldn't quite get
4747 4761 them to properly re-execute, but at least the user is warned.
4748 4762
4749 4763 * Started ChangeLog.
@@ -1,390 +1,395 b''
1 1 .\" Hey, EMACS: -*- nroff -*-
2 2 .\" First parameter, NAME, should be all caps
3 3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
4 4 .\" other parameters are allowed: see man(7), man(1)
5 5 .TH IPYTHON 1 "November 30, 2004"
6 6 .\" Please adjust this date whenever revising the manpage.
7 7 .\"
8 8 .\" Some roff macros, for reference:
9 9 .\" .nh disable hyphenation
10 10 .\" .hy enable hyphenation
11 11 .\" .ad l left justify
12 12 .\" .ad b justify to both left and right margins
13 13 .\" .nf disable filling
14 14 .\" .fi enable filling
15 15 .\" .br insert line break
16 16 .\" .sp <n> insert n+1 empty lines
17 17 .\" for manpage-specific macros, see man(7) and groff_man(7)
18 18 .\" .SH section heading
19 19 .\" .SS secondary section heading
20 20 .\"
21 21 .\"
22 22 .\" To preview this page as plain text: nroff -man ipython.1
23 23 .\"
24 24 .SH NAME
25 25 ipython \- An Enhanced Interactive Python
26 26 .SH SYNOPSIS
27 27 .B ipython
28 28 .RI [ options ] " files" ...
29 29 .SH DESCRIPTION
30 30 An interactive Python shell with automatic history (input and output),
31 31 dynamic object introspection, easier configuration, command
32 32 completion, access to the system shell, integration with numerical and
33 33 scientific computing tools, and more.
34 34 .SH SPECIAL THREADING OPTIONS
35 35 The following special options are ONLY valid at the beginning of the command
36 36 line, and not later. This is because they control the initialization of
37 37 ipython itself, before the normal option-handling mechanism is active.
38 38 .TP
39 39 .B \-gthread, \-qthread, \-wthread, \-pylab
40 40 Only ONE of these can be given, and it can only be given as the first option
41 41 passed to IPython (it will have no effect in any other position). They
42 42 provide threading support for the GTK, QT and WXWidgets toolkits, and for the
43 43 matplotlib library.
44 44 .br
45 45 .sp 1
46 46 With any of the first three options, IPython starts running a separate thread
47 47 for the graphical toolkit's operation, so that you can open and control
48 48 graphical elements from within an IPython command line, without blocking. All
49 49 three provide essentially the same functionality, respectively for GTK, QT and
50 50 WXWidgets (via their Python interfaces).
51 51 .br
52 52 .sp 1
53 53 If \-pylab is given, IPython loads special support for the matplotlib library
54 54 (http://matplotlib.sourceforge.net), allowing interactive usage of any of its
55 55 backends as defined in the user's .matplotlibrc file. It automatically
56 56 activates GTK, QT or WX threading for IPyhton if the choice of matplotlib
57 57 backend requires it. It also modifies the %run command to correctly execute
58 58 (without blocking) any matplotlib-based script which calls show() at the end.
59 59 .TP
60 60 .B \-tk
61 61 The \-g/q/wthread options, and \-pylab (if matplotlib is configured to use
62 62 GTK, QT or WX), will normally block Tk graphical interfaces. This means that
63 63 when GTK, QT or WX threading is active, any attempt to open a Tk GUI will
64 64 result in a dead window, and possibly cause the Python interpreter to crash.
65 65 An extra option, \-tk, is available to address this issue. It can ONLY be
66 66 given as a SECOND option after any of the above (\-gthread, \-qthread,
67 67 \-wthread or \-pylab).
68 68 .br
69 69 .sp 1
70 70 If \-tk is given, IPython will try to coordinate Tk threading with GTK, QT or
71 71 WX. This is however potentially unreliable, and you will have to test on your
72 72 platform and Python configuration to determine whether it works for you.
73 73 Debian users have reported success, apparently due to the fact that Debian
74 74 builds all of Tcl, Tk, Tkinter and Python with pthreads support. Under other
75 75 Linux environments (such as Fedora Core 2), this option has caused random
76 76 crashes and lockups of the Python interpreter. Under other operating systems
77 77 (Mac OSX and Windows), you'll need to try it to find out, since currently no
78 78 user reports are available.
79 79 .br
80 80 .sp 1
81 81 There is unfortunately no way for IPython to determine at runtime whether \-tk
82 82 will work reliably or not, so you will need to do some experiments before
83 83 relying on it for regular work.
84 84 .
85 85 .SS A WARNING ABOUT SIGNALS AND THREADS
86 86 When any of the thread systems (GTK, QT or WX) are active, either directly or
87 87 via \-pylab with a threaded backend, it is impossible to interrupt
88 88 long-running Python code via Ctrl\-C. IPython can not pass the
89 89 KeyboardInterrupt exception (or the underlying SIGINT) across threads, so any
90 90 long-running process started from IPython will run to completion, or will have
91 91 to be killed via an external (OS-based) mechanism.
92 92 .br
93 93 .sp 1
94 94 To the best of my knowledge, this limitation is imposed by the Python
95 95 interpreter itself, and it comes from the difficulty of writing portable
96 96 signal/threaded code. If any user is an expert on this topic and can suggest
97 97 a better solution, I would love to hear about it. In the IPython sources,
98 98 look at the Shell.py module, and in particular at the runcode() method.
99 99 .
100 100 .SH REGULAR OPTIONS
101 101 After the above threading options have been given, regular options can follow
102 102 in any order. All options can be abbreviated to their shortest non-ambiguous
103 103 form and are case-sensitive. One or two dashes can be used. Some options
104 104 have an alternate short form, indicated after a |.
105 105 .br
106 106 .sp 1
107 107 Most options can also be set from your ipythonrc configuration file.
108 108 See the provided examples for assistance. Options given on the
109 109 commandline override the values set in the ipythonrc file.
110 110 .br
111 111 .sp 1
112 112 All options with a [no] prepended can be specified in negated form
113 113 (\-nooption instead of \-option) to turn the feature off.
114 114 .TP
115 115 .B \-h, \-\-help
116 116 Show summary of options.
117 117 .TP
118 .B \-[no]autocall
118 .B \-autocall <val>
119 119 Make IPython automatically call any callable object even if you didn't type
120 explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically.
120 explicit parentheses. For example, 'str 43' becomes
121 'str(43)' automatically. The value can be '0' to disable the
122 feature, '1' for 'smart' autocall, where it is not applied if
123 there are no more arguments on the line, and '2' for 'full'
124 autocall, where all callable objects are automatically called
125 (even if no arguments are present). The default is '1'.
121 126 .TP
122 127 .B \-[no]autoindent
123 128 Turn automatic indentation on/off.
124 129 .TP
125 130 .B \-[no]automagic
126 131 Make magic commands automatic (without needing their first character
127 132 to be %). Type %magic at the IPython prompt for more information.
128 133 .TP
129 134 .B \-[no]autoedit_syntax
130 135 When a syntax error occurs after editing a file, automatically open the file
131 136 to the trouble causing line for convenient fixing.
132 137 .TP
133 138 .B \-[no]banner
134 139 Print the intial information banner (default on).
135 140 .TP
136 141 .B \-c <command>
137 142 Execute the given command string, and set sys.argv to ['c']. This is similar
138 143 to the \-c option in the normal Python interpreter.
139 144 .TP
140 145 .B \-cache_size|cs <n>
141 146 Size of the output cache (maximum number of entries to hold in
142 147 memory). The default is 1000, you can change it permanently in your
143 148 config file. Setting it to 0 completely disables the caching system,
144 149 and the minimum value accepted is 20 (if you provide a value less than
145 150 20, it is reset to 0 and a warning is issued). This limit is defined
146 151 because otherwise you'll spend more time re-flushing a too small cache
147 152 than working.
148 153 .TP
149 154 .B \-classic|cl
150 155 Gives IPython a similar feel to the classic Python prompt.
151 156 .TP
152 157 .B \-colors <scheme>
153 158 Color scheme for prompts and exception reporting. Currently
154 159 implemented: NoColor, Linux, and LightBG.
155 160 .TP
156 161 .B \-[no]color_info
157 162 IPython can display information about objects via a set of functions,
158 163 and optionally can use colors for this, syntax highlighting source
159 164 code and various other elements. However, because this information is
160 165 passed through a pager (like 'less') and many pagers get confused with
161 166 color codes, this option is off by default. You can test it and turn
162 167 it on permanently in your ipythonrc file if it works for you. As a
163 168 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
164 169 that in RedHat 7.2 doesn't.
165 170 .br
166 171 .sp 1
167 172 Test it and turn it on permanently if it works with your system. The
168 173 magic function @color_info allows you to toggle this interactively for
169 174 testing.
170 175 .TP
171 176 .B \-[no]confirm_exit
172 177 Set to confirm when you try to exit IPython with an EOF (Control-D in
173 178 Unix, Control-Z/Enter in Windows). Note that using the magic functions
174 179 @Exit or @Quit you can force a direct exit, bypassing any
175 180 confirmation.
176 181 .TP
177 182 .B \-[no]debug
178 183 Show information about the loading process. Very useful to pin down
179 184 problems with your configuration files or to get details about session
180 185 restores.
181 186 .TP
182 187 .B \-[no]deep_reload
183 188 IPython can use the deep_reload module which reloads changes in
184 189 modules recursively (it replaces the reload() function, so you don't
185 190 need to change anything to use it). deep_reload() forces a full reload
186 191 of modules whose code may have changed, which the default reload()
187 192 function does not.
188 193 .br
189 194 .sp 1
190 195 When deep_reload is off, IPython will use the normal reload(), but
191 196 deep_reload will still be available as dreload(). This feature is off
192 197 by default [which means that you have both normal reload() and
193 198 dreload()].
194 199 .TP
195 200 .B \-editor <name>
196 201 Which editor to use with the @edit command. By default, IPython will
197 202 honor your EDITOR environment variable (if not set, vi is the Unix
198 203 default and notepad the Windows one). Since this editor is invoked on
199 204 the fly by IPython and is meant for editing small code snippets, you
200 205 may want to use a small, lightweight editor here (in case your default
201 206 EDITOR is something like Emacs).
202 207 .TP
203 208 .B \-ipythondir <name>
204 209 The name of your IPython configuration directory IPYTHONDIR. This can
205 210 also be specified through the environment variable IPYTHONDIR.
206 211 .TP
207 212 .B \-log|l
208 213 Generate a log file of all input. The file is named ipython_log.py in your
209 214 current directory (which prevents logs from multiple IPython sessions from
210 215 trampling each other). You can use this to later restore a session by loading
211 216 your logfile as a file to be executed with option -logplay (see below).
212 217 .TP
213 218 .B \-logfile|lf
214 219 Specify the name of your logfile.
215 220 .TP
216 221 .B \-logplay|lp
217 222 Replay a previous log. For restoring a session as close as possible to
218 223 the state you left it in, use this option (don't just run the
219 224 logfile). With \-logplay, IPython will try to reconstruct the previous
220 225 working environment in full, not just execute the commands in the
221 226 logfile.
222 227 .br
223 228 .sh 1
224 229 When a session is restored, logging is automatically turned on again
225 230 with the name of the logfile it was invoked with (it is read from the
226 231 log header). So once you've turned logging on for a session, you can
227 232 quit IPython and reload it as many times as you want and it will
228 233 continue to log its history and restore from the beginning every time.
229 234 .br
230 235 .sp 1
231 236 Caveats: there are limitations in this option. The history variables
232 237 _i*,_* and _dh don't get restored properly. In the future we will try
233 238 to implement full session saving by writing and retrieving a
234 239 'snapshot' of the memory state of IPython. But our first attempts
235 240 failed because of inherent limitations of Python's Pickle module, so
236 241 this may have to wait.
237 242 .TP
238 243 .B \-[no]messages
239 244 Print messages which IPython collects about its startup process
240 245 (default on).
241 246 .TP
242 247 .B \-[no]pdb
243 248 Automatically call the pdb debugger after every uncaught exception. If
244 249 you are used to debugging using pdb, this puts you automatically
245 250 inside of it after any call (either in IPython or in code called by
246 251 it) which triggers an exception which goes uncaught.
247 252 .TP
248 253 .B \-[no]pprint
249 254 IPython can optionally use the pprint (pretty printer) module for
250 255 displaying results. pprint tends to give a nicer display of nested
251 256 data structures. If you like it, you can turn it on permanently in
252 257 your config file (default off).
253 258 .TP
254 259 .B \-profile|p <name>
255 260 Assume that your config file is ipythonrc-<name> (looks in current dir
256 261 first, then in IPYTHONDIR). This is a quick way to keep and load
257 262 multiple config files for different tasks, especially if you use the
258 263 include option of config files. You can keep a basic
259 264 IPYTHONDIR/ipythonrc file and then have other 'profiles' which include
260 265 this one and load extra things for particular tasks. For example:
261 266 .br
262 267 .sp 1
263 268 1) $HOME/.ipython/ipythonrc : load basic things you always want.
264 269 .br
265 270 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-related
266 271 modules.
267 272 .br
268 273 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
269 274 plotting modules.
270 275 .br
271 276 .sp 1
272 277 Since it is possible to create an endless loop by having circular file
273 278 inclusions, IPython will stop if it reaches 15 recursive inclusions.
274 279 .TP
275 280 .B \-prompt_in1|pi1 <string>
276 281 Specify the string used for input prompts. Note that if you are using
277 282 numbered prompts, the number is represented with a '\\#' in the
278 283 string. Don't forget to quote strings with spaces embedded in
279 284 them. Default: 'In [\\#]:'.
280 285 .br
281 286 .sp 1
282 287 Most bash-like escapes can be used to customize IPython's prompts, as well as
283 288 a few additional ones which are IPython-specific. All valid prompt escapes
284 289 are described in detail in the Customization section of the IPython HTML/PDF
285 290 manual.
286 291 .TP
287 292 .B \-prompt_in2|pi2 <string>
288 293 Similar to the previous option, but used for the continuation prompts. The
289 294 special sequence '\\D' is similar to '\\#', but with all digits replaced dots
290 295 (so you can have your continuation prompt aligned with your input
291 296 prompt). Default: ' .\\D.:' (note three spaces at the start for alignment
292 297 with 'In [\\#]').
293 298 .TP
294 299 .B \-prompt_out|po <string>
295 300 String used for output prompts, also uses numbers like prompt_in1.
296 301 Default: 'Out[\\#]:'.
297 302 .TP
298 303 .B \-quick
299 304 Start in bare bones mode (no config file loaded).
300 305 .TP
301 306 .B \-rcfile <name>
302 307 Name of your IPython resource configuration file. normally IPython
303 308 loads ipythonrc (from current directory) or IPYTHONDIR/ipythonrc. If
304 309 the loading of your config file fails, IPython starts with a bare
305 310 bones configuration (no modules loaded at all).
306 311 .TP
307 312 .B \-[no]readline
308 313 Use the readline library, which is needed to support name completion
309 314 and command history, among other things. It is enabled by default, but
310 315 may cause problems for users of X/Emacs in Python comint or shell
311 316 buffers.
312 317 .br
313 318 .sp 1
314 319 Note that emacs 'eterm' buffers (opened with M-x term) support
315 320 IPython's readline and syntax coloring fine, only 'emacs' (M-x shell
316 321 and C-c !) buffers do not.
317 322 .TP
318 323 .B \-screen_length|sl <n>
319 324 Number of lines of your screen. This is used to control printing of
320 325 very long strings. Strings longer than this number of lines will be
321 326 sent through a pager instead of directly printed.
322 327 .br
323 328 .sp 1
324 329 The default value for this is 0, which means IPython will auto-detect
325 330 your screen size every time it needs to print certain potentially long
326 331 strings (this doesn't change the behavior of the 'print' keyword, it's
327 332 only triggered internally). If for some reason this isn't working well
328 333 (it needs curses support), specify it yourself. Otherwise don't change
329 334 the default.
330 335 .TP
331 336 .B \-separate_in|si <string>
332 337 Separator before input prompts. Default '\n'.
333 338 .TP
334 339 .B \-separate_out|so <string>
335 340 Separator before output prompts. Default: 0 (nothing).
336 341 .TP
337 342 .B \-separate_out2|so2 <string>
338 343 Separator after output prompts. Default: 0 (nothing).
339 344 .TP
340 345 .B \-nosep
341 346 Shorthand for '\-separate_in 0 \-separate_out 0 \-separate_out2 0'.
342 347 Simply removes all input/output separators.
343 348 .TP
344 349 .B \-upgrade
345 350 Allows you to upgrade your IPYTHONDIR configuration when you install a
346 351 new version of IPython. Since new versions may include new command
347 352 lines options or example files, this copies updated ipythonrc-type
348 353 files. However, it backs up (with a .old extension) all files which
349 354 it overwrites so that you can merge back any custimizations you might
350 355 have in your personal files.
351 356 .TP
352 357 .B \-Version
353 358 Print version information and exit.
354 359 .TP
355 360 .B \-xmode <modename>
356 361 Mode for exception reporting. The valid modes are Plain, Context, and
357 362 Verbose.
358 363 .br
359 364 .sp 1
360 365 \- Plain: similar to python's normal traceback printing.
361 366 .br
362 367 .sp 1
363 368 \- Context: prints 5 lines of context source code around each line in the
364 369 traceback.
365 370 .br
366 371 .sp 1
367 372 \- Verbose: similar to Context, but additionally prints the variables
368 373 currently visible where the exception happened (shortening their strings if
369 374 too long). This can potentially be very slow, if you happen to have a huge
370 375 data structure whose string representation is complex to compute. Your
371 376 computer may appear to freeze for a while with cpu usage at 100%. If this
372 377 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than
373 378 once).
374 379 .
375 380 .SH EMBEDDING
376 381 It is possible to start an IPython instance inside your own Python
377 382 programs. In the documentation example files there are some
378 383 illustrations on how to do this.
379 384 .br
380 385 .sp 1
381 386 This feature allows you to evalutate dynamically the state of your
382 387 code, operate with your variables, analyze them, etc. Note however
383 388 that any changes you make to values while in the shell do NOT
384 389 propagate back to the running code, so it is safe to modify your
385 390 values because you won't break your code in bizarre ways by doing so.
386 391 .SH AUTHOR
387 392 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
388 393 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
389 394 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
390 395 <jack@xiph.org>, for the Debian project (but may be used by others).
@@ -1,9161 +1,9173 b''
1 1 #LyX 1.3 created this file. For more info see http://www.lyx.org/
2 2 \lyxformat 221
3 3 \textclass article
4 4 \begin_preamble
5 5 %\usepackage{ae,aecompl}
6 6 \usepackage{color}
7 7
8 8 % A few colors to replace the defaults for certain link types
9 9 \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
10 10 \definecolor{darkorange}{rgb}{.71,0.21,0.01}
11 11 \definecolor{darkred}{rgb}{.52,0.08,0.01}
12 12 \definecolor{darkgreen}{rgb}{.12,.54,.11}
13 13
14 14 % Use and configure listings package for nicely formatted code
15 15 \usepackage{listings}
16 16 \lstset{
17 17 language=Python,
18 18 basicstyle=\small\ttfamily,
19 19 commentstyle=\ttfamily\color{blue},
20 20 stringstyle=\ttfamily\color{darkorange},
21 21 showstringspaces=false,
22 22 breaklines=true,
23 23 postbreak = \space\dots
24 24 }
25 25
26 26 \usepackage[%pdftex, % needed for pdflatex
27 27 breaklinks=true, % so long urls are correctly broken across lines
28 28 colorlinks=true,
29 29 urlcolor=blue,
30 30 linkcolor=darkred,
31 31 citecolor=darkgreen,
32 32 ]{hyperref}
33 33
34 34 \usepackage{html}
35 35
36 36 % This helps prevent overly long lines that stretch beyond the margins
37 37 \sloppy
38 38
39 39 % Define a \codelist command which either uses listings for latex, or
40 40 % plain verbatim for html (since latex2html doesn't understand the
41 41 % listings package).
42 42 \usepackage{verbatim}
43 43 \newcommand{\codelist}[1] {
44 44 \latex{\lstinputlisting{#1}}
45 45 \html{\verbatiminput{#1}}
46 46 }
47 47 \end_preamble
48 48 \language english
49 49 \inputencoding latin1
50 50 \fontscheme palatino
51 51 \graphics default
52 52 \paperfontsize 10
53 53 \spacing single
54 54 \papersize Default
55 55 \paperpackage a4
56 56 \use_geometry 1
57 57 \use_amsmath 0
58 58 \use_natbib 0
59 59 \use_numerical_citations 0
60 60 \paperorientation portrait
61 61 \leftmargin 1.1in
62 62 \topmargin 1in
63 63 \rightmargin 1.1in
64 64 \bottommargin 1in
65 65 \secnumdepth 3
66 66 \tocdepth 3
67 67 \paragraph_separation skip
68 68 \defskip medskip
69 69 \quotes_language english
70 70 \quotes_times 2
71 71 \papercolumns 1
72 72 \papersides 1
73 73 \paperpagestyle fancy
74 74
75 75 \layout Title
76 76
77 77 IPython
78 78 \newline
79 79
80 80 \size larger
81 81 An enhanced Interactive Python
82 82 \size large
83 83
84 84 \newline
85 85 User Manual, v.
86 86 __version__
87 87 \layout Author
88 88
89 89 Fernando P�rez
90 90 \layout Standard
91 91
92 92
93 93 \begin_inset ERT
94 94 status Collapsed
95 95
96 96 \layout Standard
97 97
98 98 \backslash
99 99 latex{
100 100 \end_inset
101 101
102 102
103 103 \begin_inset LatexCommand \tableofcontents{}
104 104
105 105 \end_inset
106 106
107 107
108 108 \begin_inset ERT
109 109 status Collapsed
110 110
111 111 \layout Standard
112 112 }
113 113 \end_inset
114 114
115 115
116 116 \layout Standard
117 117
118 118
119 119 \begin_inset ERT
120 120 status Open
121 121
122 122 \layout Standard
123 123
124 124 \backslash
125 125 html{
126 126 \backslash
127 127 bodytext{bgcolor=#ffffff}}
128 128 \end_inset
129 129
130 130
131 131 \layout Section
132 132 \pagebreak_top
133 133 Overview
134 134 \layout Standard
135 135
136 136 One of Python's most useful features is its interactive interpreter.
137 137 This system allows very fast testing of ideas without the overhead of creating
138 138 test files as is typical in most programming languages.
139 139 However, the interpreter supplied with the standard Python distribution
140 140 is somewhat limited for extended interactive use.
141 141 \layout Standard
142 142
143 143 IPython is a free software project (released under the BSD license) which
144 144 tries to:
145 145 \layout Enumerate
146 146
147 147 Provide an interactive shell superior to Python's default.
148 148 IPython has many features for object introspection, system shell access,
149 149 and its own special command system for adding functionality when working
150 150 interactively.
151 151 It tries to be a very efficient environment both for Python code development
152 152 and for exploration of problems using Python objects (in situations like
153 153 data analysis).
154 154 \layout Enumerate
155 155
156 156 Serve as an embeddable, ready to use interpreter for your own programs.
157 157 IPython can be started with a single call from inside another program,
158 158 providing access to the current namespace.
159 159 This can be very useful both for debugging purposes and for situations
160 160 where a blend of batch-processing and interactive exploration are needed.
161 161 \layout Enumerate
162 162
163 163 Offer a flexible framework which can be used as the base environment for
164 164 other systems with Python as the underlying language.
165 165 Specifically scientific environments like Mathematica, IDL and Matlab inspired
166 166 its design, but similar ideas can be useful in many fields.
167 167 \layout Subsection
168 168
169 169 Main features
170 170 \layout Itemize
171 171
172 172 Dynamic object introspection.
173 173 One can access docstrings, function definition prototypes, source code,
174 174 source files and other details of any object accessible to the interpreter
175 175 with a single keystroke (`
176 176 \family typewriter
177 177 ?
178 178 \family default
179 179 ').
180 180 \layout Itemize
181 181
182 182 Completion in the local namespace, by typing TAB at the prompt.
183 183 This works for keywords, methods, variables and files in the current directory.
184 184 This is supported via the readline library, and full access to configuring
185 185 readline's behavior is provided.
186 186 \layout Itemize
187 187
188 188 Numbered input/output prompts with command history (persistent across sessions
189 189 and tied to each profile), full searching in this history and caching of
190 190 all input and output.
191 191 \layout Itemize
192 192
193 193 User-extensible `magic' commands.
194 194 A set of commands prefixed with
195 195 \family typewriter
196 196 %
197 197 \family default
198 198 is available for controlling IPython itself and provides directory control,
199 199 namespace information and many aliases to common system shell commands.
200 200 \layout Itemize
201 201
202 202 Alias facility for defining your own system aliases.
203 203 \layout Itemize
204 204
205 205 Complete system shell access.
206 206 Lines starting with ! are passed directly to the system shell, and using
207 207 !! captures shell output into python variables for further use.
208 208 \layout Itemize
209 209
210 210 All calls to the system (via aliases or via !) have their standard output/error
211 211 automatically stored as strings, and also available as lists.
212 212 \layout Itemize
213 213
214 214 Background execution of Python commands in a separate thread.
215 215 IPython has an internal job manager called
216 216 \family typewriter
217 217 jobs
218 218 \family default
219 219 , and a conveninence backgrounding magic function called
220 220 \family typewriter
221 221 %bg
222 222 \family default
223 223 .
224 224 \layout Itemize
225 225
226 226 The ability to expand python variables when calling the system shell.
227 227 In a shell command, any python variable prefixed with
228 228 \family typewriter
229 229 $
230 230 \family default
231 231 is expanded.
232 232 A double
233 233 \family typewriter
234 234 $$
235 235 \family default
236 236 allows passing a literal
237 237 \family typewriter
238 238 $
239 239 \family default
240 240 to the shell (for access to shell and environment variables like
241 241 \family typewriter
242 242 $PATH
243 243 \family default
244 244 ).
245 245 \layout Itemize
246 246
247 247 Filesystem navigation, via a magic
248 248 \family typewriter
249 249 %cd
250 250 \family default
251 251 command, along with a persistent bookmark system (using
252 252 \family typewriter
253 253 %bookmark
254 254 \family default
255 255 ) for fast access to frequently visited directories.
256 256 \layout Itemize
257 257
258 258 Automatic indentation (optional) of code as you type (through the readline
259 259 library).
260 260 \layout Itemize
261 261
262 262 Macro system for quickly re-executing multiple lines of previous input with
263 263 a single name.
264 264 \layout Itemize
265 265
266 266 Session logging (you can then later use these logs as code in your programs).
267 267 \layout Itemize
268 268
269 269 Session restoring: logs can be replayed to restore a previous session to
270 270 the state where you left it.
271 271 \layout Itemize
272 272
273 273 Verbose and colored exception traceback printouts.
274 274 Easier to parse visually, and in verbose mode they produce a lot of useful
275 275 debugging information (basically a terminal version of the cgitb module).
276 276 \layout Itemize
277 277
278 278 Auto-parentheses: callable objects can be executed without parentheses:
279 279
280 280 \family typewriter
281 281 `sin 3'
282 282 \family default
283 283 is automatically converted to
284 284 \family typewriter
285 285 `sin(3)
286 286 \family default
287 287 '.
288 288 \layout Itemize
289 289
290 290 Auto-quoting: using `
291 291 \family typewriter
292 292 ,
293 293 \family default
294 294 ' or `
295 295 \family typewriter
296 296 ;
297 297 \family default
298 298 ' as the first character forces auto-quoting of the rest of the line:
299 299 \family typewriter
300 300 `,my_function a\SpecialChar ~
301 301 b'
302 302 \family default
303 303 becomes automatically
304 304 \family typewriter
305 305 `my_function("a","b")'
306 306 \family default
307 307 , while
308 308 \family typewriter
309 309 `;my_function a\SpecialChar ~
310 310 b'
311 311 \family default
312 312 becomes
313 313 \family typewriter
314 314 `my_function("a b")'
315 315 \family default
316 316 .
317 317 \layout Itemize
318 318
319 319 Extensible input syntax.
320 320 You can define filters that pre-process user input to simplify input in
321 321 special situations.
322 322 This allows for example pasting multi-line code fragments which start with
323 323
324 324 \family typewriter
325 325 `>>>'
326 326 \family default
327 327 or
328 328 \family typewriter
329 329 `...'
330 330 \family default
331 331 such as those from other python sessions or the standard Python documentation.
332 332 \layout Itemize
333 333
334 334 Flexible configuration system.
335 335 It uses a configuration file which allows permanent setting of all command-line
336 336 options, module loading, code and file execution.
337 337 The system allows recursive file inclusion, so you can have a base file
338 338 with defaults and layers which load other customizations for particular
339 339 projects.
340 340 \layout Itemize
341 341
342 342 Embeddable.
343 343 You can call IPython as a python shell inside your own python programs.
344 344 This can be used both for debugging code or for providing interactive abilities
345 345 to your programs with knowledge about the local namespaces (very useful
346 346 in debugging and data analysis situations).
347 347 \layout Itemize
348 348
349 349 Easy debugger access.
350 350 You can set IPython to call up an enhanced version of the Python debugger
351 351 (
352 352 \family typewriter
353 353 pdb
354 354 \family default
355 355 ) every time there is an uncaught exception.
356 356 This drops you inside the code which triggered the exception with all the
357 357 data live and it is possible to navigate the stack to rapidly isolate the
358 358 source of a bug.
359 359 The
360 360 \family typewriter
361 361 %run
362 362 \family default
363 363 magic command --with the
364 364 \family typewriter
365 365 -d
366 366 \family default
367 367 option-- can run any script under
368 368 \family typewriter
369 369 pdb
370 370 \family default
371 371 's control, automatically setting initial breakpoints for you.
372 372 This version of
373 373 \family typewriter
374 374 pdb
375 375 \family default
376 376 has IPython-specific improvements, including tab-completion and traceback
377 377 coloring support.
378 378 \layout Itemize
379 379
380 380 Profiler support.
381 381 You can run single statements (similar to
382 382 \family typewriter
383 383 profile.run()
384 384 \family default
385 385 ) or complete programs under the profiler's control.
386 386 While this is possible with the standard
387 387 \family typewriter
388 388 profile
389 389 \family default
390 390 module, IPython wraps this functionality with magic commands (see
391 391 \family typewriter
392 392 `%prun'
393 393 \family default
394 394 and
395 395 \family typewriter
396 396 `%run -p
397 397 \family default
398 398 ') convenient for rapid interactive work.
399 399 \layout Subsection
400 400
401 401 Portability and Python requirements
402 402 \layout Standard
403 403
404 404
405 405 \series bold
406 406 Python requirements:
407 407 \series default
408 408 IPython works with Python version 2.2 or newer.
409 409 It has been tested with Python 2.4 and no problems have been reported.
410 410 Support for Python 2.1 hasn't been recently tested, since I don't have access
411 411 to it on any of my systems.
412 412 But I suspect there may be some problems with Python 2.1, because some of
413 413 the newer code may use 2.2 features.
414 414 \layout Standard
415 415
416 416 IPython is developed under
417 417 \series bold
418 418 Linux
419 419 \series default
420 420 , but it should work in any reasonable Unix-type system (tested OK under
421 421 Solaris and the *BSD family, for which a port exists thanks to Dryice Liu).
422 422 \layout Standard
423 423
424 424
425 425 \series bold
426 426 Mac OS X
427 427 \series default
428 428 : it works, apparently without any problems (thanks to Jim Boyle at Lawrence
429 429 Livermore for the information).
430 430 Thanks to Andrea Riciputi, Fink support is available.
431 431 \layout Standard
432 432
433 433
434 434 \series bold
435 435 CygWin
436 436 \series default
437 437 : it works mostly OK, though some users have reported problems with prompt
438 438 coloring.
439 439 No satisfactory solution to this has been found so far, you may want to
440 440 disable colors permanently in the
441 441 \family typewriter
442 442 ipythonrc
443 443 \family default
444 444 configuration file if you experience problems.
445 445 If you have proper color support under cygwin, please post to the IPython
446 446 mailing list so this issue can be resolved for all users.
447 447 \layout Standard
448 448
449 449
450 450 \series bold
451 451 Windows
452 452 \series default
453 453 : it works well under Windows XP/2k, and I suspect NT should behave similarly.
454 454 Section\SpecialChar ~
455 455
456 456 \begin_inset LatexCommand \ref{sub:Under-Windows}
457 457
458 458 \end_inset
459 459
460 460 describes installation details for Windows, including some additional tools
461 461 needed on this platform.
462 462 \layout Standard
463 463
464 464 Windows 9x support is present, and has been reported to work fine (at least
465 465 on WinME).
466 466 \layout Standard
467 467
468 468 Please note, however, that I have very little access to and experience with
469 469 Windows development.
470 470 For this reason, Windows-specific bugs tend to linger far longer than I
471 471 would like, and often I just can't find a satisfactory solution.
472 472 If any Windows user wants to join in with development help, all hands are
473 473 always welcome.
474 474 \layout Subsection
475 475
476 476 Location
477 477 \layout Standard
478 478
479 479 IPython is generously hosted at
480 480 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
481 481
482 482 \end_inset
483 483
484 484 by the SciPy project.
485 485 This site offers downloads, subversion access, mailing lists and a bug
486 486 tracking system.
487 487 I am very grateful to Enthought (
488 488 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
489 489
490 490 \end_inset
491 491
492 492 ) and all of the SciPy team for their contribution.
493 493 \layout Section
494 494
495 495
496 496 \begin_inset LatexCommand \label{sec:install}
497 497
498 498 \end_inset
499 499
500 500 Installation
501 501 \layout Subsection
502 502
503 503 Instant instructions
504 504 \layout Standard
505 505
506 506 If you are of the impatient kind, under Linux/Unix simply untar/unzip the
507 507 download, then install with
508 508 \family typewriter
509 509 `python setup.py install'
510 510 \family default
511 511 .
512 512 Under Windows, double-click on the provided
513 513 \family typewriter
514 514 .exe
515 515 \family default
516 516 binary installer.
517 517 \layout Standard
518 518
519 519 Then, take a look at Sections
520 520 \begin_inset LatexCommand \ref{sec:good_config}
521 521
522 522 \end_inset
523 523
524 524 for configuring things optimally and
525 525 \begin_inset LatexCommand \ref{sec:quick_tips}
526 526
527 527 \end_inset
528 528
529 529 for quick tips on efficient use of IPython.
530 530 You can later refer to the rest of the manual for all the gory details.
531 531 \layout Standard
532 532
533 533 See the notes in sec.
534 534
535 535 \begin_inset LatexCommand \ref{sec:upgrade}
536 536
537 537 \end_inset
538 538
539 539 for upgrading IPython versions.
540 540 \layout Subsection
541 541
542 542 Detailed Unix instructions (Linux, Mac OS X, etc.)
543 543 \layout Standard
544 544
545 545 For RPM based systems, simply install the supplied package in the usual
546 546 manner.
547 547 If you download the tar archive, the process is:
548 548 \layout Enumerate
549 549
550 550 Unzip/untar the
551 551 \family typewriter
552 552 ipython-XXX.tar.gz
553 553 \family default
554 554 file wherever you want (
555 555 \family typewriter
556 556 XXX
557 557 \family default
558 558 is the version number).
559 559 It will make a directory called
560 560 \family typewriter
561 561 ipython-XXX.
562 562
563 563 \family default
564 564 Change into that directory where you will find the files
565 565 \family typewriter
566 566 README
567 567 \family default
568 568 and
569 569 \family typewriter
570 570 setup.py
571 571 \family default
572 572 .
573 573
574 574 \family typewriter
575 575 O
576 576 \family default
577 577 nce you've completed the installation, you can safely remove this directory.
578 578
579 579 \layout Enumerate
580 580
581 581 If you are installing over a previous installation of version 0.2.0 or earlier,
582 582 first remove your
583 583 \family typewriter
584 584 $HOME/.ipython
585 585 \family default
586 586 directory, since the configuration file format has changed somewhat (the
587 587 '=' were removed from all option specifications).
588 588 Or you can call ipython with the
589 589 \family typewriter
590 590 -upgrade
591 591 \family default
592 592 option and it will do this automatically for you.
593 593 \layout Enumerate
594 594
595 595 IPython uses distutils, so you can install it by simply typing at the system
596 596 prompt (don't type the
597 597 \family typewriter
598 598 $
599 599 \family default
600 600 )
601 601 \newline
602 602
603 603 \family typewriter
604 604 $ python setup.py install
605 605 \family default
606 606
607 607 \newline
608 608 Note that this assumes you have root access to your machine.
609 609 If you don't have root access or don't want IPython to go in the default
610 610 python directories, you'll need to use the
611 611 \begin_inset ERT
612 612 status Collapsed
613 613
614 614 \layout Standard
615 615
616 616 \backslash
617 617 verb|--home|
618 618 \end_inset
619 619
620 620 option (or
621 621 \begin_inset ERT
622 622 status Collapsed
623 623
624 624 \layout Standard
625 625
626 626 \backslash
627 627 verb|--prefix|
628 628 \end_inset
629 629
630 630 ).
631 631 For example:
632 632 \newline
633 633
634 634 \begin_inset ERT
635 635 status Collapsed
636 636
637 637 \layout Standard
638 638
639 639 \backslash
640 640 verb|$ python setup.py install --home $HOME/local|
641 641 \end_inset
642 642
643 643
644 644 \newline
645 645 will install IPython into
646 646 \family typewriter
647 647 $HOME/local
648 648 \family default
649 649 and its subdirectories (creating them if necessary).
650 650 \newline
651 651 You can type
652 652 \newline
653 653
654 654 \begin_inset ERT
655 655 status Collapsed
656 656
657 657 \layout Standard
658 658
659 659 \backslash
660 660 verb|$ python setup.py --help|
661 661 \end_inset
662 662
663 663
664 664 \newline
665 665 for more details.
666 666 \newline
667 667 Note that if you change the default location for
668 668 \begin_inset ERT
669 669 status Collapsed
670 670
671 671 \layout Standard
672 672
673 673 \backslash
674 674 verb|--home|
675 675 \end_inset
676 676
677 677 at installation, IPython may end up installed at a location which is not
678 678 part of your
679 679 \family typewriter
680 680 $PYTHONPATH
681 681 \family default
682 682 environment variable.
683 683 In this case, you'll need to configure this variable to include the actual
684 684 directory where the
685 685 \family typewriter
686 686 IPython/
687 687 \family default
688 688 directory ended (typically the value you give to
689 689 \begin_inset ERT
690 690 status Collapsed
691 691
692 692 \layout Standard
693 693
694 694 \backslash
695 695 verb|--home|
696 696 \end_inset
697 697
698 698 plus
699 699 \family typewriter
700 700 /lib/python
701 701 \family default
702 702 ).
703 703 \layout Subsubsection
704 704
705 705 Mac OSX information
706 706 \layout Standard
707 707
708 708 Under OSX, there is a choice you need to make.
709 709 Apple ships its own build of Python, which lives in the core OSX filesystem
710 710 hierarchy.
711 711 You can also manually install a separate Python, either purely by hand
712 712 (typically in
713 713 \family typewriter
714 714 /usr/local
715 715 \family default
716 716 ) or by using Fink, which puts everything under
717 717 \family typewriter
718 718 /sw
719 719 \family default
720 720 .
721 721 Which route to follow is a matter of personal preference, as I've seen
722 722 users who favor each of the approaches.
723 723 Here I will simply list the known installation issues under OSX, along
724 724 with their solutions.
725 725 \layout Standard
726 726
727 727 This page:
728 728 \begin_inset LatexCommand \htmlurl{http://geosci.uchicago.edu/~tobis/pylab.html}
729 729
730 730 \end_inset
731 731
732 732 contains information on this topic, with additional details on how to make
733 733 IPython and matplotlib play nicely under OSX.
734 734 \layout Subsubsection*
735 735
736 736 GUI problems
737 737 \layout Standard
738 738
739 739 The following instructions apply to an install of IPython under OSX from
740 740 unpacking the
741 741 \family typewriter
742 742 .tar.gz
743 743 \family default
744 744 distribution and installing it for the default Python interpreter shipped
745 745 by Apple.
746 746 If you are using a fink install, fink will take care of these details for
747 747 you, by installing IPython against fink's Python.
748 748 \layout Standard
749 749
750 750 IPython offers various forms of support for interacting with graphical applicati
751 751 ons from the command line, from simple Tk apps (which are in principle always
752 752 supported by Python) to interactive control of WX, Qt and GTK apps.
753 753 Under OSX, however, this requires that ipython is installed by calling
754 754 the special
755 755 \family typewriter
756 756 pythonw
757 757 \family default
758 758 script at installation time, which takes care of coordinating things with
759 759 Apple's graphical environment.
760 760 \layout Standard
761 761
762 762 So when installing under OSX, it is best to use the following command:
763 763 \family typewriter
764 764
765 765 \newline
766 766
767 767 \family default
768 768
769 769 \begin_inset ERT
770 770 status Collapsed
771 771
772 772 \layout Standard
773 773
774 774 \backslash
775 775 verb| $ sudo pythonw setup.py install --install-scripts=/usr/local/bin|
776 776 \end_inset
777 777
778 778
779 779 \newline
780 780 or
781 781 \newline
782 782
783 783 \begin_inset ERT
784 784 status Open
785 785
786 786 \layout Standard
787 787
788 788 \backslash
789 789 verb| $ sudo pythonw setup.py install --install-scripts=/usr/bin|
790 790 \end_inset
791 791
792 792
793 793 \newline
794 794 depending on where you like to keep hand-installed executables.
795 795 \layout Standard
796 796
797 797 The resulting script will have an appropriate shebang line (the first line
798 798 in the script whic begins with
799 799 \family typewriter
800 800 #!...
801 801 \family default
802 802 ) such that the ipython interpreter can interact with the OS X GUI.
803 803 If the installed version does not work and has a shebang line that points
804 804 to, for example, just
805 805 \family typewriter
806 806 /usr/bin/python
807 807 \family default
808 808 , then you might have a stale, cached version in your
809 809 \family typewriter
810 810 build/scripts-<python-version>
811 811 \family default
812 812 directory.
813 813 Delete that directory and rerun the
814 814 \family typewriter
815 815 setup.py
816 816 \family default
817 817 .
818 818
819 819 \layout Standard
820 820
821 821 It is also a good idea to use the special flag
822 822 \begin_inset ERT
823 823 status Collapsed
824 824
825 825 \layout Standard
826 826
827 827 \backslash
828 828 verb|--install-scripts|
829 829 \end_inset
830 830
831 831 as indicated above, to ensure that the ipython scripts end up in a location
832 832 which is part of your
833 833 \family typewriter
834 834 $PATH
835 835 \family default
836 836 .
837 837 Otherwise Apple's Python will put the scripts in an internal directory
838 838 not available by default at the command line (if you use
839 839 \family typewriter
840 840 /usr/local/bin
841 841 \family default
842 842 , you need to make sure this is in your
843 843 \family typewriter
844 844 $PATH
845 845 \family default
846 846 , which may not be true by default).
847 847 \layout Subsubsection*
848 848
849 849 Readline problems
850 850 \layout Standard
851 851
852 852 By default, the Python version shipped by Apple does
853 853 \emph on
854 854 not
855 855 \emph default
856 856 include the readline library, so central to IPython's behavior.
857 857 If you install IPython against Apple's Python, you will not have arrow
858 858 keys, tab completion, etc.
859 859 For Mac OSX 10.3 (Panther), you can find a prebuilt readline library here:
860 860 \newline
861 861
862 862 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/readline-5.0-py2.3-macosx10.3.zip}
863 863
864 864 \end_inset
865 865
866 866
867 867 \layout Standard
868 868
869 869 If you are using OSX 10.4 (Tiger), after installing this package you need
870 870 to either:
871 871 \layout Enumerate
872 872
873 873 move
874 874 \family typewriter
875 875 readline.so
876 876 \family default
877 877 from
878 878 \family typewriter
879 879 /Library/Python/2.3
880 880 \family default
881 881 to
882 882 \family typewriter
883 883 /Library/Python/2.3/site-packages
884 884 \family default
885 885 , or
886 886 \layout Enumerate
887 887
888 888 install
889 889 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/TigerPython23Compat.pkg.zip}
890 890
891 891 \end_inset
892 892
893 893
894 894 \layout Standard
895 895
896 896 Users installing against Fink's Python or a properly hand-built one should
897 897 not have this problem.
898 898 \layout Subsubsection*
899 899
900 900 DarwinPorts
901 901 \layout Standard
902 902
903 903 I report here a message from an OSX user, who suggests an alternative means
904 904 of using IPython under this operating system with good results.
905 905 Please let me know of any updates that may be useful for this section.
906 906 His message is reproduced verbatim below:
907 907 \layout Quote
908 908
909 909 From: Markus Banfi
910 910 \family typewriter
911 911 <markus.banfi-AT-mospheira.net>
912 912 \layout Quote
913 913
914 914 As a MacOS X (10.4.2) user I prefer to install software using DawinPorts instead
915 915 of Fink.
916 916 I had no problems installing ipython with DarwinPorts.
917 917 It's just:
918 918 \layout Quote
919 919
920 920
921 921 \family typewriter
922 922 sudo port install py-ipython
923 923 \layout Quote
924 924
925 925 It automatically resolved all dependencies (python24, readline, py-readline).
926 926 So far I did not encounter any problems with the DarwinPorts port of ipython.
927 927
928 928 \layout Subsection
929 929
930 930
931 931 \begin_inset LatexCommand \label{sub:Under-Windows}
932 932
933 933 \end_inset
934 934
935 935 Windows instructions
936 936 \layout Standard
937 937
938 938 Some of IPython's very useful features are:
939 939 \layout Itemize
940 940
941 941 Integrated readline support (Tab-based file, object and attribute completion,
942 942 input history across sessions, editable command line, etc.)
943 943 \layout Itemize
944 944
945 945 Coloring of prompts, code and tracebacks.
946 946 \layout Standard
947 947
948 948 These, by default, are only available under Unix-like operating systems.
949 949 However, thanks to Gary Bishop's work, Windows XP/2k users can also benefit
950 950 from them.
951 951 His readline library implements both GNU readline functionality and color
952 952 support, so that IPython under Windows XP/2k can be as friendly and powerful
953 953 as under Unix-like environments.
954 954 \layout Standard
955 955
956 956 The
957 957 \family typewriter
958 958 readline
959 959 \family default
960 960 extension needs two other libraries to work, so in all you need:
961 961 \layout Enumerate
962 962
963 963
964 964 \family typewriter
965 965 PyWin32
966 966 \family default
967 967 from
968 968 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
969 969
970 970 \end_inset
971 971
972 972 .
973 973 \layout Enumerate
974 974
975 975
976 976 \family typewriter
977 977 CTypes
978 978 \family default
979 979 from
980 980 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
981 981
982 982 \end_inset
983 983
984 984 (you
985 985 \emph on
986 986 must
987 987 \emph default
988 988 use version 0.9.1 or newer).
989 989 \layout Enumerate
990 990
991 991
992 992 \family typewriter
993 993 Readline
994 994 \family default
995 995 for Windows from
996 996 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
997 997
998 998 \end_inset
999 999
1000 1000 .
1001 1001 \layout Standard
1002 1002
1003 1003
1004 1004 \series bold
1005 1005 Warning about a broken readline-like library:
1006 1006 \series default
1007 1007 several users have reported problems stemming from using the pseudo-readline
1008 1008 library at
1009 1009 \begin_inset LatexCommand \htmlurl{http://newcenturycomputers.net/projects/readline.html}
1010 1010
1011 1011 \end_inset
1012 1012
1013 1013 .
1014 1014 This is a broken library which, while called readline, only implements
1015 1015 an incomplete subset of the readline API.
1016 1016 Since it is still called readline, it fools IPython's detection mechanisms
1017 1017 and causes unpredictable crashes later.
1018 1018 If you wish to use IPython under Windows, you must NOT use this library,
1019 1019 which for all purposes is (at least as of version 1.6) terminally broken.
1020 1020 \layout Subsubsection
1021 1021
1022 1022 Installation procedure
1023 1023 \layout Standard
1024 1024
1025 1025 Once you have the above installed, from the IPython download directory grab
1026 1026 the
1027 1027 \family typewriter
1028 1028 ipython-XXX.win32.exe
1029 1029 \family default
1030 1030 file, where
1031 1031 \family typewriter
1032 1032 XXX
1033 1033 \family default
1034 1034 represents the version number.
1035 1035 This is a regular windows executable installer, which you can simply double-cli
1036 1036 ck to install.
1037 1037 It will add an entry for IPython to your Start Menu, as well as registering
1038 1038 IPython in the Windows list of applications, so you can later uninstall
1039 1039 it from the Control Panel.
1040 1040
1041 1041 \layout Standard
1042 1042
1043 1043 IPython tries to install the configuration information in a directory named
1044 1044
1045 1045 \family typewriter
1046 1046 .ipython
1047 1047 \family default
1048 1048 (
1049 1049 \family typewriter
1050 1050 _ipython
1051 1051 \family default
1052 1052 under Windows) located in your `home' directory.
1053 1053 IPython sets this directory by looking for a
1054 1054 \family typewriter
1055 1055 HOME
1056 1056 \family default
1057 1057 environment variable; if such a variable does not exist, it uses
1058 1058 \family typewriter
1059 1059 HOMEDRIVE
1060 1060 \backslash
1061 1061 HOMEPATH
1062 1062 \family default
1063 1063 (these are always defined by Windows).
1064 1064 This typically gives something like
1065 1065 \family typewriter
1066 1066 C:
1067 1067 \backslash
1068 1068 Documents and Settings
1069 1069 \backslash
1070 1070 YourUserName
1071 1071 \family default
1072 1072 , but your local details may vary.
1073 1073 In this directory you will find all the files that configure IPython's
1074 1074 defaults, and you can put there your profiles and extensions.
1075 1075 This directory is automatically added by IPython to
1076 1076 \family typewriter
1077 1077 sys.path
1078 1078 \family default
1079 1079 , so anything you place there can be found by
1080 1080 \family typewriter
1081 1081 import
1082 1082 \family default
1083 1083 statements.
1084 1084 \layout Paragraph
1085 1085
1086 1086 Upgrading
1087 1087 \layout Standard
1088 1088
1089 1089 For an IPython upgrade, you should first uninstall the previous version.
1090 1090 This will ensure that all files and directories (such as the documentation)
1091 1091 which carry embedded version strings in their names are properly removed.
1092 1092 \layout Paragraph
1093 1093
1094 1094 Manual installation under Win32
1095 1095 \layout Standard
1096 1096
1097 1097 In case the automatic installer does not work for some reason, you can download
1098 1098 the
1099 1099 \family typewriter
1100 1100 ipython-XXX.tar.gz
1101 1101 \family default
1102 1102 file, which contains the full IPython source distribution (the popular
1103 1103 WinZip can read
1104 1104 \family typewriter
1105 1105 .tar.gz
1106 1106 \family default
1107 1107 files).
1108 1108 After uncompressing the archive, you can install it at a command terminal
1109 1109 just like any other Python module, by using
1110 1110 \family typewriter
1111 1111 `python setup.py install'
1112 1112 \family default
1113 1113 .
1114 1114
1115 1115 \layout Standard
1116 1116
1117 1117 After the installation, run the supplied
1118 1118 \family typewriter
1119 1119 win32_manual_post_install.py
1120 1120 \family default
1121 1121 script, which creates the necessary Start Menu shortcuts for you.
1122 1122 \layout Subsection
1123 1123
1124 1124
1125 1125 \begin_inset LatexCommand \label{sec:upgrade}
1126 1126
1127 1127 \end_inset
1128 1128
1129 1129 Upgrading from a previous version
1130 1130 \layout Standard
1131 1131
1132 1132 If you are upgrading from a previous version of IPython, after doing the
1133 1133 routine installation described above, you should call IPython with the
1134 1134
1135 1135 \family typewriter
1136 1136 -upgrade
1137 1137 \family default
1138 1138 option the first time you run your new copy.
1139 1139 This will automatically update your configuration directory while preserving
1140 1140 copies of your old files.
1141 1141 You can then later merge back any personal customizations you may have
1142 1142 made into the new files.
1143 1143 It is a good idea to do this as there may be new options available in the
1144 1144 new configuration files which you will not have.
1145 1145 \layout Standard
1146 1146
1147 1147 Under Windows, if you don't know how to call python scripts with arguments
1148 1148 from a command line, simply delete the old config directory and IPython
1149 1149 will make a new one.
1150 1150 Win2k and WinXP users will find it in
1151 1151 \family typewriter
1152 1152 C:
1153 1153 \backslash
1154 1154 Documents and Settings
1155 1155 \backslash
1156 1156 YourUserName
1157 1157 \backslash
1158 1158 _ipython
1159 1159 \family default
1160 1160 , and Win 9x users under
1161 1161 \family typewriter
1162 1162 C:
1163 1163 \backslash
1164 1164 Program Files
1165 1165 \backslash
1166 1166 IPython
1167 1167 \backslash
1168 1168 _ipython.
1169 1169 \layout Section
1170 1170
1171 1171
1172 1172 \begin_inset LatexCommand \label{sec:good_config}
1173 1173
1174 1174 \end_inset
1175 1175
1176 1176
1177 1177 \begin_inset OptArg
1178 1178 collapsed true
1179 1179
1180 1180 \layout Standard
1181 1181
1182 1182 Initial configuration
1183 1183 \begin_inset ERT
1184 1184 status Collapsed
1185 1185
1186 1186 \layout Standard
1187 1187
1188 1188 \backslash
1189 1189 ldots
1190 1190 \end_inset
1191 1191
1192 1192
1193 1193 \end_inset
1194 1194
1195 1195 Initial configuration of your environment
1196 1196 \layout Standard
1197 1197
1198 1198 This section will help you set various things in your environment for your
1199 1199 IPython sessions to be as efficient as possible.
1200 1200 All of IPython's configuration information, along with several example
1201 1201 files, is stored in a directory named by default
1202 1202 \family typewriter
1203 1203 $HOME/.ipython
1204 1204 \family default
1205 1205 .
1206 1206 You can change this by defining the environment variable
1207 1207 \family typewriter
1208 1208 IPYTHONDIR
1209 1209 \family default
1210 1210 , or at runtime with the command line option
1211 1211 \family typewriter
1212 1212 -ipythondir
1213 1213 \family default
1214 1214 .
1215 1215 \layout Standard
1216 1216
1217 1217 If all goes well, the first time you run IPython it should automatically
1218 1218 create a user copy of the config directory for you, based on its builtin
1219 1219 defaults.
1220 1220 You can look at the files it creates to learn more about configuring the
1221 1221 system.
1222 1222 The main file you will modify to configure IPython's behavior is called
1223 1223
1224 1224 \family typewriter
1225 1225 ipythonrc
1226 1226 \family default
1227 1227 (with a
1228 1228 \family typewriter
1229 1229 .ini
1230 1230 \family default
1231 1231 extension under Windows), included for reference in Sec.
1232 1232
1233 1233 \begin_inset LatexCommand \ref{sec:ipytonrc-sample}
1234 1234
1235 1235 \end_inset
1236 1236
1237 1237 .
1238 1238 This file is very commented and has many variables you can change to suit
1239 1239 your taste, you can find more details in Sec.
1240 1240
1241 1241 \begin_inset LatexCommand \ref{sec:customization}
1242 1242
1243 1243 \end_inset
1244 1244
1245 1245 .
1246 1246 Here we discuss the basic things you will want to make sure things are
1247 1247 working properly from the beginning.
1248 1248 \layout Subsection
1249 1249
1250 1250
1251 1251 \begin_inset LatexCommand \label{sec:help-access}
1252 1252
1253 1253 \end_inset
1254 1254
1255 1255 Access to the Python help system
1256 1256 \layout Standard
1257 1257
1258 1258 This is true for Python in general (not just for IPython): you should have
1259 1259 an environment variable called
1260 1260 \family typewriter
1261 1261 PYTHONDOCS
1262 1262 \family default
1263 1263 pointing to the directory where your HTML Python documentation lives.
1264 1264 In my system it's
1265 1265 \family typewriter
1266 1266 /usr/share/doc/python-docs-2.3.4/html
1267 1267 \family default
1268 1268 , check your local details or ask your systems administrator.
1269 1269
1270 1270 \layout Standard
1271 1271
1272 1272 This is the directory which holds the HTML version of the Python manuals.
1273 1273 Unfortunately it seems that different Linux distributions package these
1274 1274 files differently, so you may have to look around a bit.
1275 1275 Below I show the contents of this directory on my system for reference:
1276 1276 \layout Standard
1277 1277
1278 1278
1279 1279 \family typewriter
1280 1280 [html]> ls
1281 1281 \newline
1282 1282 about.dat acks.html dist/ ext/ index.html lib/ modindex.html stdabout.dat tut/
1283 1283 about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
1284 1284 \layout Standard
1285 1285
1286 1286 You should really make sure this variable is correctly set so that Python's
1287 1287 pydoc-based help system works.
1288 1288 It is a powerful and convenient system with full access to the Python manuals
1289 1289 and all modules accessible to you.
1290 1290 \layout Standard
1291 1291
1292 1292 Under Windows it seems that pydoc finds the documentation automatically,
1293 1293 so no extra setup appears necessary.
1294 1294 \layout Subsection
1295 1295
1296 1296 Editor
1297 1297 \layout Standard
1298 1298
1299 1299 The
1300 1300 \family typewriter
1301 1301 %edit
1302 1302 \family default
1303 1303 command (and its alias
1304 1304 \family typewriter
1305 1305 %ed
1306 1306 \family default
1307 1307 ) will invoke the editor set in your environment as
1308 1308 \family typewriter
1309 1309 EDITOR
1310 1310 \family default
1311 1311 .
1312 1312 If this variable is not set, it will default to
1313 1313 \family typewriter
1314 1314 vi
1315 1315 \family default
1316 1316 under Linux/Unix and to
1317 1317 \family typewriter
1318 1318 notepad
1319 1319 \family default
1320 1320 under Windows.
1321 1321 You may want to set this variable properly and to a lightweight editor
1322 1322 which doesn't take too long to start (that is, something other than a new
1323 1323 instance of
1324 1324 \family typewriter
1325 1325 Emacs
1326 1326 \family default
1327 1327 ).
1328 1328 This way you can edit multi-line code quickly and with the power of a real
1329 1329 editor right inside IPython.
1330 1330
1331 1331 \layout Standard
1332 1332
1333 1333 If you are a dedicated
1334 1334 \family typewriter
1335 1335 Emacs
1336 1336 \family default
1337 1337 user, you should set up the
1338 1338 \family typewriter
1339 1339 Emacs
1340 1340 \family default
1341 1341 server so that new requests are handled by the original process.
1342 1342 This means that almost no time is spent in handling the request (assuming
1343 1343 an
1344 1344 \family typewriter
1345 1345 Emacs
1346 1346 \family default
1347 1347 process is already running).
1348 1348 For this to work, you need to set your
1349 1349 \family typewriter
1350 1350 EDITOR
1351 1351 \family default
1352 1352 environment variable to
1353 1353 \family typewriter
1354 1354 'emacsclient'
1355 1355 \family default
1356 1356 .
1357 1357
1358 1358 \family typewriter
1359 1359
1360 1360 \family default
1361 1361 The code below, supplied by Francois Pinard, can then be used in your
1362 1362 \family typewriter
1363 1363 .emacs
1364 1364 \family default
1365 1365 file to enable the server:
1366 1366 \layout Standard
1367 1367
1368 1368
1369 1369 \family typewriter
1370 1370 (defvar server-buffer-clients)
1371 1371 \newline
1372 1372 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
1373 1373 \newline
1374 1374
1375 1375 \begin_inset ERT
1376 1376 status Collapsed
1377 1377
1378 1378 \layout Standard
1379 1379
1380 1380 \backslash
1381 1381 hspace*{0mm}
1382 1382 \end_inset
1383 1383
1384 1384 \SpecialChar ~
1385 1385 \SpecialChar ~
1386 1386 (server-start)
1387 1387 \newline
1388 1388
1389 1389 \begin_inset ERT
1390 1390 status Collapsed
1391 1391
1392 1392 \layout Standard
1393 1393
1394 1394 \backslash
1395 1395 hspace*{0mm}
1396 1396 \end_inset
1397 1397
1398 1398 \SpecialChar ~
1399 1399 \SpecialChar ~
1400 1400 (defun fp-kill-server-with-buffer-routine ()
1401 1401 \newline
1402 1402
1403 1403 \begin_inset ERT
1404 1404 status Collapsed
1405 1405
1406 1406 \layout Standard
1407 1407
1408 1408 \backslash
1409 1409 hspace*{0mm}
1410 1410 \end_inset
1411 1411
1412 1412 \SpecialChar ~
1413 1413 \SpecialChar ~
1414 1414 \SpecialChar ~
1415 1415 \SpecialChar ~
1416 1416 (and server-buffer-clients (server-done)))
1417 1417 \newline
1418 1418
1419 1419 \begin_inset ERT
1420 1420 status Collapsed
1421 1421
1422 1422 \layout Standard
1423 1423
1424 1424 \backslash
1425 1425 hspace*{0mm}
1426 1426 \end_inset
1427 1427
1428 1428 \SpecialChar ~
1429 1429 \SpecialChar ~
1430 1430 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
1431 1431 \layout Standard
1432 1432
1433 1433 You can also set the value of this editor via the commmand-line option '-
1434 1434 \family typewriter
1435 1435 editor'
1436 1436 \family default
1437 1437 or in your
1438 1438 \family typewriter
1439 1439 ipythonrc
1440 1440 \family default
1441 1441 file.
1442 1442 This is useful if you wish to use specifically for IPython an editor different
1443 1443 from your typical default (and for Windows users who tend to use fewer
1444 1444 environment variables).
1445 1445 \layout Subsection
1446 1446
1447 1447 Color
1448 1448 \layout Standard
1449 1449
1450 1450 The default IPython configuration has most bells and whistles turned on
1451 1451 (they're pretty safe).
1452 1452 But there's one that
1453 1453 \emph on
1454 1454 may
1455 1455 \emph default
1456 1456 cause problems on some systems: the use of color on screen for displaying
1457 1457 information.
1458 1458 This is very useful, since IPython can show prompts and exception tracebacks
1459 1459 with various colors, display syntax-highlighted source code, and in general
1460 1460 make it easier to visually parse information.
1461 1461 \layout Standard
1462 1462
1463 1463 The following terminals seem to handle the color sequences fine:
1464 1464 \layout Itemize
1465 1465
1466 1466 Linux main text console, KDE Konsole, Gnome Terminal, E-term, rxvt, xterm.
1467 1467 \layout Itemize
1468 1468
1469 1469 CDE terminal (tested under Solaris).
1470 1470 This one boldfaces light colors.
1471 1471 \layout Itemize
1472 1472
1473 1473 (X)Emacs buffers.
1474 1474 See sec.
1475 1475 \begin_inset LatexCommand \ref{sec:emacs}
1476 1476
1477 1477 \end_inset
1478 1478
1479 1479 for more details on using IPython with (X)Emacs.
1480 1480 \layout Itemize
1481 1481
1482 1482 A Windows (XP/2k) command prompt
1483 1483 \emph on
1484 1484 with Gary Bishop's support extensions
1485 1485 \emph default
1486 1486 .
1487 1487 Gary's extensions are discussed in Sec.\SpecialChar ~
1488 1488
1489 1489 \begin_inset LatexCommand \ref{sub:Under-Windows}
1490 1490
1491 1491 \end_inset
1492 1492
1493 1493 .
1494 1494 \layout Itemize
1495 1495
1496 1496 A Windows (XP/2k) CygWin shell.
1497 1497 Although some users have reported problems; it is not clear whether there
1498 1498 is an issue for everyone or only under specific configurations.
1499 1499 If you have full color support under cygwin, please post to the IPython
1500 1500 mailing list so this issue can be resolved for all users.
1501 1501 \layout Standard
1502 1502
1503 1503 These have shown problems:
1504 1504 \layout Itemize
1505 1505
1506 1506 Windows command prompt in WinXP/2k logged into a Linux machine via telnet
1507 1507 or ssh.
1508 1508 \layout Itemize
1509 1509
1510 1510 Windows native command prompt in WinXP/2k,
1511 1511 \emph on
1512 1512 without
1513 1513 \emph default
1514 1514 Gary Bishop's extensions.
1515 1515 Once Gary's readline library is installed, the normal WinXP/2k command
1516 1516 prompt works perfectly.
1517 1517 \layout Standard
1518 1518
1519 1519 Currently the following color schemes are available:
1520 1520 \layout Itemize
1521 1521
1522 1522
1523 1523 \family typewriter
1524 1524 NoColor
1525 1525 \family default
1526 1526 : uses no color escapes at all (all escapes are empty
1527 1527 \begin_inset Quotes eld
1528 1528 \end_inset
1529 1529
1530 1530
1531 1531 \begin_inset Quotes eld
1532 1532 \end_inset
1533 1533
1534 1534 strings).
1535 1535 This 'scheme' is thus fully safe to use in any terminal.
1536 1536 \layout Itemize
1537 1537
1538 1538
1539 1539 \family typewriter
1540 1540 Linux
1541 1541 \family default
1542 1542 : works well in Linux console type environments: dark background with light
1543 1543 fonts.
1544 1544 It uses bright colors for information, so it is difficult to read if you
1545 1545 have a light colored background.
1546 1546 \layout Itemize
1547 1547
1548 1548
1549 1549 \family typewriter
1550 1550 LightBG
1551 1551 \family default
1552 1552 : the basic colors are similar to those in the
1553 1553 \family typewriter
1554 1554 Linux
1555 1555 \family default
1556 1556 scheme but darker.
1557 1557 It is easy to read in terminals with light backgrounds.
1558 1558 \layout Standard
1559 1559
1560 1560 IPython uses colors for two main groups of things: prompts and tracebacks
1561 1561 which are directly printed to the terminal, and the object introspection
1562 1562 system which passes large sets of data through a pager.
1563 1563 \layout Subsubsection
1564 1564
1565 1565 Input/Output prompts and exception tracebacks
1566 1566 \layout Standard
1567 1567
1568 1568 You can test whether the colored prompts and tracebacks work on your system
1569 1569 interactively by typing
1570 1570 \family typewriter
1571 1571 '%colors Linux'
1572 1572 \family default
1573 1573 at the prompt (use '
1574 1574 \family typewriter
1575 1575 %colors LightBG'
1576 1576 \family default
1577 1577 if your terminal has a light background).
1578 1578 If the input prompt shows garbage like:
1579 1579 \newline
1580 1580
1581 1581 \family typewriter
1582 1582 [0;32mIn [[1;32m1[0;32m]: [0;00m
1583 1583 \family default
1584 1584
1585 1585 \newline
1586 1586 instead of (in color) something like:
1587 1587 \newline
1588 1588
1589 1589 \family typewriter
1590 1590 In [1]:
1591 1591 \family default
1592 1592
1593 1593 \newline
1594 1594 this means that your terminal doesn't properly handle color escape sequences.
1595 1595 You can go to a 'no color' mode by typing '
1596 1596 \family typewriter
1597 1597 %colors NoColor
1598 1598 \family default
1599 1599 '.
1600 1600
1601 1601 \layout Standard
1602 1602
1603 1603 You can try using a different terminal emulator program.
1604 1604 To permanently set your color preferences, edit the file
1605 1605 \family typewriter
1606 1606 $HOME/.ipython/ipythonrc
1607 1607 \family default
1608 1608 and set the
1609 1609 \family typewriter
1610 1610 colors
1611 1611 \family default
1612 1612 option to the desired value.
1613 1613 \layout Subsubsection
1614 1614
1615 1615 Object details (types, docstrings, source code, etc.)
1616 1616 \layout Standard
1617 1617
1618 1618 IPython has a set of special functions for studying the objects you are
1619 1619 working with, discussed in detail in Sec.
1620 1620
1621 1621 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1622 1622
1623 1623 \end_inset
1624 1624
1625 1625 .
1626 1626 But this system relies on passing information which is longer than your
1627 1627 screen through a data pager, such as the common Unix
1628 1628 \family typewriter
1629 1629 less
1630 1630 \family default
1631 1631 and
1632 1632 \family typewriter
1633 1633 more
1634 1634 \family default
1635 1635 programs.
1636 1636 In order to be able to see this information in color, your pager needs
1637 1637 to be properly configured.
1638 1638 I strongly recommend using
1639 1639 \family typewriter
1640 1640 less
1641 1641 \family default
1642 1642 instead of
1643 1643 \family typewriter
1644 1644 more
1645 1645 \family default
1646 1646 , as it seems that
1647 1647 \family typewriter
1648 1648 more
1649 1649 \family default
1650 1650 simply can not understand colored text correctly.
1651 1651 \layout Standard
1652 1652
1653 1653 In order to configure
1654 1654 \family typewriter
1655 1655 less
1656 1656 \family default
1657 1657 as your default pager, do the following:
1658 1658 \layout Enumerate
1659 1659
1660 1660 Set the environment
1661 1661 \family typewriter
1662 1662 PAGER
1663 1663 \family default
1664 1664 variable to
1665 1665 \family typewriter
1666 1666 less
1667 1667 \family default
1668 1668 .
1669 1669 \layout Enumerate
1670 1670
1671 1671 Set the environment
1672 1672 \family typewriter
1673 1673 LESS
1674 1674 \family default
1675 1675 variable to
1676 1676 \family typewriter
1677 1677 -r
1678 1678 \family default
1679 1679 (plus any other options you always want to pass to
1680 1680 \family typewriter
1681 1681 less
1682 1682 \family default
1683 1683 by default).
1684 1684 This tells
1685 1685 \family typewriter
1686 1686 less
1687 1687 \family default
1688 1688 to properly interpret control sequences, which is how color information
1689 1689 is given to your terminal.
1690 1690 \layout Standard
1691 1691
1692 1692 For the
1693 1693 \family typewriter
1694 1694 csh
1695 1695 \family default
1696 1696 or
1697 1697 \family typewriter
1698 1698 tcsh
1699 1699 \family default
1700 1700 shells, add to your
1701 1701 \family typewriter
1702 1702 ~/.cshrc
1703 1703 \family default
1704 1704 file the lines:
1705 1705 \layout Standard
1706 1706
1707 1707
1708 1708 \family typewriter
1709 1709 setenv PAGER less
1710 1710 \newline
1711 1711 setenv LESS -r
1712 1712 \layout Standard
1713 1713
1714 1714 There is similar syntax for other Unix shells, look at your system documentation
1715 1715 for details.
1716 1716 \layout Standard
1717 1717
1718 1718 If you are on a system which lacks proper data pagers (such as Windows),
1719 1719 IPython will use a very limited builtin pager.
1720 1720 \layout Subsection
1721 1721
1722 1722
1723 1723 \begin_inset LatexCommand \label{sec:emacs}
1724 1724
1725 1725 \end_inset
1726 1726
1727 1727 (X)Emacs configuration
1728 1728 \layout Standard
1729 1729
1730 1730 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, currently
1731 1731 (X)Emacs and IPython get along very well.
1732 1732
1733 1733 \layout Standard
1734 1734
1735 1735
1736 1736 \series bold
1737 1737 Important note:
1738 1738 \series default
1739 1739 You will need to use a recent enough version of
1740 1740 \family typewriter
1741 1741 python-mode.el
1742 1742 \family default
1743 1743 , along with the file
1744 1744 \family typewriter
1745 1745 ipython.el
1746 1746 \family default
1747 1747 .
1748 1748 You can check that the version you have of
1749 1749 \family typewriter
1750 1750 python-mode.el
1751 1751 \family default
1752 1752 is new enough by either looking at the revision number in the file itself,
1753 1753 or asking for it in (X)Emacs via
1754 1754 \family typewriter
1755 1755 M-x py-version
1756 1756 \family default
1757 1757 .
1758 1758 Versions 4.68 and newer contain the necessary fixes for proper IPython support.
1759 1759 \layout Standard
1760 1760
1761 1761 The file
1762 1762 \family typewriter
1763 1763 ipython.el
1764 1764 \family default
1765 1765 is included with the IPython distribution, in the documentation directory
1766 1766 (where this manual resides in PDF and HTML formats).
1767 1767 \layout Standard
1768 1768
1769 1769 Once you put these files in your Emacs path, all you need in your
1770 1770 \family typewriter
1771 1771 .emacs
1772 1772 \family default
1773 1773 file is:
1774 1774 \layout Standard
1775 1775
1776 1776
1777 1777 \family typewriter
1778 1778 (require 'ipython)
1779 1779 \layout Standard
1780 1780
1781 1781 This should give you full support for executing code snippets via IPython,
1782 1782 opening IPython as your Python shell via
1783 1783 \family typewriter
1784 1784 C-c\SpecialChar ~
1785 1785 !
1786 1786 \family default
1787 1787 , etc.
1788 1788
1789 1789 \layout Subsubsection*
1790 1790
1791 1791 Notes
1792 1792 \layout Itemize
1793 1793
1794 1794 There is one caveat you should be aware of: you must start the IPython shell
1795 1795
1796 1796 \emph on
1797 1797 before
1798 1798 \emph default
1799 1799 attempting to execute any code regions via
1800 1800 \family typewriter
1801 1801 C-c\SpecialChar ~
1802 1802 |
1803 1803 \family default
1804 1804 .
1805 1805 Simply type
1806 1806 \family typewriter
1807 1807 C-c\SpecialChar ~
1808 1808 !
1809 1809 \family default
1810 1810 to start IPython before passing any code regions to the interpreter, and
1811 1811 you shouldn't experience any problems.
1812 1812 \newline
1813 1813 This is due to a bug in Python itself, which has been fixed for Python 2.3,
1814 1814 but exists as of Python 2.2.2 (reported as SF bug [ 737947 ]).
1815 1815 \layout Itemize
1816 1816
1817 1817 The (X)Emacs support is maintained by Alexander Schmolck, so all comments/reques
1818 1818 ts should be directed to him through the IPython mailing lists.
1819 1819
1820 1820 \layout Itemize
1821 1821
1822 1822 This code is still somewhat experimental so it's a bit rough around the
1823 1823 edges (although in practice, it works quite well).
1824 1824 \layout Itemize
1825 1825
1826 1826 Be aware that if you customize
1827 1827 \family typewriter
1828 1828 py-python-command
1829 1829 \family default
1830 1830 previously, this value will override what
1831 1831 \family typewriter
1832 1832 ipython.el
1833 1833 \family default
1834 1834 does (because loading the customization variables comes later).
1835 1835 \layout Section
1836 1836
1837 1837
1838 1838 \begin_inset LatexCommand \label{sec:quick_tips}
1839 1839
1840 1840 \end_inset
1841 1841
1842 1842 Quick tips
1843 1843 \layout Standard
1844 1844
1845 1845 IPython can be used as an improved replacement for the Python prompt, and
1846 1846 for that you don't really need to read any more of this manual.
1847 1847 But in this section we'll try to summarize a few tips on how to make the
1848 1848 most effective use of it for everyday Python development, highlighting
1849 1849 things you might miss in the rest of the manual (which is getting long).
1850 1850 We'll give references to parts in the manual which provide more detail
1851 1851 when appropriate.
1852 1852 \layout Standard
1853 1853
1854 1854 The following article by Jeremy Jones provides an introductory tutorial
1855 1855 about IPython:
1856 1856 \newline
1857 1857
1858 1858 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html}
1859 1859
1860 1860 \end_inset
1861 1861
1862 1862
1863 1863 \layout Itemize
1864 1864
1865 1865 The TAB key.
1866 1866 TAB-completion, especially for attributes, is a convenient way to explore
1867 1867 the structure of any object you're dealing with.
1868 1868 Simply type
1869 1869 \family typewriter
1870 1870 object_name.<TAB>
1871 1871 \family default
1872 1872 and a list of the object's attributes will be printed (see sec.
1873 1873
1874 1874 \begin_inset LatexCommand \ref{sec:readline}
1875 1875
1876 1876 \end_inset
1877 1877
1878 1878 for more).
1879 1879 Tab completion also works on file and directory names, which combined with
1880 1880 IPython's alias system allows you to do from within IPython many of the
1881 1881 things you normally would need the system shell for.
1882 1882
1883 1883 \layout Itemize
1884 1884
1885 1885 Explore your objects.
1886 1886 Typing
1887 1887 \family typewriter
1888 1888 object_name?
1889 1889 \family default
1890 1890 will print all sorts of details about any object, including docstrings,
1891 1891 function definition lines (for call arguments) and constructor details
1892 1892 for classes.
1893 1893 The magic commands
1894 1894 \family typewriter
1895 1895 %pdoc
1896 1896 \family default
1897 1897 ,
1898 1898 \family typewriter
1899 1899 %pdef
1900 1900 \family default
1901 1901 ,
1902 1902 \family typewriter
1903 1903 %psource
1904 1904 \family default
1905 1905 and
1906 1906 \family typewriter
1907 1907 %pfile
1908 1908 \family default
1909 1909 will respectively print the docstring, function definition line, full source
1910 1910 code and the complete file for any object (when they can be found).
1911 1911 If automagic is on (it is by default), you don't need to type the '
1912 1912 \family typewriter
1913 1913 %
1914 1914 \family default
1915 1915 ' explicitly.
1916 1916 See sec.
1917 1917
1918 1918 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1919 1919
1920 1920 \end_inset
1921 1921
1922 1922 for more.
1923 1923 \layout Itemize
1924 1924
1925 1925 The
1926 1926 \family typewriter
1927 1927 %run
1928 1928 \family default
1929 1929 magic command allows you to run any python script and load all of its data
1930 1930 directly into the interactive namespace.
1931 1931 Since the file is re-read from disk each time, changes you make to it are
1932 1932 reflected immediately (in contrast to the behavior of
1933 1933 \family typewriter
1934 1934 import
1935 1935 \family default
1936 1936 ).
1937 1937 I rarely use
1938 1938 \family typewriter
1939 1939 import
1940 1940 \family default
1941 1941 for code I am testing, relying on
1942 1942 \family typewriter
1943 1943 %run
1944 1944 \family default
1945 1945 instead.
1946 1946 See sec.
1947 1947
1948 1948 \begin_inset LatexCommand \ref{sec:magic}
1949 1949
1950 1950 \end_inset
1951 1951
1952 1952 for more on this and other magic commands, or type the name of any magic
1953 1953 command and ? to get details on it.
1954 1954 See also sec.
1955 1955
1956 1956 \begin_inset LatexCommand \ref{sec:dreload}
1957 1957
1958 1958 \end_inset
1959 1959
1960 1960 for a recursive reload command.
1961 1961 \newline
1962 1962
1963 1963 \family typewriter
1964 1964 %run
1965 1965 \family default
1966 1966 also has special flags for timing the execution of your scripts (
1967 1967 \family typewriter
1968 1968 -t
1969 1969 \family default
1970 1970 ) and for executing them under the control of either Python's
1971 1971 \family typewriter
1972 1972 pdb
1973 1973 \family default
1974 1974 debugger (
1975 1975 \family typewriter
1976 1976 -d
1977 1977 \family default
1978 1978 ) or profiler (
1979 1979 \family typewriter
1980 1980 -p
1981 1981 \family default
1982 1982 ).
1983 1983 With all of these,
1984 1984 \family typewriter
1985 1985 %run
1986 1986 \family default
1987 1987 can be used as the main tool for efficient interactive development of code
1988 1988 which you write in your editor of choice.
1989 1989 \layout Itemize
1990 1990
1991 1991 Use the Python debugger,
1992 1992 \family typewriter
1993 1993 pdb
1994 1994 \family default
1995 1995
1996 1996 \begin_inset Foot
1997 1997 collapsed true
1998 1998
1999 1999 \layout Standard
2000 2000
2001 2001 Thanks to Christian Hart and Matthew Arnison for the suggestions leading
2002 2002 to IPython's improved debugger and profiler support.
2003 2003 \end_inset
2004 2004
2005 2005 .
2006 2006 The
2007 2007 \family typewriter
2008 2008 %pdb
2009 2009 \family default
2010 2010 command allows you to toggle on and off the automatic invocation of an
2011 2011 IPython-enhanced
2012 2012 \family typewriter
2013 2013 pdb
2014 2014 \family default
2015 2015 debugger (with coloring, tab completion and more) at any uncaught exception.
2016 2016 The advantage of this is that
2017 2017 \family typewriter
2018 2018 pdb
2019 2019 \family default
2020 2020 starts
2021 2021 \emph on
2022 2022 inside
2023 2023 \emph default
2024 2024 the function where the exception occurred, with all data still available.
2025 2025 You can print variables, see code, execute statements and even walk up
2026 2026 and down the call stack to track down the true source of the problem (which
2027 2027 often is many layers in the stack above where the exception gets triggered).
2028 2028 \newline
2029 2029 Running programs with
2030 2030 \family typewriter
2031 2031 %run
2032 2032 \family default
2033 2033 and pdb active can be an efficient to develop and debug code, in many cases
2034 2034 eliminating the need for
2035 2035 \family typewriter
2036 2036 print
2037 2037 \family default
2038 2038 statements or external debugging tools.
2039 2039 I often simply put a
2040 2040 \family typewriter
2041 2041 1/0
2042 2042 \family default
2043 2043 in a place where I want to take a look so that pdb gets called, quickly
2044 2044 view whatever variables I need to or test various pieces of code and then
2045 2045 remove the
2046 2046 \family typewriter
2047 2047 1/0
2048 2048 \family default
2049 2049 .
2050 2050 \newline
2051 2051 Note also that `
2052 2052 \family typewriter
2053 2053 %run -d
2054 2054 \family default
2055 2055 ' activates
2056 2056 \family typewriter
2057 2057 pdb
2058 2058 \family default
2059 2059 and automatically sets initial breakpoints for you to step through your
2060 2060 code, watch variables, etc.
2061 2061 See Sec.\SpecialChar ~
2062 2062
2063 2063 \begin_inset LatexCommand \ref{sec:cache_output}
2064 2064
2065 2065 \end_inset
2066 2066
2067 2067 for details.
2068 2068 \layout Itemize
2069 2069
2070 2070 Use the output cache.
2071 2071 All output results are automatically stored in a global dictionary named
2072 2072
2073 2073 \family typewriter
2074 2074 Out
2075 2075 \family default
2076 2076 and variables named
2077 2077 \family typewriter
2078 2078 _1
2079 2079 \family default
2080 2080 ,
2081 2081 \family typewriter
2082 2082 _2
2083 2083 \family default
2084 2084 , etc.
2085 2085 alias them.
2086 2086 For example, the result of input line 4 is available either as
2087 2087 \family typewriter
2088 2088 Out[4]
2089 2089 \family default
2090 2090 or as
2091 2091 \family typewriter
2092 2092 _4
2093 2093 \family default
2094 2094 .
2095 2095 Additionally, three variables named
2096 2096 \family typewriter
2097 2097 _
2098 2098 \family default
2099 2099 ,
2100 2100 \family typewriter
2101 2101 __
2102 2102 \family default
2103 2103 and
2104 2104 \family typewriter
2105 2105 ___
2106 2106 \family default
2107 2107 are always kept updated with the for the last three results.
2108 2108 This allows you to recall any previous result and further use it for new
2109 2109 calculations.
2110 2110 See Sec.\SpecialChar ~
2111 2111
2112 2112 \begin_inset LatexCommand \ref{sec:cache_output}
2113 2113
2114 2114 \end_inset
2115 2115
2116 2116 for more.
2117 2117 \layout Itemize
2118 2118
2119 2119 Put a '
2120 2120 \family typewriter
2121 2121 ;
2122 2122 \family default
2123 2123 ' at the end of a line to supress the printing of output.
2124 2124 This is useful when doing calculations which generate long output you are
2125 2125 not interested in seeing.
2126 2126 The
2127 2127 \family typewriter
2128 2128 _*
2129 2129 \family default
2130 2130 variables and the
2131 2131 \family typewriter
2132 2132 Out[]
2133 2133 \family default
2134 2134 list do get updated with the contents of the output, even if it is not
2135 2135 printed.
2136 2136 You can thus still access the generated results this way for further processing.
2137 2137 \layout Itemize
2138 2138
2139 2139 A similar system exists for caching input.
2140 2140 All input is stored in a global list called
2141 2141 \family typewriter
2142 2142 In
2143 2143 \family default
2144 2144 , so you can re-execute lines 22 through 28 plus line 34 by typing
2145 2145 \family typewriter
2146 2146 'exec In[22:29]+In[34]'
2147 2147 \family default
2148 2148 (using Python slicing notation).
2149 2149 If you need to execute the same set of lines often, you can assign them
2150 2150 to a macro with the
2151 2151 \family typewriter
2152 2152 %macro
2153 2153 \family default
2154 2154
2155 2155 \family typewriter
2156 2156 function.
2157 2157
2158 2158 \family default
2159 2159 See sec.
2160 2160
2161 2161 \begin_inset LatexCommand \ref{sec:cache_input}
2162 2162
2163 2163 \end_inset
2164 2164
2165 2165 for more.
2166 2166 \layout Itemize
2167 2167
2168 2168 Use your input history.
2169 2169 The
2170 2170 \family typewriter
2171 2171 %hist
2172 2172 \family default
2173 2173 command can show you all previous input, without line numbers if desired
2174 2174 (option
2175 2175 \family typewriter
2176 2176 -n
2177 2177 \family default
2178 2178 ) so you can directly copy and paste code either back in IPython or in a
2179 2179 text editor.
2180 2180 You can also save all your history by turning on logging via
2181 2181 \family typewriter
2182 2182 %logstart
2183 2183 \family default
2184 2184 ; these logs can later be either reloaded as IPython sessions or used as
2185 2185 code for your programs.
2186 2186 \layout Itemize
2187 2187
2188 2188 Define your own macros with
2189 2189 \family typewriter
2190 2190 %macro
2191 2191 \family default
2192 2192 .
2193 2193 This can be useful for automating sequences of expressions when working
2194 2194 interactively.
2195 2195 \layout Itemize
2196 2196
2197 2197 Define your own system aliases.
2198 2198 Even though IPython gives you access to your system shell via the
2199 2199 \family typewriter
2200 2200 !
2201 2201 \family default
2202 2202 prefix, it is convenient to have aliases to the system commands you use
2203 2203 most often.
2204 2204 This allows you to work seamlessly from inside IPython with the same commands
2205 2205 you are used to in your system shell.
2206 2206 \newline
2207 2207 IPython comes with some pre-defined aliases and a complete system for changing
2208 2208 directories, both via a stack (see
2209 2209 \family typewriter
2210 2210 %pushd
2211 2211 \family default
2212 2212 ,
2213 2213 \family typewriter
2214 2214 %popd
2215 2215 \family default
2216 2216 and
2217 2217 \family typewriter
2218 2218 %ds
2219 2219 \family default
2220 2220 ) and via direct
2221 2221 \family typewriter
2222 2222 %cd
2223 2223 \family default
2224 2224 .
2225 2225 The latter keeps a history of visited directories and allows you to go
2226 2226 to any previously visited one.
2227 2227 \layout Itemize
2228 2228
2229 2229 Use Python to manipulate the results of system commands.
2230 2230 The `
2231 2231 \family typewriter
2232 2232 !!
2233 2233 \family default
2234 2234 ' special syntax, and the
2235 2235 \family typewriter
2236 2236 %sc
2237 2237 \family default
2238 2238 and
2239 2239 \family typewriter
2240 2240 %sx
2241 2241 \family default
2242 2242 magic commands allow you to capture system output into Python variables.
2243 2243 \layout Itemize
2244 2244
2245 2245 Expand python variables when calling the shell (either via
2246 2246 \family typewriter
2247 2247 `!'
2248 2248 \family default
2249 2249 and
2250 2250 \family typewriter
2251 2251 `!!'
2252 2252 \family default
2253 2253 or via aliases) by prepending a
2254 2254 \family typewriter
2255 2255 $
2256 2256 \family default
2257 2257 in front of them.
2258 2258 You can also expand complete python expressions.
2259 2259 See sec.\SpecialChar ~
2260 2260
2261 2261 \begin_inset LatexCommand \ref{sub:System-shell-access}
2262 2262
2263 2263 \end_inset
2264 2264
2265 2265 for more.
2266 2266 \layout Itemize
2267 2267
2268 2268 Use profiles to maintain different configurations (modules to load, function
2269 2269 definitions, option settings) for particular tasks.
2270 2270 You can then have customized versions of IPython for specific purposes.
2271 2271 See sec.\SpecialChar ~
2272 2272
2273 2273 \begin_inset LatexCommand \ref{sec:profiles}
2274 2274
2275 2275 \end_inset
2276 2276
2277 2277 for more.
2278 2278 \layout Itemize
2279 2279
2280 2280 Embed IPython in your programs.
2281 2281 A few lines of code are enough to load a complete IPython inside your own
2282 2282 programs, giving you the ability to work with your data interactively after
2283 2283 automatic processing has been completed.
2284 2284 See sec.\SpecialChar ~
2285 2285
2286 2286 \begin_inset LatexCommand \ref{sec:embed}
2287 2287
2288 2288 \end_inset
2289 2289
2290 2290 for more.
2291 2291 \layout Itemize
2292 2292
2293 2293 Use the Python profiler.
2294 2294 When dealing with performance issues, the
2295 2295 \family typewriter
2296 2296 %run
2297 2297 \family default
2298 2298 command with a
2299 2299 \family typewriter
2300 2300 -p
2301 2301 \family default
2302 2302 option allows you to run complete programs under the control of the Python
2303 2303 profiler.
2304 2304 The
2305 2305 \family typewriter
2306 2306 %prun
2307 2307 \family default
2308 2308 command does a similar job for single Python expressions (like function
2309 2309 calls).
2310 2310 \layout Itemize
2311 2311
2312 2312 Use
2313 2313 \family typewriter
2314 2314 %edit
2315 2315 \family default
2316 2316 to have almost multiline editing.
2317 2317 While IPython doesn't support true multiline editing, this command allows
2318 2318 you to call an editor on the spot, and IPython will execute the code you
2319 2319 type in there as if it were typed interactively.
2320 2320 \layout Itemize
2321 2321
2322 2322 Use the IPython.demo.Demo class to load any Python script as an interactive
2323 2323 demo.
2324 2324 With a minimal amount of simple markup, you can control the execution of
2325 2325 the script, stopping as needed.
2326 2326 See sec.\SpecialChar ~
2327 2327
2328 2328 \begin_inset LatexCommand \ref{sec:interactive-demos}
2329 2329
2330 2330 \end_inset
2331 2331
2332 2332 for more.
2333 2333 \layout Standard
2334 2334
2335 2335
2336 2336 \series bold
2337 2337 Effective logging:
2338 2338 \series default
2339 2339 a very useful suggestion sent in by Robert Kern follows
2340 2340 \layout Standard
2341 2341
2342 2342 I recently happened on a nifty way to keep tidy per-project log files.
2343 2343 I made a profile for my project (which is called "parkfield").
2344 2344 \layout LyX-Code
2345 2345
2346 2346 include ipythonrc
2347 2347 \layout LyX-Code
2348 2348
2349 2349 logfile '' # cancel earlier logfile invocation
2350 2350 \layout LyX-Code
2351 2351
2352 2352 execute import time
2353 2353 \layout LyX-Code
2354 2354
2355 2355 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
2356 2356 \layout LyX-Code
2357 2357
2358 2358 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
2359 2359 \layout Standard
2360 2360
2361 2361 I also added a shell alias for convenience:
2362 2362 \layout LyX-Code
2363 2363
2364 2364 alias parkfield="ipython -pylab -profile parkfield"
2365 2365 \layout Standard
2366 2366
2367 2367 Now I have a nice little directory with everything I ever type in, organized
2368 2368 by project and date.
2369 2369 \layout Standard
2370 2370
2371 2371
2372 2372 \series bold
2373 2373 Contribute your own:
2374 2374 \series default
2375 2375 If you have your own favorite tip on using IPython efficiently for a certain
2376 2376 task (especially things which can't be done in the normal Python interpreter),
2377 2377 don't hesitate to send it!
2378 2378 \layout Section
2379 2379
2380 2380 Command-line use
2381 2381 \layout Standard
2382 2382
2383 2383 You start IPython with the command:
2384 2384 \layout Standard
2385 2385
2386 2386
2387 2387 \family typewriter
2388 2388 $ ipython [options] files
2389 2389 \layout Standard
2390 2390
2391 2391 If invoked with no options, it executes all the files listed in sequence
2392 2392 and drops you into the interpreter while still acknowledging any options
2393 2393 you may have set in your ipythonrc file.
2394 2394 This behavior is different from standard Python, which when called as
2395 2395 \family typewriter
2396 2396 python -i
2397 2397 \family default
2398 2398 will only execute one file and ignore your configuration setup.
2399 2399 \layout Standard
2400 2400
2401 2401 Please note that some of the configuration options are not available at
2402 2402 the command line, simply because they are not practical here.
2403 2403 Look into your ipythonrc configuration file for details on those.
2404 2404 This file typically installed in the
2405 2405 \family typewriter
2406 2406 $HOME/.ipython
2407 2407 \family default
2408 2408 directory.
2409 2409 For Windows users,
2410 2410 \family typewriter
2411 2411 $HOME
2412 2412 \family default
2413 2413 resolves to
2414 2414 \family typewriter
2415 2415 C:
2416 2416 \backslash
2417 2417
2418 2418 \backslash
2419 2419 Documents and Settings
2420 2420 \backslash
2421 2421
2422 2422 \backslash
2423 2423 YourUserName
2424 2424 \family default
2425 2425 in most instances.
2426 2426 In the rest of this text, we will refer to this directory as
2427 2427 \family typewriter
2428 2428 IPYTHONDIR
2429 2429 \family default
2430 2430 .
2431 2431 \layout Subsection
2432 2432
2433 2433
2434 2434 \begin_inset LatexCommand \label{sec:threading-opts}
2435 2435
2436 2436 \end_inset
2437 2437
2438 2438 Special Threading Options
2439 2439 \layout Standard
2440 2440
2441 2441 The following special options are ONLY valid at the beginning of the command
2442 2442 line, and not later.
2443 2443 This is because they control the initial- ization of ipython itself, before
2444 2444 the normal option-handling mechanism is active.
2445 2445 \layout List
2446 2446 \labelwidthstring 00.00.0000
2447 2447
2448 2448
2449 2449 \family typewriter
2450 2450 \series bold
2451 2451 -gthread,\SpecialChar ~
2452 2452 -qthread,\SpecialChar ~
2453 2453 -wthread,\SpecialChar ~
2454 2454 -pylab:
2455 2455 \family default
2456 2456 \series default
2457 2457 Only
2458 2458 \emph on
2459 2459 one
2460 2460 \emph default
2461 2461 of these can be given, and it can only be given as the first option passed
2462 2462 to IPython (it will have no effect in any other position).
2463 2463 They provide threading support for the GTK Qt and WXPython toolkits, and
2464 2464 for the matplotlib library.
2465 2465 \layout List
2466 2466 \labelwidthstring 00.00.0000
2467 2467
2468 2468 \SpecialChar ~
2469 2469 With any of the first three options, IPython starts running a separate
2470 2470 thread for the graphical toolkit's operation, so that you can open and
2471 2471 control graphical elements from within an IPython command line, without
2472 2472 blocking.
2473 2473 All three provide essentially the same functionality, respectively for
2474 2474 GTK, QT and WXWidgets (via their Python interfaces).
2475 2475 \layout List
2476 2476 \labelwidthstring 00.00.0000
2477 2477
2478 2478 \SpecialChar ~
2479 2479 If
2480 2480 \family typewriter
2481 2481 -pylab
2482 2482 \family default
2483 2483 is given, IPython loads special support for the mat plotlib library (
2484 2484 \begin_inset LatexCommand \htmlurl{http://matplotlib.sourceforge.net}
2485 2485
2486 2486 \end_inset
2487 2487
2488 2488 ), allowing interactive usage of any of its backends as defined in the user's
2489 2489
2490 2490 \family typewriter
2491 2491 ~/.matplotlib/matplotlibrc
2492 2492 \family default
2493 2493 file.
2494 2494 It automatically activates GTK, Qt or WX threading for IPyhton if the choice
2495 2495 of matplotlib backend requires it.
2496 2496 It also modifies the
2497 2497 \family typewriter
2498 2498 %run
2499 2499 \family default
2500 2500 command to correctly execute (without blocking) any matplotlib-based script
2501 2501 which calls
2502 2502 \family typewriter
2503 2503 show()
2504 2504 \family default
2505 2505 at the end.
2506 2506
2507 2507 \layout List
2508 2508 \labelwidthstring 00.00.0000
2509 2509
2510 2510
2511 2511 \family typewriter
2512 2512 \series bold
2513 2513 -tk
2514 2514 \family default
2515 2515 \series default
2516 2516 The
2517 2517 \family typewriter
2518 2518 -g/q/wthread
2519 2519 \family default
2520 2520 options, and
2521 2521 \family typewriter
2522 2522 -pylab
2523 2523 \family default
2524 2524 (if matplotlib is configured to use GTK, Qt or WX), will normally block
2525 2525 Tk graphical interfaces.
2526 2526 This means that when either GTK, Qt or WX threading is active, any attempt
2527 2527 to open a Tk GUI will result in a dead window, and possibly cause the Python
2528 2528 interpreter to crash.
2529 2529 An extra option,
2530 2530 \family typewriter
2531 2531 -tk
2532 2532 \family default
2533 2533 , is available to address this issue.
2534 2534 It can
2535 2535 \emph on
2536 2536 only
2537 2537 \emph default
2538 2538 be given as a
2539 2539 \emph on
2540 2540 second
2541 2541 \emph default
2542 2542 option after any of the above (
2543 2543 \family typewriter
2544 2544 -gthread
2545 2545 \family default
2546 2546 ,
2547 2547 \family typewriter
2548 2548 -wthread
2549 2549 \family default
2550 2550 or
2551 2551 \family typewriter
2552 2552 -pylab
2553 2553 \family default
2554 2554 ).
2555 2555 \layout List
2556 2556 \labelwidthstring 00.00.0000
2557 2557
2558 2558 \SpecialChar ~
2559 2559 If
2560 2560 \family typewriter
2561 2561 -tk
2562 2562 \family default
2563 2563 is given, IPython will try to coordinate Tk threading with GTK, Qt or WX.
2564 2564 This is however potentially unreliable, and you will have to test on your
2565 2565 platform and Python configuration to determine whether it works for you.
2566 2566 Debian users have reported success, apparently due to the fact that Debian
2567 2567 builds all of Tcl, Tk, Tkinter and Python with pthreads support.
2568 2568 Under other Linux environments (such as Fedora Core 2/3), this option has
2569 2569 caused random crashes and lockups of the Python interpreter.
2570 2570 Under other operating systems (Mac OSX and Windows), you'll need to try
2571 2571 it to find out, since currently no user reports are available.
2572 2572 \layout List
2573 2573 \labelwidthstring 00.00.0000
2574 2574
2575 2575 \SpecialChar ~
2576 2576 There is unfortunately no way for IPython to determine at run time whether
2577 2577
2578 2578 \family typewriter
2579 2579 -tk
2580 2580 \family default
2581 2581 will work reliably or not, so you will need to do some experiments before
2582 2582 relying on it for regular work.
2583 2583
2584 2584 \layout Subsection
2585 2585
2586 2586
2587 2587 \begin_inset LatexCommand \label{sec:cmd-line-opts}
2588 2588
2589 2589 \end_inset
2590 2590
2591 2591 Regular Options
2592 2592 \layout Standard
2593 2593
2594 2594 After the above threading options have been given, regular options can follow
2595 2595 in any order.
2596 2596 All options can be abbreviated to their shortest non-ambiguous form and
2597 2597 are case-sensitive.
2598 2598 One or two dashes can be used.
2599 2599 Some options have an alternate short form, indicated after a
2600 2600 \family typewriter
2601 2601 |
2602 2602 \family default
2603 2603 .
2604 2604 \layout Standard
2605 2605
2606 2606 Most options can also be set from your ipythonrc configuration file.
2607 2607 See the provided example for more details on what the options do.
2608 2608 Options given at the command line override the values set in the ipythonrc
2609 2609 file.
2610 2610 \layout Standard
2611 2611
2612 2612 All options with a
2613 2613 \family typewriter
2614 2614 [no]
2615 2615 \family default
2616 2616 prepended can be specified in negated form (
2617 2617 \family typewriter
2618 2618 -nooption
2619 2619 \family default
2620 2620 instead of
2621 2621 \family typewriter
2622 2622 -option
2623 2623 \family default
2624 2624 ) to turn the feature off.
2625 2625 \layout List
2626 2626 \labelwidthstring 00.00.0000
2627 2627
2628 2628
2629 2629 \family typewriter
2630 2630 \series bold
2631 2631 -help
2632 2632 \family default
2633 2633 \series default
2634 2634 : print a help message and exit.
2635 2635 \layout List
2636 2636 \labelwidthstring 00.00.0000
2637 2637
2638 2638
2639 2639 \family typewriter
2640 2640 \series bold
2641 2641 -pylab:
2642 2642 \family default
2643 2643 \series default
2644 2644 this can
2645 2645 \emph on
2646 2646 only
2647 2647 \emph default
2648 2648 be given as the
2649 2649 \emph on
2650 2650 first
2651 2651 \emph default
2652 2652 option passed to IPython (it will have no effect in any other position).
2653 2653 It adds special support for the matplotlib library (
2654 2654 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
2655 2655
2656 2656 \end_inset
2657 2657
2658 2658 ), allowing interactive usage of any of its backends as defined in the user's
2659 2659
2660 2660 \family typewriter
2661 2661 .matplotlibrc
2662 2662 \family default
2663 2663 file.
2664 2664 It automatically activates GTK or WX threading for IPyhton if the choice
2665 2665 of matplotlib backend requires it.
2666 2666 It also modifies the
2667 2667 \family typewriter
2668 2668 %run
2669 2669 \family default
2670 2670 command to correctly execute (without blocking) any matplotlib-based script
2671 2671 which calls
2672 2672 \family typewriter
2673 2673 show()
2674 2674 \family default
2675 2675 at the end.
2676 2676 See Sec.\SpecialChar ~
2677 2677
2678 2678 \begin_inset LatexCommand \ref{sec:matplotlib-support}
2679 2679
2680 2680 \end_inset
2681 2681
2682 2682 for more details.
2683 2683 \layout List
2684 2684 \labelwidthstring 00.00.0000
2685 2685
2686 2686
2687 2687 \family typewriter
2688 2688 \series bold
2689 -[no]autocall:
2689 -autocall <val>:
2690 2690 \family default
2691 2691 \series default
2692 2692 Make IPython automatically call any callable object even if you didn't
2693 2693 type explicit parentheses.
2694 2694 For example, `str 43' becomes `str(43)' automatically.
2695 The value can be `0' to disable the feature, `1' for
2696 \emph on
2697 smart
2698 \emph default
2699 autocall, where it is not applied if there are no more arguments on the
2700 line, and `2' for
2701 \emph on
2702 full
2703 \emph default
2704 autocall, where all callable objects are automatically called (even if
2705 no arguments are present).
2706 The default is `1'.
2695 2707 \layout List
2696 2708 \labelwidthstring 00.00.0000
2697 2709
2698 2710
2699 2711 \family typewriter
2700 2712 \series bold
2701 2713 -[no]autoindent:
2702 2714 \family default
2703 2715 \series default
2704 2716 Turn automatic indentation on/off.
2705 2717 \layout List
2706 2718 \labelwidthstring 00.00.0000
2707 2719
2708 2720
2709 2721 \family typewriter
2710 2722 \series bold
2711 2723 -[no]automagic
2712 2724 \series default
2713 2725 :
2714 2726 \family default
2715 2727 make magic commands automatic (without needing their first character to
2716 2728 be
2717 2729 \family typewriter
2718 2730 %
2719 2731 \family default
2720 2732 ).
2721 2733 Type
2722 2734 \family typewriter
2723 2735 %magic
2724 2736 \family default
2725 2737 at the IPython prompt for more information.
2726 2738 \layout List
2727 2739 \labelwidthstring 00.00.0000
2728 2740
2729 2741
2730 2742 \family typewriter
2731 2743 \series bold
2732 2744 -[no]autoedit_syntax:
2733 2745 \family default
2734 2746 \series default
2735 2747 When a syntax error occurs after editing a file, automatically open the
2736 2748 file to the trouble causing line for convenient fixing.
2737 2749
2738 2750 \layout List
2739 2751 \labelwidthstring 00.00.0000
2740 2752
2741 2753
2742 2754 \family typewriter
2743 2755 \series bold
2744 2756 -[no]banner
2745 2757 \series default
2746 2758 :
2747 2759 \family default
2748 2760 Print the initial information banner (default on).
2749 2761 \layout List
2750 2762 \labelwidthstring 00.00.0000
2751 2763
2752 2764
2753 2765 \family typewriter
2754 2766 \series bold
2755 2767 -c\SpecialChar ~
2756 2768 <command>:
2757 2769 \family default
2758 2770 \series default
2759 2771 execute the given command string, and set sys.argv to
2760 2772 \family typewriter
2761 2773 ['c']
2762 2774 \family default
2763 2775 .
2764 2776 This is similar to the
2765 2777 \family typewriter
2766 2778 -c
2767 2779 \family default
2768 2780 option in the normal Python interpreter.
2769 2781
2770 2782 \layout List
2771 2783 \labelwidthstring 00.00.0000
2772 2784
2773 2785
2774 2786 \family typewriter
2775 2787 \series bold
2776 2788 -cache_size|cs\SpecialChar ~
2777 2789 <n>
2778 2790 \series default
2779 2791 :
2780 2792 \family default
2781 2793 size of the output cache (maximum number of entries to hold in memory).
2782 2794 The default is 1000, you can change it permanently in your config file.
2783 2795 Setting it to 0 completely disables the caching system, and the minimum
2784 2796 value accepted is 20 (if you provide a value less than 20, it is reset
2785 2797 to 0 and a warning is issued) This limit is defined because otherwise you'll
2786 2798 spend more time re-flushing a too small cache than working.
2787 2799 \layout List
2788 2800 \labelwidthstring 00.00.0000
2789 2801
2790 2802
2791 2803 \family typewriter
2792 2804 \series bold
2793 2805 -classic|cl
2794 2806 \series default
2795 2807 :
2796 2808 \family default
2797 2809 Gives IPython a similar feel to the classic Python prompt.
2798 2810 \layout List
2799 2811 \labelwidthstring 00.00.0000
2800 2812
2801 2813
2802 2814 \family typewriter
2803 2815 \series bold
2804 2816 -colors\SpecialChar ~
2805 2817 <scheme>:
2806 2818 \family default
2807 2819 \series default
2808 2820 Color scheme for prompts and exception reporting.
2809 2821 Currently implemented: NoColor, Linux and LightBG.
2810 2822 \layout List
2811 2823 \labelwidthstring 00.00.0000
2812 2824
2813 2825
2814 2826 \family typewriter
2815 2827 \series bold
2816 2828 -[no]color_info:
2817 2829 \family default
2818 2830 \series default
2819 2831 IPython can display information about objects via a set of functions, and
2820 2832 optionally can use colors for this, syntax highlighting source code and
2821 2833 various other elements.
2822 2834 However, because this information is passed through a pager (like 'less')
2823 2835 and many pagers get confused with color codes, this option is off by default.
2824 2836 You can test it and turn it on permanently in your ipythonrc file if it
2825 2837 works for you.
2826 2838 As a reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
2827 2839 that in RedHat 7.2 doesn't.
2828 2840 \layout List
2829 2841 \labelwidthstring 00.00.0000
2830 2842
2831 2843 \SpecialChar ~
2832 2844 Test it and turn it on permanently if it works with your system.
2833 2845 The magic function
2834 2846 \family typewriter
2835 2847 %color_info
2836 2848 \family default
2837 2849 allows you to toggle this interactively for testing.
2838 2850 \layout List
2839 2851 \labelwidthstring 00.00.0000
2840 2852
2841 2853
2842 2854 \family typewriter
2843 2855 \series bold
2844 2856 -[no]debug
2845 2857 \family default
2846 2858 \series default
2847 2859 : Show information about the loading process.
2848 2860 Very useful to pin down problems with your configuration files or to get
2849 2861 details about session restores.
2850 2862 \layout List
2851 2863 \labelwidthstring 00.00.0000
2852 2864
2853 2865
2854 2866 \family typewriter
2855 2867 \series bold
2856 2868 -[no]deep_reload
2857 2869 \series default
2858 2870 :
2859 2871 \family default
2860 2872 IPython can use the
2861 2873 \family typewriter
2862 2874 deep_reload
2863 2875 \family default
2864 2876 module which reloads changes in modules recursively (it replaces the
2865 2877 \family typewriter
2866 2878 reload()
2867 2879 \family default
2868 2880 function, so you don't need to change anything to use it).
2869 2881
2870 2882 \family typewriter
2871 2883 deep_reload()
2872 2884 \family default
2873 2885 forces a full reload of modules whose code may have changed, which the
2874 2886 default
2875 2887 \family typewriter
2876 2888 reload()
2877 2889 \family default
2878 2890 function does not.
2879 2891 \layout List
2880 2892 \labelwidthstring 00.00.0000
2881 2893
2882 2894 \SpecialChar ~
2883 2895 When deep_reload is off, IPython will use the normal
2884 2896 \family typewriter
2885 2897 reload()
2886 2898 \family default
2887 2899 , but deep_reload will still be available as
2888 2900 \family typewriter
2889 2901 dreload()
2890 2902 \family default
2891 2903 .
2892 2904 This feature is off by default [which means that you have both normal
2893 2905 \family typewriter
2894 2906 reload()
2895 2907 \family default
2896 2908 and
2897 2909 \family typewriter
2898 2910 dreload()
2899 2911 \family default
2900 2912 ].
2901 2913 \layout List
2902 2914 \labelwidthstring 00.00.0000
2903 2915
2904 2916
2905 2917 \family typewriter
2906 2918 \series bold
2907 2919 -editor\SpecialChar ~
2908 2920 <name>
2909 2921 \family default
2910 2922 \series default
2911 2923 : Which editor to use with the
2912 2924 \family typewriter
2913 2925 %edit
2914 2926 \family default
2915 2927 command.
2916 2928 By default, IPython will honor your
2917 2929 \family typewriter
2918 2930 EDITOR
2919 2931 \family default
2920 2932 environment variable (if not set, vi is the Unix default and notepad the
2921 2933 Windows one).
2922 2934 Since this editor is invoked on the fly by IPython and is meant for editing
2923 2935 small code snippets, you may want to use a small, lightweight editor here
2924 2936 (in case your default
2925 2937 \family typewriter
2926 2938 EDITOR
2927 2939 \family default
2928 2940 is something like Emacs).
2929 2941 \layout List
2930 2942 \labelwidthstring 00.00.0000
2931 2943
2932 2944
2933 2945 \family typewriter
2934 2946 \series bold
2935 2947 -ipythondir\SpecialChar ~
2936 2948 <name>
2937 2949 \series default
2938 2950 :
2939 2951 \family default
2940 2952 name of your IPython configuration directory
2941 2953 \family typewriter
2942 2954 IPYTHONDIR
2943 2955 \family default
2944 2956 .
2945 2957 This can also be specified through the environment variable
2946 2958 \family typewriter
2947 2959 IPYTHONDIR
2948 2960 \family default
2949 2961 .
2950 2962 \layout List
2951 2963 \labelwidthstring 00.00.0000
2952 2964
2953 2965
2954 2966 \family typewriter
2955 2967 \series bold
2956 2968 -log|l
2957 2969 \family default
2958 2970 \series default
2959 2971 : generate a log file of all input.
2960 2972 The file is named
2961 2973 \family typewriter
2962 2974 ipython_log.py
2963 2975 \family default
2964 2976 in your current directory (which prevents logs from multiple IPython sessions
2965 2977 from trampling each other).
2966 2978 You can use this to later restore a session by loading your logfile as
2967 2979 a file to be executed with option
2968 2980 \family typewriter
2969 2981 -logplay
2970 2982 \family default
2971 2983 (see below).
2972 2984 \layout List
2973 2985 \labelwidthstring 00.00.0000
2974 2986
2975 2987
2976 2988 \family typewriter
2977 2989 \series bold
2978 2990 -logfile|lf\SpecialChar ~
2979 2991 <name>
2980 2992 \series default
2981 2993 :
2982 2994 \family default
2983 2995 specify the name of your logfile.
2984 2996 \layout List
2985 2997 \labelwidthstring 00.00.0000
2986 2998
2987 2999
2988 3000 \family typewriter
2989 3001 \series bold
2990 3002 -logplay|lp\SpecialChar ~
2991 3003 <name>
2992 3004 \series default
2993 3005 :
2994 3006 \family default
2995 3007 you can replay a previous log.
2996 3008 For restoring a session as close as possible to the state you left it in,
2997 3009 use this option (don't just run the logfile).
2998 3010 With
2999 3011 \family typewriter
3000 3012 -logplay
3001 3013 \family default
3002 3014 , IPython will try to reconstruct the previous working environment in full,
3003 3015 not just execute the commands in the logfile.
3004 3016 \layout List
3005 3017 \labelwidthstring 00.00.0000
3006 3018
3007 3019 \SpecialChar ~
3008 3020 When a session is restored, logging is automatically turned on again with
3009 3021 the name of the logfile it was invoked with (it is read from the log header).
3010 3022 So once you've turned logging on for a session, you can quit IPython and
3011 3023 reload it as many times as you want and it will continue to log its history
3012 3024 and restore from the beginning every time.
3013 3025 \layout List
3014 3026 \labelwidthstring 00.00.0000
3015 3027
3016 3028 \SpecialChar ~
3017 3029 Caveats: there are limitations in this option.
3018 3030 The history variables
3019 3031 \family typewriter
3020 3032 _i*
3021 3033 \family default
3022 3034 ,
3023 3035 \family typewriter
3024 3036 _*
3025 3037 \family default
3026 3038 and
3027 3039 \family typewriter
3028 3040 _dh
3029 3041 \family default
3030 3042 don't get restored properly.
3031 3043 In the future we will try to implement full session saving by writing and
3032 3044 retrieving a 'snapshot' of the memory state of IPython.
3033 3045 But our first attempts failed because of inherent limitations of Python's
3034 3046 Pickle module, so this may have to wait.
3035 3047 \layout List
3036 3048 \labelwidthstring 00.00.0000
3037 3049
3038 3050
3039 3051 \family typewriter
3040 3052 \series bold
3041 3053 -[no]messages
3042 3054 \series default
3043 3055 :
3044 3056 \family default
3045 3057 Print messages which IPython collects about its startup process (default
3046 3058 on).
3047 3059 \layout List
3048 3060 \labelwidthstring 00.00.0000
3049 3061
3050 3062
3051 3063 \family typewriter
3052 3064 \series bold
3053 3065 -[no]pdb
3054 3066 \family default
3055 3067 \series default
3056 3068 : Automatically call the pdb debugger after every uncaught exception.
3057 3069 If you are used to debugging using pdb, this puts you automatically inside
3058 3070 of it after any call (either in IPython or in code called by it) which
3059 3071 triggers an exception which goes uncaught.
3060 3072 \layout List
3061 3073 \labelwidthstring 00.00.0000
3062 3074
3063 3075
3064 3076 \family typewriter
3065 3077 \series bold
3066 3078 -[no]pprint
3067 3079 \series default
3068 3080 :
3069 3081 \family default
3070 3082 ipython can optionally use the pprint (pretty printer) module for displaying
3071 3083 results.
3072 3084 pprint tends to give a nicer display of nested data structures.
3073 3085 If you like it, you can turn it on permanently in your config file (default
3074 3086 off).
3075 3087 \layout List
3076 3088 \labelwidthstring 00.00.0000
3077 3089
3078 3090
3079 3091 \family typewriter
3080 3092 \series bold
3081 3093 -profile|p <name>
3082 3094 \series default
3083 3095 :
3084 3096 \family default
3085 3097 assume that your config file is
3086 3098 \family typewriter
3087 3099 ipythonrc-<name>
3088 3100 \family default
3089 3101 (looks in current dir first, then in
3090 3102 \family typewriter
3091 3103 IPYTHONDIR
3092 3104 \family default
3093 3105 ).
3094 3106 This is a quick way to keep and load multiple config files for different
3095 3107 tasks, especially if you use the include option of config files.
3096 3108 You can keep a basic
3097 3109 \family typewriter
3098 3110 IPYTHONDIR/ipythonrc
3099 3111 \family default
3100 3112 file and then have other 'profiles' which include this one and load extra
3101 3113 things for particular tasks.
3102 3114 For example:
3103 3115 \layout List
3104 3116 \labelwidthstring 00.00.0000
3105 3117
3106 3118
3107 3119 \family typewriter
3108 3120 \SpecialChar ~
3109 3121
3110 3122 \family default
3111 3123 1.
3112 3124
3113 3125 \family typewriter
3114 3126 $HOME/.ipython/ipythonrc
3115 3127 \family default
3116 3128 : load basic things you always want.
3117 3129 \layout List
3118 3130 \labelwidthstring 00.00.0000
3119 3131
3120 3132
3121 3133 \family typewriter
3122 3134 \SpecialChar ~
3123 3135
3124 3136 \family default
3125 3137 2.
3126 3138
3127 3139 \family typewriter
3128 3140 $HOME/.ipython/ipythonrc-math
3129 3141 \family default
3130 3142 : load (1) and basic math-related modules.
3131 3143
3132 3144 \layout List
3133 3145 \labelwidthstring 00.00.0000
3134 3146
3135 3147
3136 3148 \family typewriter
3137 3149 \SpecialChar ~
3138 3150
3139 3151 \family default
3140 3152 3.
3141 3153
3142 3154 \family typewriter
3143 3155 $HOME/.ipython/ipythonrc-numeric
3144 3156 \family default
3145 3157 : load (1) and Numeric and plotting modules.
3146 3158 \layout List
3147 3159 \labelwidthstring 00.00.0000
3148 3160
3149 3161 \SpecialChar ~
3150 3162 Since it is possible to create an endless loop by having circular file
3151 3163 inclusions, IPython will stop if it reaches 15 recursive inclusions.
3152 3164 \layout List
3153 3165 \labelwidthstring 00.00.0000
3154 3166
3155 3167
3156 3168 \family typewriter
3157 3169 \series bold
3158 3170 -prompt_in1|pi1\SpecialChar ~
3159 3171 <string>:
3160 3172 \family default
3161 3173 \series default
3162 3174 Specify the string used for input prompts.
3163 3175 Note that if you are using numbered prompts, the number is represented
3164 3176 with a '
3165 3177 \backslash
3166 3178 #' in the string.
3167 3179 Don't forget to quote strings with spaces embedded in them.
3168 3180 Default: '
3169 3181 \family typewriter
3170 3182 In\SpecialChar ~
3171 3183 [
3172 3184 \backslash
3173 3185 #]:
3174 3186 \family default
3175 3187 '.
3176 3188 Sec.\SpecialChar ~
3177 3189
3178 3190 \begin_inset LatexCommand \ref{sec:prompts}
3179 3191
3180 3192 \end_inset
3181 3193
3182 3194 discusses in detail all the available escapes to customize your prompts.
3183 3195 \layout List
3184 3196 \labelwidthstring 00.00.0000
3185 3197
3186 3198
3187 3199 \family typewriter
3188 3200 \series bold
3189 3201 -prompt_in2|pi2\SpecialChar ~
3190 3202 <string>:
3191 3203 \family default
3192 3204 \series default
3193 3205 Similar to the previous option, but used for the continuation prompts.
3194 3206 The special sequence '
3195 3207 \family typewriter
3196 3208
3197 3209 \backslash
3198 3210 D
3199 3211 \family default
3200 3212 ' is similar to '
3201 3213 \family typewriter
3202 3214
3203 3215 \backslash
3204 3216 #
3205 3217 \family default
3206 3218 ', but with all digits replaced dots (so you can have your continuation
3207 3219 prompt aligned with your input prompt).
3208 3220 Default: '
3209 3221 \family typewriter
3210 3222 \SpecialChar ~
3211 3223 \SpecialChar ~
3212 3224 \SpecialChar ~
3213 3225 .
3214 3226 \backslash
3215 3227 D.:
3216 3228 \family default
3217 3229 ' (note three spaces at the start for alignment with '
3218 3230 \family typewriter
3219 3231 In\SpecialChar ~
3220 3232 [
3221 3233 \backslash
3222 3234 #]
3223 3235 \family default
3224 3236 ').
3225 3237 \layout List
3226 3238 \labelwidthstring 00.00.0000
3227 3239
3228 3240
3229 3241 \family typewriter
3230 3242 \series bold
3231 3243 -prompt_out|po\SpecialChar ~
3232 3244 <string>:
3233 3245 \family default
3234 3246 \series default
3235 3247 String used for output prompts, also uses numbers like
3236 3248 \family typewriter
3237 3249 prompt_in1
3238 3250 \family default
3239 3251 .
3240 3252 Default: '
3241 3253 \family typewriter
3242 3254 Out[
3243 3255 \backslash
3244 3256 #]:
3245 3257 \family default
3246 3258 '
3247 3259 \layout List
3248 3260 \labelwidthstring 00.00.0000
3249 3261
3250 3262
3251 3263 \family typewriter
3252 3264 \series bold
3253 3265 -quick
3254 3266 \family default
3255 3267 \series default
3256 3268 : start in bare bones mode (no config file loaded).
3257 3269 \layout List
3258 3270 \labelwidthstring 00.00.0000
3259 3271
3260 3272
3261 3273 \family typewriter
3262 3274 \series bold
3263 3275 -rcfile\SpecialChar ~
3264 3276 <name>
3265 3277 \series default
3266 3278 :
3267 3279 \family default
3268 3280 name of your IPython resource configuration file.
3269 3281 Normally IPython loads ipythonrc (from current directory) or
3270 3282 \family typewriter
3271 3283 IPYTHONDIR/ipythonrc
3272 3284 \family default
3273 3285 .
3274 3286 \layout List
3275 3287 \labelwidthstring 00.00.0000
3276 3288
3277 3289 \SpecialChar ~
3278 3290 If the loading of your config file fails, IPython starts with a bare bones
3279 3291 configuration (no modules loaded at all).
3280 3292 \layout List
3281 3293 \labelwidthstring 00.00.0000
3282 3294
3283 3295
3284 3296 \family typewriter
3285 3297 \series bold
3286 3298 -[no]readline
3287 3299 \family default
3288 3300 \series default
3289 3301 : use the readline library, which is needed to support name completion and
3290 3302 command history, among other things.
3291 3303 It is enabled by default, but may cause problems for users of X/Emacs in
3292 3304 Python comint or shell buffers.
3293 3305 \layout List
3294 3306 \labelwidthstring 00.00.0000
3295 3307
3296 3308 \SpecialChar ~
3297 3309 Note that X/Emacs 'eterm' buffers (opened with
3298 3310 \family typewriter
3299 3311 M-x\SpecialChar ~
3300 3312 term
3301 3313 \family default
3302 3314 ) support IPython's readline and syntax coloring fine, only 'emacs' (
3303 3315 \family typewriter
3304 3316 M-x\SpecialChar ~
3305 3317 shell
3306 3318 \family default
3307 3319 and
3308 3320 \family typewriter
3309 3321 C-c\SpecialChar ~
3310 3322 !
3311 3323 \family default
3312 3324 ) buffers do not.
3313 3325 \layout List
3314 3326 \labelwidthstring 00.00.0000
3315 3327
3316 3328
3317 3329 \family typewriter
3318 3330 \series bold
3319 3331 -screen_length|sl\SpecialChar ~
3320 3332 <n>
3321 3333 \series default
3322 3334 :
3323 3335 \family default
3324 3336 number of lines of your screen.
3325 3337 This is used to control printing of very long strings.
3326 3338 Strings longer than this number of lines will be sent through a pager instead
3327 3339 of directly printed.
3328 3340 \layout List
3329 3341 \labelwidthstring 00.00.0000
3330 3342
3331 3343 \SpecialChar ~
3332 3344 The default value for this is 0, which means IPython will auto-detect your
3333 3345 screen size every time it needs to print certain potentially long strings
3334 3346 (this doesn't change the behavior of the 'print' keyword, it's only triggered
3335 3347 internally).
3336 3348 If for some reason this isn't working well (it needs curses support), specify
3337 3349 it yourself.
3338 3350 Otherwise don't change the default.
3339 3351 \layout List
3340 3352 \labelwidthstring 00.00.0000
3341 3353
3342 3354
3343 3355 \family typewriter
3344 3356 \series bold
3345 3357 -separate_in|si\SpecialChar ~
3346 3358 <string>
3347 3359 \series default
3348 3360 :
3349 3361 \family default
3350 3362 separator before input prompts.
3351 3363 Default: '
3352 3364 \family typewriter
3353 3365
3354 3366 \backslash
3355 3367 n
3356 3368 \family default
3357 3369 '
3358 3370 \layout List
3359 3371 \labelwidthstring 00.00.0000
3360 3372
3361 3373
3362 3374 \family typewriter
3363 3375 \series bold
3364 3376 -separate_out|so\SpecialChar ~
3365 3377 <string>
3366 3378 \family default
3367 3379 \series default
3368 3380 : separator before output prompts.
3369 3381 Default: nothing.
3370 3382 \layout List
3371 3383 \labelwidthstring 00.00.0000
3372 3384
3373 3385
3374 3386 \family typewriter
3375 3387 \series bold
3376 3388 -separate_out2|so2\SpecialChar ~
3377 3389 <string>
3378 3390 \series default
3379 3391 :
3380 3392 \family default
3381 3393 separator after output prompts.
3382 3394 Default: nothing.
3383 3395 \layout List
3384 3396 \labelwidthstring 00.00.0000
3385 3397
3386 3398 \SpecialChar ~
3387 3399 For these three options, use the value 0 to specify no separator.
3388 3400 \layout List
3389 3401 \labelwidthstring 00.00.0000
3390 3402
3391 3403
3392 3404 \family typewriter
3393 3405 \series bold
3394 3406 -nosep
3395 3407 \series default
3396 3408 :
3397 3409 \family default
3398 3410 shorthand for
3399 3411 \family typewriter
3400 3412 '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'
3401 3413 \family default
3402 3414 .
3403 3415 Simply removes all input/output separators.
3404 3416 \layout List
3405 3417 \labelwidthstring 00.00.0000
3406 3418
3407 3419
3408 3420 \family typewriter
3409 3421 \series bold
3410 3422 -upgrade
3411 3423 \family default
3412 3424 \series default
3413 3425 : allows you to upgrade your
3414 3426 \family typewriter
3415 3427 IPYTHONDIR
3416 3428 \family default
3417 3429 configuration when you install a new version of IPython.
3418 3430 Since new versions may include new command line options or example files,
3419 3431 this copies updated ipythonrc-type files.
3420 3432 However, it backs up (with a
3421 3433 \family typewriter
3422 3434 .old
3423 3435 \family default
3424 3436 extension) all files which it overwrites so that you can merge back any
3425 3437 customizations you might have in your personal files.
3426 3438 \layout List
3427 3439 \labelwidthstring 00.00.0000
3428 3440
3429 3441
3430 3442 \family typewriter
3431 3443 \series bold
3432 3444 -Version
3433 3445 \series default
3434 3446 :
3435 3447 \family default
3436 3448 print version information and exit.
3437 3449 \layout List
3438 3450 \labelwidthstring 00.00.0000
3439 3451
3440 3452
3441 3453 \family typewriter
3442 3454 \series bold
3443 3455 -xmode <modename>
3444 3456 \series default
3445 3457 :
3446 3458 \family default
3447 3459 Mode for exception reporting.
3448 3460 \layout List
3449 3461 \labelwidthstring 00.00.0000
3450 3462
3451 3463 \SpecialChar ~
3452 3464 Valid modes: Plain, Context and Verbose.
3453 3465 \layout List
3454 3466 \labelwidthstring 00.00.0000
3455 3467
3456 3468 \SpecialChar ~
3457 3469 Plain: similar to python's normal traceback printing.
3458 3470 \layout List
3459 3471 \labelwidthstring 00.00.0000
3460 3472
3461 3473 \SpecialChar ~
3462 3474 Context: prints 5 lines of context source code around each line in the
3463 3475 traceback.
3464 3476 \layout List
3465 3477 \labelwidthstring 00.00.0000
3466 3478
3467 3479 \SpecialChar ~
3468 3480 Verbose: similar to Context, but additionally prints the variables currently
3469 3481 visible where the exception happened (shortening their strings if too long).
3470 3482 This can potentially be very slow, if you happen to have a huge data structure
3471 3483 whose string representation is complex to compute.
3472 3484 Your computer may appear to freeze for a while with cpu usage at 100%.
3473 3485 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
3474 3486 it more than once).
3475 3487 \layout Section
3476 3488
3477 3489 Interactive use
3478 3490 \layout Standard
3479 3491
3480 3492
3481 3493 \series bold
3482 3494 Warning
3483 3495 \series default
3484 3496 : IPython relies on the existence of a global variable called
3485 3497 \family typewriter
3486 3498 __IP
3487 3499 \family default
3488 3500 which controls the shell itself.
3489 3501 If you redefine
3490 3502 \family typewriter
3491 3503 __IP
3492 3504 \family default
3493 3505 to anything, bizarre behavior will quickly occur.
3494 3506 \layout Standard
3495 3507
3496 3508 Other than the above warning, IPython is meant to work as a drop-in replacement
3497 3509 for the standard interactive interpreter.
3498 3510 As such, any code which is valid python should execute normally under IPython
3499 3511 (cases where this is not true should be reported as bugs).
3500 3512 It does, however, offer many features which are not available at a standard
3501 3513 python prompt.
3502 3514 What follows is a list of these.
3503 3515 \layout Subsection
3504 3516
3505 3517 Caution for Windows users
3506 3518 \layout Standard
3507 3519
3508 3520 Windows, unfortunately, uses the `
3509 3521 \family typewriter
3510 3522
3511 3523 \backslash
3512 3524
3513 3525 \family default
3514 3526 ' character as a path separator.
3515 3527 This is a terrible choice, because `
3516 3528 \family typewriter
3517 3529
3518 3530 \backslash
3519 3531
3520 3532 \family default
3521 3533 ' also represents the escape character in most modern programming languages,
3522 3534 including Python.
3523 3535 For this reason, issuing many of the commands discussed below (especially
3524 3536 magics which affect the filesystem) with `
3525 3537 \family typewriter
3526 3538
3527 3539 \backslash
3528 3540
3529 3541 \family default
3530 3542 ' in them will cause strange errors.
3531 3543 \layout Standard
3532 3544
3533 3545 A partial solution is to use instead the `
3534 3546 \family typewriter
3535 3547 /
3536 3548 \family default
3537 3549 ' character as a path separator, which Windows recognizes in
3538 3550 \emph on
3539 3551 most
3540 3552 \emph default
3541 3553 situations.
3542 3554 However, in Windows commands `
3543 3555 \family typewriter
3544 3556 /
3545 3557 \family default
3546 3558 ' flags options, so you can not use it for the root directory.
3547 3559 This means that paths beginning at the root must be typed in a contrived
3548 3560 manner like:
3549 3561 \newline
3550 3562
3551 3563 \family typewriter
3552 3564 %copy
3553 3565 \backslash
3554 3566 opt/foo/bar.txt
3555 3567 \backslash
3556 3568 tmp
3557 3569 \layout Standard
3558 3570
3559 3571 There is no sensible thing IPython can do to truly work around this flaw
3560 3572 in Windows
3561 3573 \begin_inset Foot
3562 3574 collapsed true
3563 3575
3564 3576 \layout Standard
3565 3577
3566 3578 If anyone comes up with a
3567 3579 \emph on
3568 3580 clean
3569 3581 \emph default
3570 3582 solution which works consistently and does not negatively impact other
3571 3583 platforms at all, I'll gladly accept a patch.
3572 3584 \end_inset
3573 3585
3574 3586 .
3575 3587 \layout Subsection
3576 3588
3577 3589
3578 3590 \begin_inset LatexCommand \label{sec:magic}
3579 3591
3580 3592 \end_inset
3581 3593
3582 3594 Magic command system
3583 3595 \layout Standard
3584 3596
3585 3597 IPython will treat any line whose first character is a
3586 3598 \family typewriter
3587 3599 %
3588 3600 \family default
3589 3601 as a special call to a 'magic' function.
3590 3602 These allow you to control the behavior of IPython itself, plus a lot of
3591 3603 system-type features.
3592 3604 They are all prefixed with a
3593 3605 \family typewriter
3594 3606 %
3595 3607 \family default
3596 3608 character, but parameters are given without parentheses or quotes.
3597 3609 \layout Standard
3598 3610
3599 3611 Example: typing
3600 3612 \family typewriter
3601 3613 '%cd mydir'
3602 3614 \family default
3603 3615 (without the quotes) changes you working directory to
3604 3616 \family typewriter
3605 3617 'mydir'
3606 3618 \family default
3607 3619 , if it exists.
3608 3620 \layout Standard
3609 3621
3610 3622 If you have 'automagic' enabled (in your
3611 3623 \family typewriter
3612 3624 ipythonrc
3613 3625 \family default
3614 3626 file, via the command line option
3615 3627 \family typewriter
3616 3628 -automagic
3617 3629 \family default
3618 3630 or with the
3619 3631 \family typewriter
3620 3632 %automagic
3621 3633 \family default
3622 3634 function), you don't need to type in the
3623 3635 \family typewriter
3624 3636 %
3625 3637 \family default
3626 3638 explicitly.
3627 3639 IPython will scan its internal list of magic functions and call one if
3628 3640 it exists.
3629 3641 With automagic on you can then just type '
3630 3642 \family typewriter
3631 3643 cd mydir
3632 3644 \family default
3633 3645 ' to go to directory '
3634 3646 \family typewriter
3635 3647 mydir
3636 3648 \family default
3637 3649 '.
3638 3650 The automagic system has the lowest possible precedence in name searches,
3639 3651 so defining an identifier with the same name as an existing magic function
3640 3652 will shadow it for automagic use.
3641 3653 You can still access the shadowed magic function by explicitly using the
3642 3654
3643 3655 \family typewriter
3644 3656 %
3645 3657 \family default
3646 3658 character at the beginning of the line.
3647 3659 \layout Standard
3648 3660
3649 3661 An example (with automagic on) should clarify all this:
3650 3662 \layout LyX-Code
3651 3663
3652 3664 In [1]: cd ipython # %cd is called by automagic
3653 3665 \layout LyX-Code
3654 3666
3655 3667 /home/fperez/ipython
3656 3668 \layout LyX-Code
3657 3669
3658 3670 In [2]: cd=1 # now cd is just a variable
3659 3671 \layout LyX-Code
3660 3672
3661 3673 In [3]: cd ..
3662 3674 # and doesn't work as a function anymore
3663 3675 \layout LyX-Code
3664 3676
3665 3677 ------------------------------------------------------------
3666 3678 \layout LyX-Code
3667 3679
3668 3680 File "<console>", line 1
3669 3681 \layout LyX-Code
3670 3682
3671 3683 cd ..
3672 3684 \layout LyX-Code
3673 3685
3674 3686 ^
3675 3687 \layout LyX-Code
3676 3688
3677 3689 SyntaxError: invalid syntax
3678 3690 \layout LyX-Code
3679 3691
3680 3692 \layout LyX-Code
3681 3693
3682 3694 In [4]: %cd ..
3683 3695 # but %cd always works
3684 3696 \layout LyX-Code
3685 3697
3686 3698 /home/fperez
3687 3699 \layout LyX-Code
3688 3700
3689 3701 In [5]: del cd # if you remove the cd variable
3690 3702 \layout LyX-Code
3691 3703
3692 3704 In [6]: cd ipython # automagic can work again
3693 3705 \layout LyX-Code
3694 3706
3695 3707 /home/fperez/ipython
3696 3708 \layout Standard
3697 3709
3698 3710 You can define your own magic functions to extend the system.
3699 3711 The following is a snippet of code which shows how to do it.
3700 3712 It is provided as file
3701 3713 \family typewriter
3702 3714 example-magic.py
3703 3715 \family default
3704 3716 in the examples directory:
3705 3717 \layout Standard
3706 3718
3707 3719
3708 3720 \begin_inset ERT
3709 3721 status Open
3710 3722
3711 3723 \layout Standard
3712 3724
3713 3725 \backslash
3714 3726 codelist{examples/example-magic.py}
3715 3727 \end_inset
3716 3728
3717 3729
3718 3730 \layout Standard
3719 3731
3720 3732 You can also define your own aliased names for magic functions.
3721 3733 In your
3722 3734 \family typewriter
3723 3735 ipythonrc
3724 3736 \family default
3725 3737 file, placing a line like:
3726 3738 \layout Standard
3727 3739
3728 3740
3729 3741 \family typewriter
3730 3742 execute __IP.magic_cl = __IP.magic_clear
3731 3743 \layout Standard
3732 3744
3733 3745 will define
3734 3746 \family typewriter
3735 3747 %cl
3736 3748 \family default
3737 3749 as a new name for
3738 3750 \family typewriter
3739 3751 %clear
3740 3752 \family default
3741 3753 .
3742 3754 \layout Standard
3743 3755
3744 3756 Type
3745 3757 \family typewriter
3746 3758 %magic
3747 3759 \family default
3748 3760 for more information, including a list of all available magic functions
3749 3761 at any time and their docstrings.
3750 3762 You can also type
3751 3763 \family typewriter
3752 3764 %magic_function_name?
3753 3765 \family default
3754 3766 (see sec.
3755 3767
3756 3768 \begin_inset LatexCommand \ref{sec:dyn-object-info}
3757 3769
3758 3770 \end_inset
3759 3771
3760 3772 for information on the
3761 3773 \family typewriter
3762 3774 '?'
3763 3775 \family default
3764 3776 system) to get information about any particular magic function you are
3765 3777 interested in.
3766 3778 \layout Subsubsection
3767 3779
3768 3780 Magic commands
3769 3781 \layout Standard
3770 3782
3771 3783 The rest of this section is automatically generated for each release from
3772 3784 the docstrings in the IPython code.
3773 3785 Therefore the formatting is somewhat minimal, but this method has the advantage
3774 3786 of having information always in sync with the code.
3775 3787 \layout Standard
3776 3788
3777 3789 A list of all the magic commands available in IPython's
3778 3790 \emph on
3779 3791 default
3780 3792 \emph default
3781 3793 installation follows.
3782 3794 This is similar to what you'll see by simply typing
3783 3795 \family typewriter
3784 3796 %magic
3785 3797 \family default
3786 3798 at the prompt, but that will also give you information about magic commands
3787 3799 you may have added as part of your personal customizations.
3788 3800 \layout Standard
3789 3801
3790 3802
3791 3803 \begin_inset Include \input{magic.tex}
3792 3804 preview false
3793 3805
3794 3806 \end_inset
3795 3807
3796 3808
3797 3809 \layout Subsection
3798 3810
3799 3811 Access to the standard Python help
3800 3812 \layout Standard
3801 3813
3802 3814 As of Python 2.1, a help system is available with access to object docstrings
3803 3815 and the Python manuals.
3804 3816 Simply type
3805 3817 \family typewriter
3806 3818 'help'
3807 3819 \family default
3808 3820 (no quotes) to access it.
3809 3821 You can also type
3810 3822 \family typewriter
3811 3823 help(object)
3812 3824 \family default
3813 3825 to obtain information about a given object, and
3814 3826 \family typewriter
3815 3827 help('keyword')
3816 3828 \family default
3817 3829 for information on a keyword.
3818 3830 As noted in sec.
3819 3831
3820 3832 \begin_inset LatexCommand \ref{sec:help-access}
3821 3833
3822 3834 \end_inset
3823 3835
3824 3836 , you need to properly configure your environment variable
3825 3837 \family typewriter
3826 3838 PYTHONDOCS
3827 3839 \family default
3828 3840 for this feature to work correctly.
3829 3841 \layout Subsection
3830 3842
3831 3843
3832 3844 \begin_inset LatexCommand \label{sec:dyn-object-info}
3833 3845
3834 3846 \end_inset
3835 3847
3836 3848 Dynamic object information
3837 3849 \layout Standard
3838 3850
3839 3851 Typing
3840 3852 \family typewriter
3841 3853 ?word
3842 3854 \family default
3843 3855 or
3844 3856 \family typewriter
3845 3857 word?
3846 3858 \family default
3847 3859 prints detailed information about an object.
3848 3860 If certain strings in the object are too long (docstrings, code, etc.) they
3849 3861 get snipped in the center for brevity.
3850 3862 This system gives access variable types and values, full source code for
3851 3863 any object (if available), function prototypes and other useful information.
3852 3864 \layout Standard
3853 3865
3854 3866 Typing
3855 3867 \family typewriter
3856 3868 ??word
3857 3869 \family default
3858 3870 or
3859 3871 \family typewriter
3860 3872 word??
3861 3873 \family default
3862 3874 gives access to the full information without snipping long strings.
3863 3875 Long strings are sent to the screen through the
3864 3876 \family typewriter
3865 3877 less
3866 3878 \family default
3867 3879 pager if longer than the screen and printed otherwise.
3868 3880 On systems lacking the
3869 3881 \family typewriter
3870 3882 less
3871 3883 \family default
3872 3884 command, IPython uses a very basic internal pager.
3873 3885 \layout Standard
3874 3886
3875 3887 The following magic functions are particularly useful for gathering information
3876 3888 about your working environment.
3877 3889 You can get more details by typing
3878 3890 \family typewriter
3879 3891 %magic
3880 3892 \family default
3881 3893 or querying them individually (use
3882 3894 \family typewriter
3883 3895 %function_name?
3884 3896 \family default
3885 3897 with or without the
3886 3898 \family typewriter
3887 3899 %
3888 3900 \family default
3889 3901 ), this is just a summary:
3890 3902 \layout List
3891 3903 \labelwidthstring 00.00.0000
3892 3904
3893 3905
3894 3906 \family typewriter
3895 3907 \series bold
3896 3908 %pdoc\SpecialChar ~
3897 3909 <object>
3898 3910 \family default
3899 3911 \series default
3900 3912 : Print (or run through a pager if too long) the docstring for an object.
3901 3913 If the given object is a class, it will print both the class and the constructo
3902 3914 r docstrings.
3903 3915 \layout List
3904 3916 \labelwidthstring 00.00.0000
3905 3917
3906 3918
3907 3919 \family typewriter
3908 3920 \series bold
3909 3921 %pdef\SpecialChar ~
3910 3922 <object>
3911 3923 \family default
3912 3924 \series default
3913 3925 : Print the definition header for any callable object.
3914 3926 If the object is a class, print the constructor information.
3915 3927 \layout List
3916 3928 \labelwidthstring 00.00.0000
3917 3929
3918 3930
3919 3931 \family typewriter
3920 3932 \series bold
3921 3933 %psource\SpecialChar ~
3922 3934 <object>
3923 3935 \family default
3924 3936 \series default
3925 3937 : Print (or run through a pager if too long) the source code for an object.
3926 3938 \layout List
3927 3939 \labelwidthstring 00.00.0000
3928 3940
3929 3941
3930 3942 \family typewriter
3931 3943 \series bold
3932 3944 %pfile\SpecialChar ~
3933 3945 <object>
3934 3946 \family default
3935 3947 \series default
3936 3948 : Show the entire source file where an object was defined via a pager, opening
3937 3949 it at the line where the object definition begins.
3938 3950 \layout List
3939 3951 \labelwidthstring 00.00.0000
3940 3952
3941 3953
3942 3954 \family typewriter
3943 3955 \series bold
3944 3956 %who/%whos
3945 3957 \family default
3946 3958 \series default
3947 3959 : These functions give information about identifiers you have defined interactiv
3948 3960 ely (not things you loaded or defined in your configuration files).
3949 3961
3950 3962 \family typewriter
3951 3963 %who
3952 3964 \family default
3953 3965 just prints a list of identifiers and
3954 3966 \family typewriter
3955 3967 %whos
3956 3968 \family default
3957 3969 prints a table with some basic details about each identifier.
3958 3970 \layout Standard
3959 3971
3960 3972 Note that the dynamic object information functions (
3961 3973 \family typewriter
3962 3974 ?/??, %pdoc, %pfile, %pdef, %psource
3963 3975 \family default
3964 3976 ) give you access to documentation even on things which are not really defined
3965 3977 as separate identifiers.
3966 3978 Try for example typing
3967 3979 \family typewriter
3968 3980 {}.get?
3969 3981 \family default
3970 3982 or after doing
3971 3983 \family typewriter
3972 3984 import os
3973 3985 \family default
3974 3986 , type
3975 3987 \family typewriter
3976 3988 os.path.abspath??
3977 3989 \family default
3978 3990 .
3979 3991 \layout Subsection
3980 3992
3981 3993
3982 3994 \begin_inset LatexCommand \label{sec:readline}
3983 3995
3984 3996 \end_inset
3985 3997
3986 3998 Readline-based features
3987 3999 \layout Standard
3988 4000
3989 4001 These features require the GNU readline library, so they won't work if your
3990 4002 Python installation lacks readline support.
3991 4003 We will first describe the default behavior IPython uses, and then how
3992 4004 to change it to suit your preferences.
3993 4005 \layout Subsubsection
3994 4006
3995 4007 Command line completion
3996 4008 \layout Standard
3997 4009
3998 4010 At any time, hitting TAB will complete any available python commands or
3999 4011 variable names, and show you a list of the possible completions if there's
4000 4012 no unambiguous one.
4001 4013 It will also complete filenames in the current directory if no python names
4002 4014 match what you've typed so far.
4003 4015 \layout Subsubsection
4004 4016
4005 4017 Search command history
4006 4018 \layout Standard
4007 4019
4008 4020 IPython provides two ways for searching through previous input and thus
4009 4021 reduce the need for repetitive typing:
4010 4022 \layout Enumerate
4011 4023
4012 4024 Start typing, and then use
4013 4025 \family typewriter
4014 4026 Ctrl-p
4015 4027 \family default
4016 4028 (previous,up) and
4017 4029 \family typewriter
4018 4030 Ctrl-n
4019 4031 \family default
4020 4032 (next,down) to search through only the history items that match what you've
4021 4033 typed so far.
4022 4034 If you use
4023 4035 \family typewriter
4024 4036 Ctrl-p/Ctrl-n
4025 4037 \family default
4026 4038 at a blank prompt, they just behave like normal arrow keys.
4027 4039 \layout Enumerate
4028 4040
4029 4041 Hit
4030 4042 \family typewriter
4031 4043 Ctrl-r
4032 4044 \family default
4033 4045 : opens a search prompt.
4034 4046 Begin typing and the system searches your history for lines that contain
4035 4047 what you've typed so far, completing as much as it can.
4036 4048 \layout Subsubsection
4037 4049
4038 4050 Persistent command history across sessions
4039 4051 \layout Standard
4040 4052
4041 4053 IPython will save your input history when it leaves and reload it next time
4042 4054 you restart it.
4043 4055 By default, the history file is named
4044 4056 \family typewriter
4045 4057 $IPYTHONDIR/history
4046 4058 \family default
4047 4059 , but if you've loaded a named profile, '
4048 4060 \family typewriter
4049 4061 -PROFILE_NAME
4050 4062 \family default
4051 4063 ' is appended to the name.
4052 4064 This allows you to keep separate histories related to various tasks: commands
4053 4065 related to numerical work will not be clobbered by a system shell history,
4054 4066 for example.
4055 4067 \layout Subsubsection
4056 4068
4057 4069 Autoindent
4058 4070 \layout Standard
4059 4071
4060 4072 IPython can recognize lines ending in ':' and indent the next line, while
4061 4073 also un-indenting automatically after 'raise' or 'return'.
4062 4074
4063 4075 \layout Standard
4064 4076
4065 4077 This feature uses the readline library, so it will honor your
4066 4078 \family typewriter
4067 4079 ~/.inputrc
4068 4080 \family default
4069 4081 configuration (or whatever file your
4070 4082 \family typewriter
4071 4083 INPUTRC
4072 4084 \family default
4073 4085 variable points to).
4074 4086 Adding the following lines to your
4075 4087 \family typewriter
4076 4088 .inputrc
4077 4089 \family default
4078 4090 file can make indenting/unindenting more convenient (
4079 4091 \family typewriter
4080 4092 M-i
4081 4093 \family default
4082 4094 indents,
4083 4095 \family typewriter
4084 4096 M-u
4085 4097 \family default
4086 4098 unindents):
4087 4099 \layout Standard
4088 4100
4089 4101
4090 4102 \family typewriter
4091 4103 $if Python
4092 4104 \newline
4093 4105 "
4094 4106 \backslash
4095 4107 M-i": "\SpecialChar ~
4096 4108 \SpecialChar ~
4097 4109 \SpecialChar ~
4098 4110 \SpecialChar ~
4099 4111 "
4100 4112 \newline
4101 4113 "
4102 4114 \backslash
4103 4115 M-u": "
4104 4116 \backslash
4105 4117 d
4106 4118 \backslash
4107 4119 d
4108 4120 \backslash
4109 4121 d
4110 4122 \backslash
4111 4123 d"
4112 4124 \newline
4113 4125 $endif
4114 4126 \layout Standard
4115 4127
4116 4128 Note that there are 4 spaces between the quote marks after
4117 4129 \family typewriter
4118 4130 "M-i"
4119 4131 \family default
4120 4132 above.
4121 4133 \layout Standard
4122 4134
4123 4135
4124 4136 \series bold
4125 4137 Warning:
4126 4138 \series default
4127 4139 this feature is ON by default, but it can cause problems with the pasting
4128 4140 of multi-line indented code (the pasted code gets re-indented on each line).
4129 4141 A magic function
4130 4142 \family typewriter
4131 4143 %autoindent
4132 4144 \family default
4133 4145 allows you to toggle it on/off at runtime.
4134 4146 You can also disable it permanently on in your
4135 4147 \family typewriter
4136 4148 ipythonrc
4137 4149 \family default
4138 4150 file (set
4139 4151 \family typewriter
4140 4152 autoindent 0
4141 4153 \family default
4142 4154 ).
4143 4155 \layout Subsubsection
4144 4156
4145 4157 Customizing readline behavior
4146 4158 \layout Standard
4147 4159
4148 4160 All these features are based on the GNU readline library, which has an extremely
4149 4161 customizable interface.
4150 4162 Normally, readline is configured via a file which defines the behavior
4151 4163 of the library; the details of the syntax for this can be found in the
4152 4164 readline documentation available with your system or on the Internet.
4153 4165 IPython doesn't read this file (if it exists) directly, but it does support
4154 4166 passing to readline valid options via a simple interface.
4155 4167 In brief, you can customize readline by setting the following options in
4156 4168 your
4157 4169 \family typewriter
4158 4170 ipythonrc
4159 4171 \family default
4160 4172 configuration file (note that these options can
4161 4173 \emph on
4162 4174 not
4163 4175 \emph default
4164 4176 be specified at the command line):
4165 4177 \layout List
4166 4178 \labelwidthstring 00.00.0000
4167 4179
4168 4180
4169 4181 \family typewriter
4170 4182 \series bold
4171 4183 readline_parse_and_bind:
4172 4184 \family default
4173 4185 \series default
4174 4186 this option can appear as many times as you want, each time defining a
4175 4187 string to be executed via a
4176 4188 \family typewriter
4177 4189 readline.parse_and_bind()
4178 4190 \family default
4179 4191 command.
4180 4192 The syntax for valid commands of this kind can be found by reading the
4181 4193 documentation for the GNU readline library, as these commands are of the
4182 4194 kind which readline accepts in its configuration file.
4183 4195 \layout List
4184 4196 \labelwidthstring 00.00.0000
4185 4197
4186 4198
4187 4199 \family typewriter
4188 4200 \series bold
4189 4201 readline_remove_delims:
4190 4202 \family default
4191 4203 \series default
4192 4204 a string of characters to be removed from the default word-delimiters list
4193 4205 used by readline, so that completions may be performed on strings which
4194 4206 contain them.
4195 4207 Do not change the default value unless you know what you're doing.
4196 4208 \layout List
4197 4209 \labelwidthstring 00.00.0000
4198 4210
4199 4211
4200 4212 \family typewriter
4201 4213 \series bold
4202 4214 readline_omit__names
4203 4215 \family default
4204 4216 \series default
4205 4217 : when tab-completion is enabled, hitting
4206 4218 \family typewriter
4207 4219 <tab>
4208 4220 \family default
4209 4221 after a '
4210 4222 \family typewriter
4211 4223 .
4212 4224 \family default
4213 4225 ' in a name will complete all attributes of an object, including all the
4214 4226 special methods whose names include double underscores (like
4215 4227 \family typewriter
4216 4228 __getitem__
4217 4229 \family default
4218 4230 or
4219 4231 \family typewriter
4220 4232 __class__
4221 4233 \family default
4222 4234 ).
4223 4235 If you'd rather not see these names by default, you can set this option
4224 4236 to 1.
4225 4237 Note that even when this option is set, you can still see those names by
4226 4238 explicitly typing a
4227 4239 \family typewriter
4228 4240 _
4229 4241 \family default
4230 4242 after the period and hitting
4231 4243 \family typewriter
4232 4244 <tab>
4233 4245 \family default
4234 4246 : '
4235 4247 \family typewriter
4236 4248 name._<tab>
4237 4249 \family default
4238 4250 ' will always complete attribute names starting with '
4239 4251 \family typewriter
4240 4252 _
4241 4253 \family default
4242 4254 '.
4243 4255 \layout List
4244 4256 \labelwidthstring 00.00.0000
4245 4257
4246 4258 \SpecialChar ~
4247 4259 This option is off by default so that new users see all attributes of any
4248 4260 objects they are dealing with.
4249 4261 \layout Standard
4250 4262
4251 4263 You will find the default values along with a corresponding detailed explanation
4252 4264 in your
4253 4265 \family typewriter
4254 4266 ipythonrc
4255 4267 \family default
4256 4268 file.
4257 4269 \layout Subsection
4258 4270
4259 4271 Session logging and restoring
4260 4272 \layout Standard
4261 4273
4262 4274 You can log all input from a session either by starting IPython with the
4263 4275 command line switches
4264 4276 \family typewriter
4265 4277 -log
4266 4278 \family default
4267 4279 or
4268 4280 \family typewriter
4269 4281 -logfile
4270 4282 \family default
4271 4283 (see sec.
4272 4284
4273 4285 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
4274 4286
4275 4287 \end_inset
4276 4288
4277 4289 )or by activating the logging at any moment with the magic function
4278 4290 \family typewriter
4279 4291 %logstart
4280 4292 \family default
4281 4293 .
4282 4294
4283 4295 \layout Standard
4284 4296
4285 4297 Log files can later be reloaded with the
4286 4298 \family typewriter
4287 4299 -logplay
4288 4300 \family default
4289 4301 option and IPython will attempt to 'replay' the log by executing all the
4290 4302 lines in it, thus restoring the state of a previous session.
4291 4303 This feature is not quite perfect, but can still be useful in many cases.
4292 4304 \layout Standard
4293 4305
4294 4306 The log files can also be used as a way to have a permanent record of any
4295 4307 code you wrote while experimenting.
4296 4308 Log files are regular text files which you can later open in your favorite
4297 4309 text editor to extract code or to 'clean them up' before using them to
4298 4310 replay a session.
4299 4311 \layout Standard
4300 4312
4301 4313 The
4302 4314 \family typewriter
4303 4315 %logstart
4304 4316 \family default
4305 4317 function for activating logging in mid-session is used as follows:
4306 4318 \layout Standard
4307 4319
4308 4320
4309 4321 \family typewriter
4310 4322 %logstart [log_name [log_mode]]
4311 4323 \layout Standard
4312 4324
4313 4325 If no name is given, it defaults to a file named
4314 4326 \family typewriter
4315 4327 'log'
4316 4328 \family default
4317 4329 in your IPYTHONDIR directory, in
4318 4330 \family typewriter
4319 4331 'rotate'
4320 4332 \family default
4321 4333 mode (see below).
4322 4334 \layout Standard
4323 4335
4324 4336 '
4325 4337 \family typewriter
4326 4338 %logstart name
4327 4339 \family default
4328 4340 ' saves to file
4329 4341 \family typewriter
4330 4342 'name'
4331 4343 \family default
4332 4344 in
4333 4345 \family typewriter
4334 4346 'backup'
4335 4347 \family default
4336 4348 mode.
4337 4349 It saves your history up to that point and then continues logging.
4338 4350 \layout Standard
4339 4351
4340 4352
4341 4353 \family typewriter
4342 4354 %logstart
4343 4355 \family default
4344 4356 takes a second optional parameter: logging mode.
4345 4357 This can be one of (note that the modes are given unquoted):
4346 4358 \layout List
4347 4359 \labelwidthstring 00.00.0000
4348 4360
4349 4361
4350 4362 \family typewriter
4351 4363 over
4352 4364 \family default
4353 4365 : overwrite existing
4354 4366 \family typewriter
4355 4367 log_name
4356 4368 \family default
4357 4369 .
4358 4370 \layout List
4359 4371 \labelwidthstring 00.00.0000
4360 4372
4361 4373
4362 4374 \family typewriter
4363 4375 backup
4364 4376 \family default
4365 4377 : rename (if exists) to
4366 4378 \family typewriter
4367 4379 log_name~
4368 4380 \family default
4369 4381 and start
4370 4382 \family typewriter
4371 4383 log_name
4372 4384 \family default
4373 4385 .
4374 4386 \layout List
4375 4387 \labelwidthstring 00.00.0000
4376 4388
4377 4389
4378 4390 \family typewriter
4379 4391 append
4380 4392 \family default
4381 4393 : well, that says it.
4382 4394 \layout List
4383 4395 \labelwidthstring 00.00.0000
4384 4396
4385 4397
4386 4398 \family typewriter
4387 4399 rotate
4388 4400 \family default
4389 4401 : create rotating logs
4390 4402 \family typewriter
4391 4403 log_name
4392 4404 \family default
4393 4405 .
4394 4406 \family typewriter
4395 4407 1~
4396 4408 \family default
4397 4409 ,
4398 4410 \family typewriter
4399 4411 log_name.2~
4400 4412 \family default
4401 4413 , etc.
4402 4414 \layout Standard
4403 4415
4404 4416 The
4405 4417 \family typewriter
4406 4418 %logoff
4407 4419 \family default
4408 4420 and
4409 4421 \family typewriter
4410 4422 %logon
4411 4423 \family default
4412 4424 functions allow you to temporarily stop and resume logging to a file which
4413 4425 had previously been started with
4414 4426 \family typewriter
4415 4427 %logstart
4416 4428 \family default
4417 4429 .
4418 4430 They will fail (with an explanation) if you try to use them before logging
4419 4431 has been started.
4420 4432 \layout Subsection
4421 4433
4422 4434
4423 4435 \begin_inset LatexCommand \label{sub:System-shell-access}
4424 4436
4425 4437 \end_inset
4426 4438
4427 4439 System shell access
4428 4440 \layout Standard
4429 4441
4430 4442 Any input line beginning with a
4431 4443 \family typewriter
4432 4444 !
4433 4445 \family default
4434 4446 character is passed verbatim (minus the
4435 4447 \family typewriter
4436 4448 !
4437 4449 \family default
4438 4450 , of course) to the underlying operating system.
4439 4451 For example, typing
4440 4452 \family typewriter
4441 4453 !ls
4442 4454 \family default
4443 4455 will run
4444 4456 \family typewriter
4445 4457 'ls'
4446 4458 \family default
4447 4459 in the current directory.
4448 4460 \layout Subsubsection
4449 4461
4450 4462 Manual capture of command output
4451 4463 \layout Standard
4452 4464
4453 4465 If the input line begins with
4454 4466 \emph on
4455 4467 two
4456 4468 \emph default
4457 4469 exclamation marks,
4458 4470 \family typewriter
4459 4471 !!
4460 4472 \family default
4461 4473 , the command is executed but its output is captured and returned as a python
4462 4474 list, split on newlines.
4463 4475 Any output sent by the subprocess to standard error is printed separately,
4464 4476 so that the resulting list only captures standard output.
4465 4477 The
4466 4478 \family typewriter
4467 4479 !!
4468 4480 \family default
4469 4481 syntax is a shorthand for the
4470 4482 \family typewriter
4471 4483 %sx
4472 4484 \family default
4473 4485 magic command.
4474 4486 \layout Standard
4475 4487
4476 4488 Finally, the
4477 4489 \family typewriter
4478 4490 %sc
4479 4491 \family default
4480 4492 magic (short for `shell capture') is similar to
4481 4493 \family typewriter
4482 4494 %sx
4483 4495 \family default
4484 4496 , but allowing more fine-grained control of the capture details, and storing
4485 4497 the result directly into a named variable.
4486 4498 \layout Standard
4487 4499
4488 4500 See Sec.\SpecialChar ~
4489 4501
4490 4502 \begin_inset LatexCommand \ref{sec:magic}
4491 4503
4492 4504 \end_inset
4493 4505
4494 4506 for details on the magics
4495 4507 \family typewriter
4496 4508 %sc
4497 4509 \family default
4498 4510 and
4499 4511 \family typewriter
4500 4512 %sx
4501 4513 \family default
4502 4514 , or use IPython's own help (
4503 4515 \family typewriter
4504 4516 sc?
4505 4517 \family default
4506 4518 and
4507 4519 \family typewriter
4508 4520 sx?
4509 4521 \family default
4510 4522 ) for further details.
4511 4523 \layout Standard
4512 4524
4513 4525 IPython also allows you to expand the value of python variables when making
4514 4526 system calls.
4515 4527 Any python variable or expression which you prepend with
4516 4528 \family typewriter
4517 4529 $
4518 4530 \family default
4519 4531 will get expanded before the system call is made.
4520 4532
4521 4533 \layout Standard
4522 4534
4523 4535
4524 4536 \family typewriter
4525 4537 In [1]: pyvar='Hello world'
4526 4538 \newline
4527 4539 In [2]: !echo "A python variable: $pyvar"
4528 4540 \newline
4529 4541 A python variable: Hello world
4530 4542 \layout Standard
4531 4543
4532 4544 If you want the shell to actually see a literal
4533 4545 \family typewriter
4534 4546 $
4535 4547 \family default
4536 4548 , you need to type it twice:
4537 4549 \layout Standard
4538 4550
4539 4551
4540 4552 \family typewriter
4541 4553 In [3]: !echo "A system variable: $$HOME"
4542 4554 \newline
4543 4555 A system variable: /home/fperez
4544 4556 \layout Standard
4545 4557
4546 4558 You can pass arbitrary expressions, though you'll need to delimit them with
4547 4559
4548 4560 \family typewriter
4549 4561 {}
4550 4562 \family default
4551 4563 if there is ambiguity as to the extent of the expression:
4552 4564 \layout Standard
4553 4565
4554 4566
4555 4567 \family typewriter
4556 4568 In [5]: x=10
4557 4569 \newline
4558 4570 In [6]: y=20
4559 4571 \newline
4560 4572 In [13]: !echo $x+y
4561 4573 \newline
4562 4574 10+y
4563 4575 \newline
4564 4576 In [7]: !echo ${x+y}
4565 4577 \newline
4566 4578 30
4567 4579 \layout Standard
4568 4580
4569 4581 Even object attributes can be expanded:
4570 4582 \layout Standard
4571 4583
4572 4584
4573 4585 \family typewriter
4574 4586 In [12]: !echo $sys.argv
4575 4587 \newline
4576 4588 [/home/fperez/usr/bin/ipython]
4577 4589 \layout Subsection
4578 4590
4579 4591 System command aliases
4580 4592 \layout Standard
4581 4593
4582 4594 The
4583 4595 \family typewriter
4584 4596 %alias
4585 4597 \family default
4586 4598 magic function and the
4587 4599 \family typewriter
4588 4600 alias
4589 4601 \family default
4590 4602 option in the
4591 4603 \family typewriter
4592 4604 ipythonrc
4593 4605 \family default
4594 4606 configuration file allow you to define magic functions which are in fact
4595 4607 system shell commands.
4596 4608 These aliases can have parameters.
4597 4609
4598 4610 \layout Standard
4599 4611
4600 4612 '
4601 4613 \family typewriter
4602 4614 %alias alias_name cmd
4603 4615 \family default
4604 4616 ' defines '
4605 4617 \family typewriter
4606 4618 alias_name
4607 4619 \family default
4608 4620 ' as an alias for '
4609 4621 \family typewriter
4610 4622 cmd
4611 4623 \family default
4612 4624 '
4613 4625 \layout Standard
4614 4626
4615 4627 Then, typing '
4616 4628 \family typewriter
4617 4629 %alias_name params
4618 4630 \family default
4619 4631 ' will execute the system command '
4620 4632 \family typewriter
4621 4633 cmd params
4622 4634 \family default
4623 4635 ' (from your underlying operating system).
4624 4636
4625 4637 \layout Standard
4626 4638
4627 4639 You can also define aliases with parameters using
4628 4640 \family typewriter
4629 4641 %s
4630 4642 \family default
4631 4643 specifiers (one per parameter).
4632 4644 The following example defines the
4633 4645 \family typewriter
4634 4646 %parts
4635 4647 \family default
4636 4648 function as an alias to the command '
4637 4649 \family typewriter
4638 4650 echo first %s second %s
4639 4651 \family default
4640 4652 ' where each
4641 4653 \family typewriter
4642 4654 %s
4643 4655 \family default
4644 4656 will be replaced by a positional parameter to the call to
4645 4657 \family typewriter
4646 4658 %parts:
4647 4659 \layout Standard
4648 4660
4649 4661
4650 4662 \family typewriter
4651 4663 In [1]: alias parts echo first %s second %s
4652 4664 \newline
4653 4665 In [2]: %parts A B
4654 4666 \newline
4655 4667 first A second B
4656 4668 \newline
4657 4669 In [3]: %parts A
4658 4670 \newline
4659 4671 Incorrect number of arguments: 2 expected.
4660 4672
4661 4673 \newline
4662 4674 parts is an alias to: 'echo first %s second %s'
4663 4675 \layout Standard
4664 4676
4665 4677 If called with no parameters,
4666 4678 \family typewriter
4667 4679 %alias
4668 4680 \family default
4669 4681 prints the table of currently defined aliases.
4670 4682 \layout Standard
4671 4683
4672 4684 The
4673 4685 \family typewriter
4674 4686 %rehash/rehashx
4675 4687 \family default
4676 4688 magics allow you to load your entire
4677 4689 \family typewriter
4678 4690 $PATH
4679 4691 \family default
4680 4692 as ipython aliases.
4681 4693 See their respective docstrings (or sec.\SpecialChar ~
4682 4694
4683 4695 \begin_inset LatexCommand \ref{sec:magic}
4684 4696
4685 4697 \end_inset
4686 4698
4687 4699 for further details).
4688 4700 \layout Subsection
4689 4701
4690 4702
4691 4703 \begin_inset LatexCommand \label{sec:dreload}
4692 4704
4693 4705 \end_inset
4694 4706
4695 4707 Recursive reload
4696 4708 \layout Standard
4697 4709
4698 4710 The
4699 4711 \family typewriter
4700 4712 %dreload
4701 4713 \family default
4702 4714 command does a recursive reload of a module: changes made to the module
4703 4715 since you imported will actually be available without having to exit.
4704 4716 \layout Subsection
4705 4717
4706 4718 Verbose and colored exception traceback printouts
4707 4719 \layout Standard
4708 4720
4709 4721 IPython provides the option to see very detailed exception tracebacks, which
4710 4722 can be especially useful when debugging large programs.
4711 4723 You can run any Python file with the
4712 4724 \family typewriter
4713 4725 %run
4714 4726 \family default
4715 4727 function to benefit from these detailed tracebacks.
4716 4728 Furthermore, both normal and verbose tracebacks can be colored (if your
4717 4729 terminal supports it) which makes them much easier to parse visually.
4718 4730 \layout Standard
4719 4731
4720 4732 See the magic
4721 4733 \family typewriter
4722 4734 xmode
4723 4735 \family default
4724 4736 and
4725 4737 \family typewriter
4726 4738 colors
4727 4739 \family default
4728 4740 functions for details (just type
4729 4741 \family typewriter
4730 4742 %magic
4731 4743 \family default
4732 4744 ).
4733 4745 \layout Standard
4734 4746
4735 4747 These features are basically a terminal version of Ka-Ping Yee's
4736 4748 \family typewriter
4737 4749 cgitb
4738 4750 \family default
4739 4751 module, now part of the standard Python library.
4740 4752 \layout Subsection
4741 4753
4742 4754
4743 4755 \begin_inset LatexCommand \label{sec:cache_input}
4744 4756
4745 4757 \end_inset
4746 4758
4747 4759 Input caching system
4748 4760 \layout Standard
4749 4761
4750 4762 IPython offers numbered prompts (In/Out) with input and output caching.
4751 4763 All input is saved and can be retrieved as variables (besides the usual
4752 4764 arrow key recall).
4753 4765 \layout Standard
4754 4766
4755 4767 The following GLOBAL variables always exist (so don't overwrite them!):
4756 4768
4757 4769 \family typewriter
4758 4770 _i
4759 4771 \family default
4760 4772 : stores previous input.
4761 4773
4762 4774 \family typewriter
4763 4775 _ii
4764 4776 \family default
4765 4777 : next previous.
4766 4778
4767 4779 \family typewriter
4768 4780 _iii
4769 4781 \family default
4770 4782 : next-next previous.
4771 4783
4772 4784 \family typewriter
4773 4785 _ih
4774 4786 \family default
4775 4787 : a list of all input
4776 4788 \family typewriter
4777 4789 _ih[n]
4778 4790 \family default
4779 4791 is the input from line
4780 4792 \family typewriter
4781 4793 n
4782 4794 \family default
4783 4795 and this list is aliased to the global variable
4784 4796 \family typewriter
4785 4797 In
4786 4798 \family default
4787 4799 .
4788 4800 If you overwrite
4789 4801 \family typewriter
4790 4802 In
4791 4803 \family default
4792 4804 with a variable of your own, you can remake the assignment to the internal
4793 4805 list with a simple
4794 4806 \family typewriter
4795 4807 'In=_ih'
4796 4808 \family default
4797 4809 .
4798 4810 \layout Standard
4799 4811
4800 4812 Additionally, global variables named
4801 4813 \family typewriter
4802 4814 _i<n>
4803 4815 \family default
4804 4816 are dynamically created (
4805 4817 \family typewriter
4806 4818 <n>
4807 4819 \family default
4808 4820 being the prompt counter), such that
4809 4821 \newline
4810 4822
4811 4823 \family typewriter
4812 4824 _i<n> == _ih[<n>] == In[<n>].
4813 4825 \layout Standard
4814 4826
4815 4827 For example, what you typed at prompt 14 is available as
4816 4828 \family typewriter
4817 4829 _i14,
4818 4830 \family default
4819 4831
4820 4832 \family typewriter
4821 4833 _ih[14]
4822 4834 \family default
4823 4835 and
4824 4836 \family typewriter
4825 4837 In[14]
4826 4838 \family default
4827 4839 .
4828 4840 \layout Standard
4829 4841
4830 4842 This allows you to easily cut and paste multi line interactive prompts by
4831 4843 printing them out: they print like a clean string, without prompt characters.
4832 4844 You can also manipulate them like regular variables (they are strings),
4833 4845 modify or exec them (typing
4834 4846 \family typewriter
4835 4847 'exec _i9'
4836 4848 \family default
4837 4849 will re-execute the contents of input prompt 9, '
4838 4850 \family typewriter
4839 4851 exec In[9:14]+In[18]
4840 4852 \family default
4841 4853 ' will re-execute lines 9 through 13 and line 18).
4842 4854 \layout Standard
4843 4855
4844 4856 You can also re-execute multiple lines of input easily by using the magic
4845 4857
4846 4858 \family typewriter
4847 4859 %macro
4848 4860 \family default
4849 4861 function (which automates the process and allows re-execution without having
4850 4862 to type '
4851 4863 \family typewriter
4852 4864 exec
4853 4865 \family default
4854 4866 ' every time).
4855 4867 The macro system also allows you to re-execute previous lines which include
4856 4868 magic function calls (which require special processing).
4857 4869 Type
4858 4870 \family typewriter
4859 4871 %macro?
4860 4872 \family default
4861 4873 or see sec.
4862 4874
4863 4875 \begin_inset LatexCommand \ref{sec:magic}
4864 4876
4865 4877 \end_inset
4866 4878
4867 4879 for more details on the macro system.
4868 4880 \layout Standard
4869 4881
4870 4882 A history function
4871 4883 \family typewriter
4872 4884 %hist
4873 4885 \family default
4874 4886 allows you to see any part of your input history by printing a range of
4875 4887 the
4876 4888 \family typewriter
4877 4889 _i
4878 4890 \family default
4879 4891 variables.
4880 4892 \layout Subsection
4881 4893
4882 4894
4883 4895 \begin_inset LatexCommand \label{sec:cache_output}
4884 4896
4885 4897 \end_inset
4886 4898
4887 4899 Output caching system
4888 4900 \layout Standard
4889 4901
4890 4902 For output that is returned from actions, a system similar to the input
4891 4903 cache exists but using
4892 4904 \family typewriter
4893 4905 _
4894 4906 \family default
4895 4907 instead of
4896 4908 \family typewriter
4897 4909 _i
4898 4910 \family default
4899 4911 .
4900 4912 Only actions that produce a result (NOT assignments, for example) are cached.
4901 4913 If you are familiar with Mathematica, IPython's
4902 4914 \family typewriter
4903 4915 _
4904 4916 \family default
4905 4917 variables behave exactly like Mathematica's
4906 4918 \family typewriter
4907 4919 %
4908 4920 \family default
4909 4921 variables.
4910 4922 \layout Standard
4911 4923
4912 4924 The following GLOBAL variables always exist (so don't overwrite them!):
4913 4925
4914 4926 \layout List
4915 4927 \labelwidthstring 00.00.0000
4916 4928
4917 4929
4918 4930 \family typewriter
4919 4931 \series bold
4920 4932 _
4921 4933 \family default
4922 4934 \series default
4923 4935 (a
4924 4936 \emph on
4925 4937 single
4926 4938 \emph default
4927 4939 underscore) : stores previous output, like Python's default interpreter.
4928 4940 \layout List
4929 4941 \labelwidthstring 00.00.0000
4930 4942
4931 4943
4932 4944 \family typewriter
4933 4945 \series bold
4934 4946 __
4935 4947 \family default
4936 4948 \series default
4937 4949 (two underscores): next previous.
4938 4950 \layout List
4939 4951 \labelwidthstring 00.00.0000
4940 4952
4941 4953
4942 4954 \family typewriter
4943 4955 \series bold
4944 4956 ___
4945 4957 \family default
4946 4958 \series default
4947 4959 (three underscores): next-next previous.
4948 4960 \layout Standard
4949 4961
4950 4962 Additionally, global variables named
4951 4963 \family typewriter
4952 4964 _<n>
4953 4965 \family default
4954 4966 are dynamically created (
4955 4967 \family typewriter
4956 4968 <n>
4957 4969 \family default
4958 4970 being the prompt counter), such that the result of output
4959 4971 \family typewriter
4960 4972 <n>
4961 4973 \family default
4962 4974 is always available as
4963 4975 \family typewriter
4964 4976 _<n>
4965 4977 \family default
4966 4978 (don't use the angle brackets, just the number, e.g.
4967 4979
4968 4980 \family typewriter
4969 4981 _21
4970 4982 \family default
4971 4983 ).
4972 4984 \layout Standard
4973 4985
4974 4986 These global variables are all stored in a global dictionary (not a list,
4975 4987 since it only has entries for lines which returned a result) available
4976 4988 under the names
4977 4989 \family typewriter
4978 4990 _oh
4979 4991 \family default
4980 4992 and
4981 4993 \family typewriter
4982 4994 Out
4983 4995 \family default
4984 4996 (similar to
4985 4997 \family typewriter
4986 4998 _ih
4987 4999 \family default
4988 5000 and
4989 5001 \family typewriter
4990 5002 In
4991 5003 \family default
4992 5004 ).
4993 5005 So the output from line 12 can be obtained as
4994 5006 \family typewriter
4995 5007 _12
4996 5008 \family default
4997 5009 ,
4998 5010 \family typewriter
4999 5011 Out[12]
5000 5012 \family default
5001 5013 or
5002 5014 \family typewriter
5003 5015 _oh[12]
5004 5016 \family default
5005 5017 .
5006 5018 If you accidentally overwrite the
5007 5019 \family typewriter
5008 5020 Out
5009 5021 \family default
5010 5022 variable you can recover it by typing
5011 5023 \family typewriter
5012 5024 'Out=_oh
5013 5025 \family default
5014 5026 ' at the prompt.
5015 5027 \layout Standard
5016 5028
5017 5029 This system obviously can potentially put heavy memory demands on your system,
5018 5030 since it prevents Python's garbage collector from removing any previously
5019 5031 computed results.
5020 5032 You can control how many results are kept in memory with the option (at
5021 5033 the command line or in your
5022 5034 \family typewriter
5023 5035 ipythonrc
5024 5036 \family default
5025 5037 file)
5026 5038 \family typewriter
5027 5039 cache_size
5028 5040 \family default
5029 5041 .
5030 5042 If you set it to 0, the whole system is completely disabled and the prompts
5031 5043 revert to the classic
5032 5044 \family typewriter
5033 5045 '>>>'
5034 5046 \family default
5035 5047 of normal Python.
5036 5048 \layout Subsection
5037 5049
5038 5050 Directory history
5039 5051 \layout Standard
5040 5052
5041 5053 Your history of visited directories is kept in the global list
5042 5054 \family typewriter
5043 5055 _dh
5044 5056 \family default
5045 5057 , and the magic
5046 5058 \family typewriter
5047 5059 %cd
5048 5060 \family default
5049 5061 command can be used to go to any entry in that list.
5050 5062 The
5051 5063 \family typewriter
5052 5064 %dhist
5053 5065 \family default
5054 5066 command allows you to view this history.
5055 5067 \layout Subsection
5056 5068
5057 5069 Automatic parentheses and quotes
5058 5070 \layout Standard
5059 5071
5060 5072 These features were adapted from Nathan Gray's LazyPython.
5061 5073 They are meant to allow less typing for common situations.
5062 5074 \layout Subsubsection
5063 5075
5064 5076 Automatic parentheses
5065 5077 \layout Standard
5066 5078
5067 5079 Callable objects (i.e.
5068 5080 functions, methods, etc) can be invoked like this (notice the commas between
5069 5081 the arguments):
5070 5082 \layout Standard
5071 5083
5072 5084
5073 5085 \family typewriter
5074 5086 >>> callable_ob arg1, arg2, arg3
5075 5087 \layout Standard
5076 5088
5077 5089 and the input will be translated to this:
5078 5090 \layout Standard
5079 5091
5080 5092
5081 5093 \family typewriter
5082 5094 --> callable_ob(arg1, arg2, arg3)
5083 5095 \layout Standard
5084 5096
5085 5097 You can force automatic parentheses by using '/' as the first character
5086 5098 of a line.
5087 5099 For example:
5088 5100 \layout Standard
5089 5101
5090 5102
5091 5103 \family typewriter
5092 5104 >>> /globals # becomes 'globals()'
5093 5105 \layout Standard
5094 5106
5095 5107 Note that the '/' MUST be the first character on the line! This won't work:
5096 5108
5097 5109 \layout Standard
5098 5110
5099 5111
5100 5112 \family typewriter
5101 5113 >>> print /globals # syntax error
5102 5114 \layout Standard
5103 5115
5104 5116 In most cases the automatic algorithm should work, so you should rarely
5105 5117 need to explicitly invoke /.
5106 5118 One notable exception is if you are trying to call a function with a list
5107 5119 of tuples as arguments (the parenthesis will confuse IPython):
5108 5120 \layout Standard
5109 5121
5110 5122
5111 5123 \family typewriter
5112 5124 In [1]: zip (1,2,3),(4,5,6) # won't work
5113 5125 \layout Standard
5114 5126
5115 5127 but this will work:
5116 5128 \layout Standard
5117 5129
5118 5130
5119 5131 \family typewriter
5120 5132 In [2]: /zip (1,2,3),(4,5,6)
5121 5133 \newline
5122 5134 ------> zip ((1,2,3),(4,5,6))
5123 5135 \newline
5124 5136 Out[2]= [(1, 4), (2, 5), (3, 6)]
5125 5137 \layout Standard
5126 5138
5127 5139 IPython tells you that it has altered your command line by displaying the
5128 5140 new command line preceded by
5129 5141 \family typewriter
5130 5142 -->
5131 5143 \family default
5132 5144 .
5133 5145 e.g.:
5134 5146 \layout Standard
5135 5147
5136 5148
5137 5149 \family typewriter
5138 5150 In [18]: callable list
5139 5151 \newline
5140 5152 -------> callable (list)
5141 5153 \layout Subsubsection
5142 5154
5143 5155 Automatic quoting
5144 5156 \layout Standard
5145 5157
5146 5158 You can force automatic quoting of a function's arguments by using
5147 5159 \family typewriter
5148 5160 `,'
5149 5161 \family default
5150 5162 or
5151 5163 \family typewriter
5152 5164 `;'
5153 5165 \family default
5154 5166 as the first character of a line.
5155 5167 For example:
5156 5168 \layout Standard
5157 5169
5158 5170
5159 5171 \family typewriter
5160 5172 >>> ,my_function /home/me # becomes my_function("/home/me")
5161 5173 \layout Standard
5162 5174
5163 5175 If you use
5164 5176 \family typewriter
5165 5177 `;'
5166 5178 \family default
5167 5179 instead, the whole argument is quoted as a single string (while
5168 5180 \family typewriter
5169 5181 `,'
5170 5182 \family default
5171 5183 splits on whitespace):
5172 5184 \layout Standard
5173 5185
5174 5186
5175 5187 \family typewriter
5176 5188 >>> ,my_function a b c # becomes my_function("a","b","c")
5177 5189 \layout Standard
5178 5190
5179 5191
5180 5192 \family typewriter
5181 5193 >>> ;my_function a b c # becomes my_function("a b c")
5182 5194 \layout Standard
5183 5195
5184 5196 Note that the `
5185 5197 \family typewriter
5186 5198 ,
5187 5199 \family default
5188 5200 ' or `
5189 5201 \family typewriter
5190 5202 ;
5191 5203 \family default
5192 5204 ' MUST be the first character on the line! This won't work:
5193 5205 \layout Standard
5194 5206
5195 5207
5196 5208 \family typewriter
5197 5209 >>> x = ,my_function /home/me # syntax error
5198 5210 \layout Section
5199 5211
5200 5212
5201 5213 \begin_inset LatexCommand \label{sec:customization}
5202 5214
5203 5215 \end_inset
5204 5216
5205 5217 Customization
5206 5218 \layout Standard
5207 5219
5208 5220 As we've already mentioned, IPython reads a configuration file which can
5209 5221 be specified at the command line (
5210 5222 \family typewriter
5211 5223 -rcfile
5212 5224 \family default
5213 5225 ) or which by default is assumed to be called
5214 5226 \family typewriter
5215 5227 ipythonrc
5216 5228 \family default
5217 5229 .
5218 5230 Such a file is looked for in the current directory where IPython is started
5219 5231 and then in your
5220 5232 \family typewriter
5221 5233 IPYTHONDIR
5222 5234 \family default
5223 5235 , which allows you to have local configuration files for specific projects.
5224 5236 In this section we will call these types of configuration files simply
5225 5237 rcfiles (short for resource configuration file).
5226 5238 \layout Standard
5227 5239
5228 5240 The syntax of an rcfile is one of key-value pairs separated by whitespace,
5229 5241 one per line.
5230 5242 Lines beginning with a
5231 5243 \family typewriter
5232 5244 #
5233 5245 \family default
5234 5246 are ignored as comments, but comments can
5235 5247 \series bold
5236 5248 not
5237 5249 \series default
5238 5250 be put on lines with data (the parser is fairly primitive).
5239 5251 Note that these are not python files, and this is deliberate, because it
5240 5252 allows us to do some things which would be quite tricky to implement if
5241 5253 they were normal python files.
5242 5254 \layout Standard
5243 5255
5244 5256 First, an rcfile can contain permanent default values for almost all command
5245 5257 line options (except things like
5246 5258 \family typewriter
5247 5259 -help
5248 5260 \family default
5249 5261 or
5250 5262 \family typewriter
5251 5263 -Version
5252 5264 \family default
5253 5265 ).
5254 5266 Sec\SpecialChar ~
5255 5267
5256 5268 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5257 5269
5258 5270 \end_inset
5259 5271
5260 5272 contains a description of all command-line options.
5261 5273 However, values you explicitly specify at the command line override the
5262 5274 values defined in the rcfile.
5263 5275 \layout Standard
5264 5276
5265 5277 Besides command line option values, the rcfile can specify values for certain
5266 5278 extra special options which are not available at the command line.
5267 5279 These options are briefly described below.
5268 5280
5269 5281 \layout Standard
5270 5282
5271 5283 Each of these options may appear as many times as you need it in the file.
5272 5284 \layout List
5273 5285 \labelwidthstring 00.00.0000
5274 5286
5275 5287
5276 5288 \family typewriter
5277 5289 \series bold
5278 5290 include\SpecialChar ~
5279 5291 <file1>\SpecialChar ~
5280 5292 <file2>\SpecialChar ~
5281 5293 ...
5282 5294 \family default
5283 5295 \series default
5284 5296 : you can name
5285 5297 \emph on
5286 5298 other
5287 5299 \emph default
5288 5300 rcfiles you want to recursively load up to 15 levels (don't use the
5289 5301 \family typewriter
5290 5302 <>
5291 5303 \family default
5292 5304 brackets in your names!).
5293 5305 This feature allows you to define a 'base' rcfile with general options
5294 5306 and special-purpose files which can be loaded only when needed with particular
5295 5307 configuration options.
5296 5308 To make this more convenient, IPython accepts the
5297 5309 \family typewriter
5298 5310 -profile <name>
5299 5311 \family default
5300 5312 option (abbreviates to
5301 5313 \family typewriter
5302 5314 -p <name
5303 5315 \family default
5304 5316 >)
5305 5317 \family typewriter
5306 5318 which
5307 5319 \family default
5308 5320 tells it to look for an rcfile named
5309 5321 \family typewriter
5310 5322 ipythonrc-<name>
5311 5323 \family default
5312 5324 .
5313 5325
5314 5326 \layout List
5315 5327 \labelwidthstring 00.00.0000
5316 5328
5317 5329
5318 5330 \family typewriter
5319 5331 \series bold
5320 5332 import_mod\SpecialChar ~
5321 5333 <mod1>\SpecialChar ~
5322 5334 <mod2>\SpecialChar ~
5323 5335 ...
5324 5336 \family default
5325 5337 \series default
5326 5338 : import modules with '
5327 5339 \family typewriter
5328 5340 import
5329 5341 \family default
5330 5342
5331 5343 \family typewriter
5332 5344 <mod1>,<mod2>,...
5333 5345 \family default
5334 5346 '
5335 5347 \layout List
5336 5348 \labelwidthstring 00.00.0000
5337 5349
5338 5350
5339 5351 \family typewriter
5340 5352 \series bold
5341 5353 import_some\SpecialChar ~
5342 5354 <mod>\SpecialChar ~
5343 5355 <f1>\SpecialChar ~
5344 5356 <f2>\SpecialChar ~
5345 5357 ...
5346 5358 \family default
5347 5359 \series default
5348 5360 : import functions with '
5349 5361 \family typewriter
5350 5362 from <mod> import
5351 5363 \family default
5352 5364
5353 5365 \family typewriter
5354 5366 <f1>,<f2>,...
5355 5367 \family default
5356 5368 '
5357 5369 \layout List
5358 5370 \labelwidthstring 00.00.0000
5359 5371
5360 5372
5361 5373 \family typewriter
5362 5374 \series bold
5363 5375 import_all\SpecialChar ~
5364 5376 <mod1>\SpecialChar ~
5365 5377 <mod2>\SpecialChar ~
5366 5378 ...
5367 5379 \family default
5368 5380 \series default
5369 5381 : for each module listed import functions with '
5370 5382 \family typewriter
5371 5383 from <mod> import *
5372 5384 \family default
5373 5385 '
5374 5386 \layout List
5375 5387 \labelwidthstring 00.00.0000
5376 5388
5377 5389
5378 5390 \family typewriter
5379 5391 \series bold
5380 5392 execute\SpecialChar ~
5381 5393 <python\SpecialChar ~
5382 5394 code>
5383 5395 \family default
5384 5396 \series default
5385 5397 : give any single-line python code to be executed.
5386 5398 \layout List
5387 5399 \labelwidthstring 00.00.0000
5388 5400
5389 5401
5390 5402 \family typewriter
5391 5403 \series bold
5392 5404 execfile\SpecialChar ~
5393 5405 <filename>
5394 5406 \family default
5395 5407 \series default
5396 5408 : execute the python file given with an '
5397 5409 \family typewriter
5398 5410 execfile(filename)
5399 5411 \family default
5400 5412 ' command.
5401 5413 Username expansion is performed on the given names.
5402 5414 So if you need any amount of extra fancy customization that won't fit in
5403 5415 any of the above 'canned' options, you can just put it in a separate python
5404 5416 file and execute it.
5405 5417 \layout List
5406 5418 \labelwidthstring 00.00.0000
5407 5419
5408 5420
5409 5421 \family typewriter
5410 5422 \series bold
5411 5423 alias\SpecialChar ~
5412 5424 <alias_def>
5413 5425 \family default
5414 5426 \series default
5415 5427 : this is equivalent to calling '
5416 5428 \family typewriter
5417 5429 %alias\SpecialChar ~
5418 5430 <alias_def>
5419 5431 \family default
5420 5432 ' at the IPython command line.
5421 5433 This way, from within IPython you can do common system tasks without having
5422 5434 to exit it or use the
5423 5435 \family typewriter
5424 5436 !
5425 5437 \family default
5426 5438 escape.
5427 5439 IPython isn't meant to be a shell replacement, but it is often very useful
5428 5440 to be able to do things with files while testing code.
5429 5441 This gives you the flexibility to have within IPython any aliases you may
5430 5442 be used to under your normal system shell.
5431 5443 \layout Subsection
5432 5444
5433 5445
5434 5446 \begin_inset LatexCommand \label{sec:ipytonrc-sample}
5435 5447
5436 5448 \end_inset
5437 5449
5438 5450 Sample
5439 5451 \family typewriter
5440 5452 ipythonrc
5441 5453 \family default
5442 5454 file
5443 5455 \layout Standard
5444 5456
5445 5457 The default rcfile, called
5446 5458 \family typewriter
5447 5459 ipythonrc
5448 5460 \family default
5449 5461 and supplied in your
5450 5462 \family typewriter
5451 5463 IPYTHONDIR
5452 5464 \family default
5453 5465 directory contains lots of comments on all of these options.
5454 5466 We reproduce it here for reference:
5455 5467 \layout Standard
5456 5468
5457 5469
5458 5470 \begin_inset ERT
5459 5471 status Open
5460 5472
5461 5473 \layout Standard
5462 5474
5463 5475 \backslash
5464 5476 codelist{../IPython/UserConfig/ipythonrc}
5465 5477 \end_inset
5466 5478
5467 5479
5468 5480 \layout Subsection
5469 5481
5470 5482
5471 5483 \begin_inset LatexCommand \label{sec:prompts}
5472 5484
5473 5485 \end_inset
5474 5486
5475 5487 Fine-tuning your prompt
5476 5488 \layout Standard
5477 5489
5478 5490 IPython's prompts can be customized using a syntax similar to that of the
5479 5491
5480 5492 \family typewriter
5481 5493 bash
5482 5494 \family default
5483 5495 shell.
5484 5496 Many of
5485 5497 \family typewriter
5486 5498 bash
5487 5499 \family default
5488 5500 's escapes are supported, as well as a few additional ones.
5489 5501 We list them below:
5490 5502 \layout Description
5491 5503
5492 5504
5493 5505 \backslash
5494 5506 # the prompt/history count number
5495 5507 \layout Description
5496 5508
5497 5509
5498 5510 \backslash
5499 5511 D the prompt/history count, with the actual digits replaced by dots.
5500 5512 Used mainly in continuation prompts (prompt_in2)
5501 5513 \layout Description
5502 5514
5503 5515
5504 5516 \backslash
5505 5517 w the current working directory
5506 5518 \layout Description
5507 5519
5508 5520
5509 5521 \backslash
5510 5522 W the basename of current working directory
5511 5523 \layout Description
5512 5524
5513 5525
5514 5526 \backslash
5515 5527 X
5516 5528 \emph on
5517 5529 n
5518 5530 \emph default
5519 5531 where
5520 5532 \begin_inset Formula $n=0\ldots5.$
5521 5533 \end_inset
5522 5534
5523 5535 The current working directory, with
5524 5536 \family typewriter
5525 5537 $HOME
5526 5538 \family default
5527 5539 replaced by
5528 5540 \family typewriter
5529 5541 ~
5530 5542 \family default
5531 5543 , and filtered out to contain only
5532 5544 \begin_inset Formula $n$
5533 5545 \end_inset
5534 5546
5535 5547 path elements
5536 5548 \layout Description
5537 5549
5538 5550
5539 5551 \backslash
5540 5552 Y
5541 5553 \emph on
5542 5554 n
5543 5555 \emph default
5544 5556 Similar to
5545 5557 \backslash
5546 5558 X
5547 5559 \emph on
5548 5560 n
5549 5561 \emph default
5550 5562 , but with the
5551 5563 \begin_inset Formula $n+1$
5552 5564 \end_inset
5553 5565
5554 5566 element included if it is
5555 5567 \family typewriter
5556 5568 ~
5557 5569 \family default
5558 5570 (this is similar to the behavior of the %c
5559 5571 \emph on
5560 5572 n
5561 5573 \emph default
5562 5574 escapes in
5563 5575 \family typewriter
5564 5576 tcsh
5565 5577 \family default
5566 5578 )
5567 5579 \layout Description
5568 5580
5569 5581
5570 5582 \backslash
5571 5583 u the username of the current user
5572 5584 \layout Description
5573 5585
5574 5586
5575 5587 \backslash
5576 5588 $ if the effective UID is 0, a #, otherwise a $
5577 5589 \layout Description
5578 5590
5579 5591
5580 5592 \backslash
5581 5593 h the hostname up to the first `.'
5582 5594 \layout Description
5583 5595
5584 5596
5585 5597 \backslash
5586 5598 H the hostname
5587 5599 \layout Description
5588 5600
5589 5601
5590 5602 \backslash
5591 5603 n a newline
5592 5604 \layout Description
5593 5605
5594 5606
5595 5607 \backslash
5596 5608 r a carriage return
5597 5609 \layout Description
5598 5610
5599 5611
5600 5612 \backslash
5601 5613 v IPython version string
5602 5614 \layout Standard
5603 5615
5604 5616 In addition to these, ANSI color escapes can be insterted into the prompts,
5605 5617 as
5606 5618 \family typewriter
5607 5619
5608 5620 \backslash
5609 5621 C_
5610 5622 \emph on
5611 5623 ColorName
5612 5624 \family default
5613 5625 \emph default
5614 5626 .
5615 5627 The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green,
5616 5628 LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor,
5617 5629 Normal, Purple, Red, White, Yellow.
5618 5630 \layout Standard
5619 5631
5620 5632 Finally, IPython supports the evaluation of arbitrary expressions in your
5621 5633 prompt string.
5622 5634 The prompt strings are evaluated through the syntax of PEP 215, but basically
5623 5635 you can use
5624 5636 \family typewriter
5625 5637 $x.y
5626 5638 \family default
5627 5639 to expand the value of
5628 5640 \family typewriter
5629 5641 x.y
5630 5642 \family default
5631 5643 , and for more complicated expressions you can use braces:
5632 5644 \family typewriter
5633 5645 ${foo()+x}
5634 5646 \family default
5635 5647 will call function
5636 5648 \family typewriter
5637 5649 foo
5638 5650 \family default
5639 5651 and add to it the value of
5640 5652 \family typewriter
5641 5653 x
5642 5654 \family default
5643 5655 , before putting the result into your prompt.
5644 5656 For example, using
5645 5657 \newline
5646 5658
5647 5659 \family typewriter
5648 5660 prompt_in1 '${commands.getoutput("uptime")}
5649 5661 \backslash
5650 5662 nIn [
5651 5663 \backslash
5652 5664 #]: '
5653 5665 \newline
5654 5666
5655 5667 \family default
5656 5668 will print the result of the uptime command on each prompt (assuming the
5657 5669
5658 5670 \family typewriter
5659 5671 commands
5660 5672 \family default
5661 5673 module has been imported in your
5662 5674 \family typewriter
5663 5675 ipythonrc
5664 5676 \family default
5665 5677 file).
5666 5678 \layout Subsubsection
5667 5679
5668 5680 Prompt examples
5669 5681 \layout Standard
5670 5682
5671 5683 The following options in an ipythonrc file will give you IPython's default
5672 5684 prompts:
5673 5685 \layout Standard
5674 5686
5675 5687
5676 5688 \family typewriter
5677 5689 prompt_in1 'In [
5678 5690 \backslash
5679 5691 #]:'
5680 5692 \newline
5681 5693 prompt_in2 '\SpecialChar ~
5682 5694 \SpecialChar ~
5683 5695 \SpecialChar ~
5684 5696 .
5685 5697 \backslash
5686 5698 D.:'
5687 5699 \newline
5688 5700 prompt_out 'Out[
5689 5701 \backslash
5690 5702 #]:'
5691 5703 \layout Standard
5692 5704
5693 5705 which look like this:
5694 5706 \layout Standard
5695 5707
5696 5708
5697 5709 \family typewriter
5698 5710 In [1]: 1+2
5699 5711 \newline
5700 5712 Out[1]: 3
5701 5713 \layout Standard
5702 5714
5703 5715
5704 5716 \family typewriter
5705 5717 In [2]: for i in (1,2,3):
5706 5718 \newline
5707 5719
5708 5720 \begin_inset ERT
5709 5721 status Collapsed
5710 5722
5711 5723 \layout Standard
5712 5724
5713 5725 \backslash
5714 5726 hspace*{0mm}
5715 5727 \end_inset
5716 5728
5717 5729 \SpecialChar ~
5718 5730 \SpecialChar ~
5719 5731 \SpecialChar ~
5720 5732 ...: \SpecialChar ~
5721 5733 \SpecialChar ~
5722 5734 \SpecialChar ~
5723 5735 \SpecialChar ~
5724 5736 print i,
5725 5737 \newline
5726 5738
5727 5739 \begin_inset ERT
5728 5740 status Collapsed
5729 5741
5730 5742 \layout Standard
5731 5743
5732 5744 \backslash
5733 5745 hspace*{0mm}
5734 5746 \end_inset
5735 5747
5736 5748 \SpecialChar ~
5737 5749 \SpecialChar ~
5738 5750 \SpecialChar ~
5739 5751 ...:
5740 5752 \newline
5741 5753 1 2 3
5742 5754 \layout Standard
5743 5755
5744 5756 These will give you a very colorful prompt with path information:
5745 5757 \layout Standard
5746 5758
5747 5759
5748 5760 \family typewriter
5749 5761 #prompt_in1 '
5750 5762 \backslash
5751 5763 C_Red
5752 5764 \backslash
5753 5765 u
5754 5766 \backslash
5755 5767 C_Blue[
5756 5768 \backslash
5757 5769 C_Cyan
5758 5770 \backslash
5759 5771 Y1
5760 5772 \backslash
5761 5773 C_Blue]
5762 5774 \backslash
5763 5775 C_LightGreen
5764 5776 \backslash
5765 5777 #>'
5766 5778 \newline
5767 5779 prompt_in2 ' ..
5768 5780 \backslash
5769 5781 D>'
5770 5782 \newline
5771 5783 prompt_out '<
5772 5784 \backslash
5773 5785 #>'
5774 5786 \layout Standard
5775 5787
5776 5788 which look like this:
5777 5789 \layout Standard
5778 5790
5779 5791
5780 5792 \family typewriter
5781 5793 \color red
5782 5794 fperez
5783 5795 \color blue
5784 5796 [
5785 5797 \color cyan
5786 5798 ~/ipython
5787 5799 \color blue
5788 5800 ]
5789 5801 \color green
5790 5802 1>
5791 5803 \color default
5792 5804 1+2
5793 5805 \newline
5794 5806
5795 5807 \begin_inset ERT
5796 5808 status Collapsed
5797 5809
5798 5810 \layout Standard
5799 5811
5800 5812 \backslash
5801 5813 hspace*{0mm}
5802 5814 \end_inset
5803 5815
5804 5816 \SpecialChar ~
5805 5817 \SpecialChar ~
5806 5818 \SpecialChar ~
5807 5819 \SpecialChar ~
5808 5820 \SpecialChar ~
5809 5821 \SpecialChar ~
5810 5822 \SpecialChar ~
5811 5823 \SpecialChar ~
5812 5824 \SpecialChar ~
5813 5825 \SpecialChar ~
5814 5826 \SpecialChar ~
5815 5827 \SpecialChar ~
5816 5828 \SpecialChar ~
5817 5829 \SpecialChar ~
5818 5830 \SpecialChar ~
5819 5831 \SpecialChar ~
5820 5832
5821 5833 \color red
5822 5834 <1>
5823 5835 \color default
5824 5836 3
5825 5837 \newline
5826 5838
5827 5839 \color red
5828 5840 fperez
5829 5841 \color blue
5830 5842 [
5831 5843 \color cyan
5832 5844 ~/ipython
5833 5845 \color blue
5834 5846 ]
5835 5847 \color green
5836 5848 2>
5837 5849 \color default
5838 5850 for i in (1,2,3):
5839 5851 \newline
5840 5852
5841 5853 \begin_inset ERT
5842 5854 status Collapsed
5843 5855
5844 5856 \layout Standard
5845 5857
5846 5858 \backslash
5847 5859 hspace*{0mm}
5848 5860 \end_inset
5849 5861
5850 5862 \SpecialChar ~
5851 5863 \SpecialChar ~
5852 5864 \SpecialChar ~
5853 5865 \SpecialChar ~
5854 5866 \SpecialChar ~
5855 5867 \SpecialChar ~
5856 5868 \SpecialChar ~
5857 5869 \SpecialChar ~
5858 5870 \SpecialChar ~
5859 5871 \SpecialChar ~
5860 5872 \SpecialChar ~
5861 5873 \SpecialChar ~
5862 5874 \SpecialChar ~
5863 5875 \SpecialChar ~
5864 5876 \SpecialChar ~
5865 5877
5866 5878 \color green
5867 5879 ...>
5868 5880 \color default
5869 5881 \SpecialChar ~
5870 5882 \SpecialChar ~
5871 5883 \SpecialChar ~
5872 5884 \SpecialChar ~
5873 5885 print i,
5874 5886 \newline
5875 5887
5876 5888 \begin_inset ERT
5877 5889 status Collapsed
5878 5890
5879 5891 \layout Standard
5880 5892
5881 5893 \backslash
5882 5894 hspace*{0mm}
5883 5895 \end_inset
5884 5896
5885 5897 \SpecialChar ~
5886 5898 \SpecialChar ~
5887 5899 \SpecialChar ~
5888 5900 \SpecialChar ~
5889 5901 \SpecialChar ~
5890 5902 \SpecialChar ~
5891 5903 \SpecialChar ~
5892 5904 \SpecialChar ~
5893 5905 \SpecialChar ~
5894 5906 \SpecialChar ~
5895 5907 \SpecialChar ~
5896 5908 \SpecialChar ~
5897 5909 \SpecialChar ~
5898 5910 \SpecialChar ~
5899 5911 \SpecialChar ~
5900 5912
5901 5913 \color green
5902 5914 ...>
5903 5915 \color default
5904 5916
5905 5917 \newline
5906 5918 1 2 3
5907 5919 \layout Standard
5908 5920
5909 5921 The following shows the usage of dynamic expression evaluation:
5910 5922 \layout Subsection
5911 5923
5912 5924
5913 5925 \begin_inset LatexCommand \label{sec:profiles}
5914 5926
5915 5927 \end_inset
5916 5928
5917 5929 IPython profiles
5918 5930 \layout Standard
5919 5931
5920 5932 As we already mentioned, IPython supports the
5921 5933 \family typewriter
5922 5934 -profile
5923 5935 \family default
5924 5936 command-line option (see sec.
5925 5937
5926 5938 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5927 5939
5928 5940 \end_inset
5929 5941
5930 5942 ).
5931 5943 A profile is nothing more than a particular configuration file like your
5932 5944 basic
5933 5945 \family typewriter
5934 5946 ipythonrc
5935 5947 \family default
5936 5948 one, but with particular customizations for a specific purpose.
5937 5949 When you start IPython with '
5938 5950 \family typewriter
5939 5951 ipython -profile <name>
5940 5952 \family default
5941 5953 ', it assumes that in your
5942 5954 \family typewriter
5943 5955 IPYTHONDIR
5944 5956 \family default
5945 5957 there is a file called
5946 5958 \family typewriter
5947 5959 ipythonrc-<name>
5948 5960 \family default
5949 5961 , and loads it instead of the normal
5950 5962 \family typewriter
5951 5963 ipythonrc
5952 5964 \family default
5953 5965 .
5954 5966 \layout Standard
5955 5967
5956 5968 This system allows you to maintain multiple configurations which load modules,
5957 5969 set options, define functions, etc.
5958 5970 suitable for different tasks and activate them in a very simple manner.
5959 5971 In order to avoid having to repeat all of your basic options (common things
5960 5972 that don't change such as your color preferences, for example), any profile
5961 5973 can include another configuration file.
5962 5974 The most common way to use profiles is then to have each one include your
5963 5975 basic
5964 5976 \family typewriter
5965 5977 ipythonrc
5966 5978 \family default
5967 5979 file as a starting point, and then add further customizations.
5968 5980 \layout Standard
5969 5981
5970 5982 In sections
5971 5983 \begin_inset LatexCommand \ref{sec:syntax-extensions}
5972 5984
5973 5985 \end_inset
5974 5986
5975 5987 and
5976 5988 \begin_inset LatexCommand \ref{sec:Gnuplot}
5977 5989
5978 5990 \end_inset
5979 5991
5980 5992 we discuss some particular profiles which come as part of the standard
5981 5993 IPython distribution.
5982 5994 You may also look in your
5983 5995 \family typewriter
5984 5996 IPYTHONDIR
5985 5997 \family default
5986 5998 directory, any file whose name begins with
5987 5999 \family typewriter
5988 6000 ipythonrc-
5989 6001 \family default
5990 6002 is a profile.
5991 6003 You can use those as examples for further customizations to suit your own
5992 6004 needs.
5993 6005 \layout Section
5994 6006
5995 6007
5996 6008 \begin_inset OptArg
5997 6009 collapsed false
5998 6010
5999 6011 \layout Standard
6000 6012
6001 6013 IPython as default...
6002 6014 \end_inset
6003 6015
6004 6016 IPython as your default Python environment
6005 6017 \layout Standard
6006 6018
6007 6019 Python honors the environment variable
6008 6020 \family typewriter
6009 6021 PYTHONSTARTUP
6010 6022 \family default
6011 6023 and will execute at startup the file referenced by this variable.
6012 6024 If you put at the end of this file the following two lines of code:
6013 6025 \layout Standard
6014 6026
6015 6027
6016 6028 \family typewriter
6017 6029 import IPython
6018 6030 \newline
6019 6031 IPython.Shell.IPShell().mainloop(sys_exit=1)
6020 6032 \layout Standard
6021 6033
6022 6034 then IPython will be your working environment anytime you start Python.
6023 6035 The
6024 6036 \family typewriter
6025 6037 sys_exit=1
6026 6038 \family default
6027 6039 is needed to have IPython issue a call to
6028 6040 \family typewriter
6029 6041 sys.exit()
6030 6042 \family default
6031 6043 when it finishes, otherwise you'll be back at the normal Python '
6032 6044 \family typewriter
6033 6045 >>>
6034 6046 \family default
6035 6047 ' prompt
6036 6048 \begin_inset Foot
6037 6049 collapsed true
6038 6050
6039 6051 \layout Standard
6040 6052
6041 6053 Based on an idea by Holger Krekel.
6042 6054 \end_inset
6043 6055
6044 6056 .
6045 6057 \layout Standard
6046 6058
6047 6059 This is probably useful to developers who manage multiple Python versions
6048 6060 and don't want to have correspondingly multiple IPython versions.
6049 6061 Note that in this mode, there is no way to pass IPython any command-line
6050 6062 options, as those are trapped first by Python itself.
6051 6063 \layout Section
6052 6064
6053 6065
6054 6066 \begin_inset LatexCommand \label{sec:embed}
6055 6067
6056 6068 \end_inset
6057 6069
6058 6070 Embedding IPython
6059 6071 \layout Standard
6060 6072
6061 6073 It is possible to start an IPython instance
6062 6074 \emph on
6063 6075 inside
6064 6076 \emph default
6065 6077 your own Python programs.
6066 6078 This allows you to evaluate dynamically the state of your code, operate
6067 6079 with your variables, analyze them, etc.
6068 6080 Note however that any changes you make to values while in the shell do
6069 6081
6070 6082 \emph on
6071 6083 not
6072 6084 \emph default
6073 6085 propagate back to the running code, so it is safe to modify your values
6074 6086 because you won't break your code in bizarre ways by doing so.
6075 6087 \layout Standard
6076 6088
6077 6089 This feature allows you to easily have a fully functional python environment
6078 6090 for doing object introspection anywhere in your code with a simple function
6079 6091 call.
6080 6092 In some cases a simple print statement is enough, but if you need to do
6081 6093 more detailed analysis of a code fragment this feature can be very valuable.
6082 6094 \layout Standard
6083 6095
6084 6096 It can also be useful in scientific computing situations where it is common
6085 6097 to need to do some automatic, computationally intensive part and then stop
6086 6098 to look at data, plots, etc
6087 6099 \begin_inset Foot
6088 6100 collapsed true
6089 6101
6090 6102 \layout Standard
6091 6103
6092 6104 This functionality was inspired by IDL's combination of the
6093 6105 \family typewriter
6094 6106 stop
6095 6107 \family default
6096 6108 keyword and the
6097 6109 \family typewriter
6098 6110 .continue
6099 6111 \family default
6100 6112 executive command, which I have found very useful in the past, and by a
6101 6113 posting on comp.lang.python by cmkl <cmkleffner-AT-gmx.de> on Dec.
6102 6114 06/01 concerning similar uses of pyrepl.
6103 6115 \end_inset
6104 6116
6105 6117 .
6106 6118 Opening an IPython instance will give you full access to your data and
6107 6119 functions, and you can resume program execution once you are done with
6108 6120 the interactive part (perhaps to stop again later, as many times as needed).
6109 6121 \layout Standard
6110 6122
6111 6123 The following code snippet is the bare minimum you need to include in your
6112 6124 Python programs for this to work (detailed examples follow later):
6113 6125 \layout LyX-Code
6114 6126
6115 6127 from IPython.Shell import IPShellEmbed
6116 6128 \layout LyX-Code
6117 6129
6118 6130 ipshell = IPShellEmbed()
6119 6131 \layout LyX-Code
6120 6132
6121 6133 ipshell() # this call anywhere in your program will start IPython
6122 6134 \layout Standard
6123 6135
6124 6136 You can run embedded instances even in code which is itself being run at
6125 6137 the IPython interactive prompt with '
6126 6138 \family typewriter
6127 6139 %run\SpecialChar ~
6128 6140 <filename>
6129 6141 \family default
6130 6142 '.
6131 6143 Since it's easy to get lost as to where you are (in your top-level IPython
6132 6144 or in your embedded one), it's a good idea in such cases to set the in/out
6133 6145 prompts to something different for the embedded instances.
6134 6146 The code examples below illustrate this.
6135 6147 \layout Standard
6136 6148
6137 6149 You can also have multiple IPython instances in your program and open them
6138 6150 separately, for example with different options for data presentation.
6139 6151 If you close and open the same instance multiple times, its prompt counters
6140 6152 simply continue from each execution to the next.
6141 6153 \layout Standard
6142 6154
6143 6155 Please look at the docstrings in the
6144 6156 \family typewriter
6145 6157 Shell.py
6146 6158 \family default
6147 6159 module for more details on the use of this system.
6148 6160 \layout Standard
6149 6161
6150 6162 The following sample file illustrating how to use the embedding functionality
6151 6163 is provided in the examples directory as
6152 6164 \family typewriter
6153 6165 example-embed.py
6154 6166 \family default
6155 6167 .
6156 6168 It should be fairly self-explanatory:
6157 6169 \layout Standard
6158 6170
6159 6171
6160 6172 \begin_inset ERT
6161 6173 status Open
6162 6174
6163 6175 \layout Standard
6164 6176
6165 6177 \backslash
6166 6178 codelist{examples/example-embed.py}
6167 6179 \end_inset
6168 6180
6169 6181
6170 6182 \layout Standard
6171 6183
6172 6184 Once you understand how the system functions, you can use the following
6173 6185 code fragments in your programs which are ready for cut and paste:
6174 6186 \layout Standard
6175 6187
6176 6188
6177 6189 \begin_inset ERT
6178 6190 status Open
6179 6191
6180 6192 \layout Standard
6181 6193
6182 6194 \backslash
6183 6195 codelist{examples/example-embed-short.py}
6184 6196 \end_inset
6185 6197
6186 6198
6187 6199 \layout Section
6188 6200
6189 6201
6190 6202 \begin_inset LatexCommand \label{sec:using-pdb}
6191 6203
6192 6204 \end_inset
6193 6205
6194 6206 Using the Python debugger (
6195 6207 \family typewriter
6196 6208 pdb
6197 6209 \family default
6198 6210 )
6199 6211 \layout Subsection
6200 6212
6201 6213 Running entire programs via
6202 6214 \family typewriter
6203 6215 pdb
6204 6216 \layout Standard
6205 6217
6206 6218
6207 6219 \family typewriter
6208 6220 pdb
6209 6221 \family default
6210 6222 , the Python debugger, is a powerful interactive debugger which allows you
6211 6223 to step through code, set breakpoints, watch variables, etc.
6212 6224 IPython makes it very easy to start any script under the control of
6213 6225 \family typewriter
6214 6226 pdb
6215 6227 \family default
6216 6228 , regardless of whether you have wrapped it into a
6217 6229 \family typewriter
6218 6230 `main()'
6219 6231 \family default
6220 6232 function or not.
6221 6233 For this, simply type
6222 6234 \family typewriter
6223 6235 `%run -d myscript'
6224 6236 \family default
6225 6237 at an IPython prompt.
6226 6238 See the
6227 6239 \family typewriter
6228 6240 %run
6229 6241 \family default
6230 6242 command's documentation (via
6231 6243 \family typewriter
6232 6244 `%run?'
6233 6245 \family default
6234 6246 or in Sec.\SpecialChar ~
6235 6247
6236 6248 \begin_inset LatexCommand \ref{sec:magic}
6237 6249
6238 6250 \end_inset
6239 6251
6240 6252 ) for more details, including how to control where
6241 6253 \family typewriter
6242 6254 pdb
6243 6255 \family default
6244 6256 will stop execution first.
6245 6257 \layout Standard
6246 6258
6247 6259 For more information on the use of the
6248 6260 \family typewriter
6249 6261 pdb
6250 6262 \family default
6251 6263 debugger, read the included
6252 6264 \family typewriter
6253 6265 pdb.doc
6254 6266 \family default
6255 6267 file (part of the standard Python distribution).
6256 6268 On a stock Linux system it is located at
6257 6269 \family typewriter
6258 6270 /usr/lib/python2.3/pdb.doc
6259 6271 \family default
6260 6272 , but the easiest way to read it is by using the
6261 6273 \family typewriter
6262 6274 help()
6263 6275 \family default
6264 6276 function of the
6265 6277 \family typewriter
6266 6278 pdb
6267 6279 \family default
6268 6280 module as follows (in an IPython prompt):
6269 6281 \layout Standard
6270 6282
6271 6283
6272 6284 \family typewriter
6273 6285 In [1]: import pdb
6274 6286 \newline
6275 6287 In [2]: pdb.help()
6276 6288 \layout Standard
6277 6289
6278 6290 This will load the
6279 6291 \family typewriter
6280 6292 pdb.doc
6281 6293 \family default
6282 6294 document in a file viewer for you automatically.
6283 6295 \layout Subsection
6284 6296
6285 6297 Automatic invocation of
6286 6298 \family typewriter
6287 6299 pdb
6288 6300 \family default
6289 6301 on exceptions
6290 6302 \layout Standard
6291 6303
6292 6304 IPython, if started with the
6293 6305 \family typewriter
6294 6306 -pdb
6295 6307 \family default
6296 6308 option (or if the option is set in your rc file) can call the Python
6297 6309 \family typewriter
6298 6310 pdb
6299 6311 \family default
6300 6312 debugger every time your code triggers an uncaught exception
6301 6313 \begin_inset Foot
6302 6314 collapsed true
6303 6315
6304 6316 \layout Standard
6305 6317
6306 6318 Many thanks to Christopher Hart for the request which prompted adding this
6307 6319 feature to IPython.
6308 6320 \end_inset
6309 6321
6310 6322 .
6311 6323 This feature can also be toggled at any time with the
6312 6324 \family typewriter
6313 6325 %pdb
6314 6326 \family default
6315 6327 magic command.
6316 6328 This can be extremely useful in order to find the origin of subtle bugs,
6317 6329 because
6318 6330 \family typewriter
6319 6331 pdb
6320 6332 \family default
6321 6333 opens up at the point in your code which triggered the exception, and while
6322 6334 your program is at this point `dead', all the data is still available and
6323 6335 you can walk up and down the stack frame and understand the origin of the
6324 6336 problem.
6325 6337 \layout Standard
6326 6338
6327 6339 Furthermore, you can use these debugging facilities both with the embedded
6328 6340 IPython mode and without IPython at all.
6329 6341 For an embedded shell (see sec.
6330 6342
6331 6343 \begin_inset LatexCommand \ref{sec:embed}
6332 6344
6333 6345 \end_inset
6334 6346
6335 6347 ), simply call the constructor with
6336 6348 \family typewriter
6337 6349 `-pdb'
6338 6350 \family default
6339 6351 in the argument string and automatically
6340 6352 \family typewriter
6341 6353 pdb
6342 6354 \family default
6343 6355 will be called if an uncaught exception is triggered by your code.
6344 6356
6345 6357 \layout Standard
6346 6358
6347 6359 For stand-alone use of the feature in your programs which do not use IPython
6348 6360 at all, put the following lines toward the top of your `main' routine:
6349 6361 \layout Standard
6350 6362 \align left
6351 6363
6352 6364 \family typewriter
6353 6365 import sys,IPython.ultraTB
6354 6366 \newline
6355 6367 sys.excepthook = IPython.ultraTB.FormattedTB(mode=`Verbose', color_scheme=`Linux',
6356 6368 call_pdb=1)
6357 6369 \layout Standard
6358 6370
6359 6371 The
6360 6372 \family typewriter
6361 6373 mode
6362 6374 \family default
6363 6375 keyword can be either
6364 6376 \family typewriter
6365 6377 `Verbose'
6366 6378 \family default
6367 6379 or
6368 6380 \family typewriter
6369 6381 `Plain'
6370 6382 \family default
6371 6383 , giving either very detailed or normal tracebacks respectively.
6372 6384 The
6373 6385 \family typewriter
6374 6386 color_scheme
6375 6387 \family default
6376 6388 keyword can be one of
6377 6389 \family typewriter
6378 6390 `NoColor'
6379 6391 \family default
6380 6392 ,
6381 6393 \family typewriter
6382 6394 `Linux'
6383 6395 \family default
6384 6396 (default) or
6385 6397 \family typewriter
6386 6398 `LightBG'
6387 6399 \family default
6388 6400 .
6389 6401 These are the same options which can be set in IPython with
6390 6402 \family typewriter
6391 6403 -colors
6392 6404 \family default
6393 6405 and
6394 6406 \family typewriter
6395 6407 -xmode
6396 6408 \family default
6397 6409 .
6398 6410 \layout Standard
6399 6411
6400 6412 This will give any of your programs detailed, colored tracebacks with automatic
6401 6413 invocation of
6402 6414 \family typewriter
6403 6415 pdb
6404 6416 \family default
6405 6417 .
6406 6418 \layout Section
6407 6419
6408 6420
6409 6421 \begin_inset LatexCommand \label{sec:syntax-extensions}
6410 6422
6411 6423 \end_inset
6412 6424
6413 6425 Extensions for syntax processing
6414 6426 \layout Standard
6415 6427
6416 6428 This isn't for the faint of heart, because the potential for breaking things
6417 6429 is quite high.
6418 6430 But it can be a very powerful and useful feature.
6419 6431 In a nutshell, you can redefine the way IPython processes the user input
6420 6432 line to accept new, special extensions to the syntax without needing to
6421 6433 change any of IPython's own code.
6422 6434 \layout Standard
6423 6435
6424 6436 In the
6425 6437 \family typewriter
6426 6438 IPython/Extensions
6427 6439 \family default
6428 6440 directory you will find some examples supplied, which we will briefly describe
6429 6441 now.
6430 6442 These can be used `as is' (and both provide very useful functionality),
6431 6443 or you can use them as a starting point for writing your own extensions.
6432 6444 \layout Subsection
6433 6445
6434 6446 Pasting of code starting with
6435 6447 \family typewriter
6436 6448 `>>>
6437 6449 \family default
6438 6450 ' or
6439 6451 \family typewriter
6440 6452 `...
6441 6453
6442 6454 \family default
6443 6455 '
6444 6456 \layout Standard
6445 6457
6446 6458 In the python tutorial it is common to find code examples which have been
6447 6459 taken from real python sessions.
6448 6460 The problem with those is that all the lines begin with either
6449 6461 \family typewriter
6450 6462 `>>>
6451 6463 \family default
6452 6464 ' or
6453 6465 \family typewriter
6454 6466 `...
6455 6467
6456 6468 \family default
6457 6469 ', which makes it impossible to paste them all at once.
6458 6470 One must instead do a line by line manual copying, carefully removing the
6459 6471 leading extraneous characters.
6460 6472 \layout Standard
6461 6473
6462 6474 This extension identifies those starting characters and removes them from
6463 6475 the input automatically, so that one can paste multi-line examples directly
6464 6476 into IPython, saving a lot of time.
6465 6477 Please look at the file
6466 6478 \family typewriter
6467 6479 InterpreterPasteInput.py
6468 6480 \family default
6469 6481 in the
6470 6482 \family typewriter
6471 6483 IPython/Extensions
6472 6484 \family default
6473 6485 directory for details on how this is done.
6474 6486 \layout Standard
6475 6487
6476 6488 IPython comes with a special profile enabling this feature, called
6477 6489 \family typewriter
6478 6490 tutorial
6479 6491 \family default
6480 6492 \emph on
6481 6493 .
6482 6494
6483 6495 \emph default
6484 6496 Simply start IPython via
6485 6497 \family typewriter
6486 6498 `ipython\SpecialChar ~
6487 6499 -p\SpecialChar ~
6488 6500 tutorial'
6489 6501 \family default
6490 6502 and the feature will be available.
6491 6503 In a normal IPython session you can activate the feature by importing the
6492 6504 corresponding module with:
6493 6505 \newline
6494 6506
6495 6507 \family typewriter
6496 6508 In [1]: import IPython.Extensions.InterpreterPasteInput
6497 6509 \layout Standard
6498 6510
6499 6511 The following is a 'screenshot' of how things work when this extension is
6500 6512 on, copying an example from the standard tutorial:
6501 6513 \layout Standard
6502 6514
6503 6515
6504 6516 \family typewriter
6505 6517 IPython profile: tutorial
6506 6518 \newline
6507 6519 \SpecialChar ~
6508 6520
6509 6521 \newline
6510 6522 *** Pasting of code with ">>>" or "..." has been enabled.
6511 6523 \newline
6512 6524 \SpecialChar ~
6513 6525
6514 6526 \newline
6515 6527 In [1]: >>> def fib2(n): # return Fibonacci series up to n
6516 6528 \newline
6517 6529
6518 6530 \begin_inset ERT
6519 6531 status Collapsed
6520 6532
6521 6533 \layout Standard
6522 6534
6523 6535 \backslash
6524 6536 hspace*{0mm}
6525 6537 \end_inset
6526 6538
6527 6539 \SpecialChar ~
6528 6540 \SpecialChar ~
6529 6541 ...: ...\SpecialChar ~
6530 6542 \SpecialChar ~
6531 6543 \SpecialChar ~
6532 6544 \SpecialChar ~
6533 6545 """Return a list containing the Fibonacci series up to n."""
6534 6546 \newline
6535 6547
6536 6548 \begin_inset ERT
6537 6549 status Collapsed
6538 6550
6539 6551 \layout Standard
6540 6552
6541 6553 \backslash
6542 6554 hspace*{0mm}
6543 6555 \end_inset
6544 6556
6545 6557 \SpecialChar ~
6546 6558 \SpecialChar ~
6547 6559 ...: ...\SpecialChar ~
6548 6560 \SpecialChar ~
6549 6561 \SpecialChar ~
6550 6562 \SpecialChar ~
6551 6563 result = []
6552 6564 \newline
6553 6565
6554 6566 \begin_inset ERT
6555 6567 status Collapsed
6556 6568
6557 6569 \layout Standard
6558 6570
6559 6571 \backslash
6560 6572 hspace*{0mm}
6561 6573 \end_inset
6562 6574
6563 6575 \SpecialChar ~
6564 6576 \SpecialChar ~
6565 6577 ...: ...\SpecialChar ~
6566 6578 \SpecialChar ~
6567 6579 \SpecialChar ~
6568 6580 \SpecialChar ~
6569 6581 a, b = 0, 1
6570 6582 \newline
6571 6583
6572 6584 \begin_inset ERT
6573 6585 status Collapsed
6574 6586
6575 6587 \layout Standard
6576 6588
6577 6589 \backslash
6578 6590 hspace*{0mm}
6579 6591 \end_inset
6580 6592
6581 6593 \SpecialChar ~
6582 6594 \SpecialChar ~
6583 6595 ...: ...\SpecialChar ~
6584 6596 \SpecialChar ~
6585 6597 \SpecialChar ~
6586 6598 \SpecialChar ~
6587 6599 while b < n:
6588 6600 \newline
6589 6601
6590 6602 \begin_inset ERT
6591 6603 status Collapsed
6592 6604
6593 6605 \layout Standard
6594 6606
6595 6607 \backslash
6596 6608 hspace*{0mm}
6597 6609 \end_inset
6598 6610
6599 6611 \SpecialChar ~
6600 6612 \SpecialChar ~
6601 6613 ...: ...\SpecialChar ~
6602 6614 \SpecialChar ~
6603 6615 \SpecialChar ~
6604 6616 \SpecialChar ~
6605 6617 \SpecialChar ~
6606 6618 \SpecialChar ~
6607 6619 \SpecialChar ~
6608 6620 \SpecialChar ~
6609 6621 result.append(b)\SpecialChar ~
6610 6622 \SpecialChar ~
6611 6623 \SpecialChar ~
6612 6624 # see below
6613 6625 \newline
6614 6626
6615 6627 \begin_inset ERT
6616 6628 status Collapsed
6617 6629
6618 6630 \layout Standard
6619 6631
6620 6632 \backslash
6621 6633 hspace*{0mm}
6622 6634 \end_inset
6623 6635
6624 6636 \SpecialChar ~
6625 6637 \SpecialChar ~
6626 6638 ...: ...\SpecialChar ~
6627 6639 \SpecialChar ~
6628 6640 \SpecialChar ~
6629 6641 \SpecialChar ~
6630 6642 \SpecialChar ~
6631 6643 \SpecialChar ~
6632 6644 \SpecialChar ~
6633 6645 \SpecialChar ~
6634 6646 a, b = b, a+b
6635 6647 \newline
6636 6648
6637 6649 \begin_inset ERT
6638 6650 status Collapsed
6639 6651
6640 6652 \layout Standard
6641 6653
6642 6654 \backslash
6643 6655 hspace*{0mm}
6644 6656 \end_inset
6645 6657
6646 6658 \SpecialChar ~
6647 6659 \SpecialChar ~
6648 6660 ...: ...\SpecialChar ~
6649 6661 \SpecialChar ~
6650 6662 \SpecialChar ~
6651 6663 \SpecialChar ~
6652 6664 return result
6653 6665 \newline
6654 6666
6655 6667 \begin_inset ERT
6656 6668 status Collapsed
6657 6669
6658 6670 \layout Standard
6659 6671
6660 6672 \backslash
6661 6673 hspace*{0mm}
6662 6674 \end_inset
6663 6675
6664 6676 \SpecialChar ~
6665 6677 \SpecialChar ~
6666 6678 ...:
6667 6679 \newline
6668 6680 \SpecialChar ~
6669 6681
6670 6682 \newline
6671 6683 In [2]: fib2(10)
6672 6684 \newline
6673 6685 Out[2]: [1, 1, 2, 3, 5, 8]
6674 6686 \layout Standard
6675 6687
6676 6688 Note that as currently written, this extension does
6677 6689 \emph on
6678 6690 not
6679 6691 \emph default
6680 6692 recognize IPython's prompts for pasting.
6681 6693 Those are more complicated, since the user can change them very easily,
6682 6694 they involve numbers and can vary in length.
6683 6695 One could however extract all the relevant information from the IPython
6684 6696 instance and build an appropriate regular expression.
6685 6697 This is left as an exercise for the reader.
6686 6698 \layout Subsection
6687 6699
6688 6700 Input of physical quantities with units
6689 6701 \layout Standard
6690 6702
6691 6703 The module
6692 6704 \family typewriter
6693 6705 PhysicalQInput
6694 6706 \family default
6695 6707 allows a simplified form of input for physical quantities with units.
6696 6708 This file is meant to be used in conjunction with the
6697 6709 \family typewriter
6698 6710 PhysicalQInteractive
6699 6711 \family default
6700 6712 module (in the same directory) and
6701 6713 \family typewriter
6702 6714 Physics.PhysicalQuantities
6703 6715 \family default
6704 6716 from Konrad Hinsen's ScientificPython (
6705 6717 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/hinsen/scientific.html}
6706 6718
6707 6719 \end_inset
6708 6720
6709 6721 ).
6710 6722 \layout Standard
6711 6723
6712 6724 The
6713 6725 \family typewriter
6714 6726 Physics.PhysicalQuantities
6715 6727 \family default
6716 6728 module defines
6717 6729 \family typewriter
6718 6730 PhysicalQuantity
6719 6731 \family default
6720 6732 objects, but these must be declared as instances of a class.
6721 6733 For example, to define
6722 6734 \family typewriter
6723 6735 v
6724 6736 \family default
6725 6737 as a velocity of 3\SpecialChar ~
6726 6738 m/s, normally you would write:
6727 6739 \family typewriter
6728 6740
6729 6741 \newline
6730 6742 In [1]: v = PhysicalQuantity(3,'m/s')
6731 6743 \layout Standard
6732 6744
6733 6745 Using the
6734 6746 \family typewriter
6735 6747 PhysicalQ_Input
6736 6748 \family default
6737 6749 extension this can be input instead as:
6738 6750 \family typewriter
6739 6751
6740 6752 \newline
6741 6753 In [1]: v = 3 m/s
6742 6754 \family default
6743 6755
6744 6756 \newline
6745 6757 which is much more convenient for interactive use (even though it is blatantly
6746 6758 invalid Python syntax).
6747 6759 \layout Standard
6748 6760
6749 6761 The
6750 6762 \family typewriter
6751 6763 physics
6752 6764 \family default
6753 6765 profile supplied with IPython (enabled via
6754 6766 \family typewriter
6755 6767 'ipython -p physics'
6756 6768 \family default
6757 6769 ) uses these extensions, which you can also activate with:
6758 6770 \layout Standard
6759 6771
6760 6772
6761 6773 \family typewriter
6762 6774 from math import * # math MUST be imported BEFORE PhysicalQInteractive
6763 6775 \newline
6764 6776 from IPython.Extensions.PhysicalQInteractive import *
6765 6777 \newline
6766 6778 import IPython.Extensions.PhysicalQInput
6767 6779 \layout Section
6768 6780
6769 6781 IPython as a system shell
6770 6782 \layout Standard
6771 6783
6772 6784 IPython ships with a special profile called
6773 6785 \family typewriter
6774 6786 pysh
6775 6787 \family default
6776 6788 , which you can activate at the command line as
6777 6789 \family typewriter
6778 6790 `ipython -p pysh'
6779 6791 \family default
6780 6792 .
6781 6793 This loads
6782 6794 \family typewriter
6783 6795 InterpreterExec
6784 6796 \family default
6785 6797 , along with some additional facilities and a prompt customized for filesystem
6786 6798 navigation.
6787 6799 \layout Standard
6788 6800
6789 6801 Note that this does
6790 6802 \emph on
6791 6803 not
6792 6804 \emph default
6793 6805 make IPython a full-fledged system shell.
6794 6806 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
6795 6807 you'll suspend pysh itself, not the process you just started.
6796 6808
6797 6809 \layout Standard
6798 6810
6799 6811 What the shell profile allows you to do is to use the convenient and powerful
6800 6812 syntax of Python to do quick scripting at the command line.
6801 6813 Below we describe some of its features.
6802 6814 \layout Subsection
6803 6815
6804 6816 Aliases
6805 6817 \layout Standard
6806 6818
6807 6819 All of your
6808 6820 \family typewriter
6809 6821 $PATH
6810 6822 \family default
6811 6823 has been loaded as IPython aliases, so you should be able to type any normal
6812 6824 system command and have it executed.
6813 6825 See
6814 6826 \family typewriter
6815 6827 %alias?
6816 6828 \family default
6817 6829 and
6818 6830 \family typewriter
6819 6831 %unalias?
6820 6832 \family default
6821 6833 for details on the alias facilities.
6822 6834 See also
6823 6835 \family typewriter
6824 6836 %rehash?
6825 6837 \family default
6826 6838 and
6827 6839 \family typewriter
6828 6840 %rehashx?
6829 6841 \family default
6830 6842 for details on the mechanism used to load
6831 6843 \family typewriter
6832 6844 $PATH
6833 6845 \family default
6834 6846 .
6835 6847 \layout Subsection
6836 6848
6837 6849 Special syntax
6838 6850 \layout Standard
6839 6851
6840 6852 Any lines which begin with
6841 6853 \family typewriter
6842 6854 `~'
6843 6855 \family default
6844 6856 ,
6845 6857 \family typewriter
6846 6858 `/'
6847 6859 \family default
6848 6860 and
6849 6861 \family typewriter
6850 6862 `.'
6851 6863 \family default
6852 6864 will be executed as shell commands instead of as Python code.
6853 6865 The special escapes below are also recognized.
6854 6866
6855 6867 \family typewriter
6856 6868 !cmd
6857 6869 \family default
6858 6870 is valid in single or multi-line input, all others are only valid in single-lin
6859 6871 e input:
6860 6872 \layout Description
6861 6873
6862 6874
6863 6875 \family typewriter
6864 6876 !cmd
6865 6877 \family default
6866 6878 pass `cmd' directly to the shell
6867 6879 \layout Description
6868 6880
6869 6881
6870 6882 \family typewriter
6871 6883 !!cmd
6872 6884 \family default
6873 6885 execute `cmd' and return output as a list (split on `
6874 6886 \backslash
6875 6887 n')
6876 6888 \layout Description
6877 6889
6878 6890
6879 6891 \family typewriter
6880 6892 $var=cmd
6881 6893 \family default
6882 6894 capture output of cmd into var, as a string
6883 6895 \layout Description
6884 6896
6885 6897
6886 6898 \family typewriter
6887 6899 $$var=cmd
6888 6900 \family default
6889 6901 capture output of cmd into var, as a list (split on `
6890 6902 \backslash
6891 6903 n')
6892 6904 \layout Standard
6893 6905
6894 6906 The
6895 6907 \family typewriter
6896 6908 $
6897 6909 \family default
6898 6910 /
6899 6911 \family typewriter
6900 6912 $$
6901 6913 \family default
6902 6914 syntaxes make Python variables from system output, which you can later
6903 6915 use for further scripting.
6904 6916 The converse is also possible: when executing an alias or calling to the
6905 6917 system via
6906 6918 \family typewriter
6907 6919 !
6908 6920 \family default
6909 6921 /
6910 6922 \family typewriter
6911 6923 !!
6912 6924 \family default
6913 6925 , you can expand any python variable or expression by prepending it with
6914 6926
6915 6927 \family typewriter
6916 6928 $
6917 6929 \family default
6918 6930 .
6919 6931 Full details of the allowed syntax can be found in Python's PEP 215.
6920 6932 \layout Standard
6921 6933
6922 6934 A few brief examples will illustrate these (note that the indentation below
6923 6935 may be incorrectly displayed):
6924 6936 \layout Standard
6925 6937
6926 6938
6927 6939 \family typewriter
6928 6940 fperez[~/test]|3> !ls *s.py
6929 6941 \newline
6930 6942 scopes.py strings.py
6931 6943 \layout Standard
6932 6944
6933 6945 ls is an internal alias, so there's no need to use
6934 6946 \family typewriter
6935 6947 !
6936 6948 \family default
6937 6949 :
6938 6950 \layout Standard
6939 6951
6940 6952
6941 6953 \family typewriter
6942 6954 fperez[~/test]|4> ls *s.py
6943 6955 \newline
6944 6956 scopes.py* strings.py
6945 6957 \layout Standard
6946 6958
6947 6959 !!ls will return the output into a Python variable:
6948 6960 \layout Standard
6949 6961
6950 6962
6951 6963 \family typewriter
6952 6964 fperez[~/test]|5> !!ls *s.py
6953 6965 \newline
6954 6966
6955 6967 \begin_inset ERT
6956 6968 status Collapsed
6957 6969
6958 6970 \layout Standard
6959 6971
6960 6972 \backslash
6961 6973 hspace*{0mm}
6962 6974 \end_inset
6963 6975
6964 6976 \SpecialChar ~
6965 6977 \SpecialChar ~
6966 6978 \SpecialChar ~
6967 6979 \SpecialChar ~
6968 6980 \SpecialChar ~
6969 6981 \SpecialChar ~
6970 6982 \SpecialChar ~
6971 6983 \SpecialChar ~
6972 6984 \SpecialChar ~
6973 6985 \SpecialChar ~
6974 6986 \SpecialChar ~
6975 6987 \SpecialChar ~
6976 6988 \SpecialChar ~
6977 6989 \SpecialChar ~
6978 6990 <5> ['scopes.py', 'strings.py']
6979 6991 \newline
6980 6992 fperez[~/test]|6> print _5
6981 6993 \newline
6982 6994 ['scopes.py', 'strings.py']
6983 6995 \layout Standard
6984 6996
6985 6997
6986 6998 \family typewriter
6987 6999 $
6988 7000 \family default
6989 7001 and
6990 7002 \family typewriter
6991 7003 $$
6992 7004 \family default
6993 7005 allow direct capture to named variables:
6994 7006 \layout Standard
6995 7007
6996 7008
6997 7009 \family typewriter
6998 7010 fperez[~/test]|7> $astr = ls *s.py
6999 7011 \newline
7000 7012 fperez[~/test]|8> astr
7001 7013 \newline
7002 7014
7003 7015 \begin_inset ERT
7004 7016 status Collapsed
7005 7017
7006 7018 \layout Standard
7007 7019
7008 7020 \backslash
7009 7021 hspace*{0mm}
7010 7022 \end_inset
7011 7023
7012 7024 \SpecialChar ~
7013 7025 \SpecialChar ~
7014 7026 \SpecialChar ~
7015 7027 \SpecialChar ~
7016 7028 \SpecialChar ~
7017 7029 \SpecialChar ~
7018 7030 \SpecialChar ~
7019 7031 \SpecialChar ~
7020 7032 \SpecialChar ~
7021 7033 \SpecialChar ~
7022 7034 \SpecialChar ~
7023 7035 \SpecialChar ~
7024 7036 \SpecialChar ~
7025 7037 \SpecialChar ~
7026 7038 <8> 'scopes.py
7027 7039 \backslash
7028 7040 nstrings.py'
7029 7041 \layout Standard
7030 7042
7031 7043
7032 7044 \family typewriter
7033 7045 fperez[~/test]|9> $$alist = ls *s.py
7034 7046 \newline
7035 7047 fperez[~/test]|10> alist
7036 7048 \newline
7037 7049
7038 7050 \begin_inset ERT
7039 7051 status Collapsed
7040 7052
7041 7053 \layout Standard
7042 7054
7043 7055 \backslash
7044 7056 hspace*{0mm}
7045 7057 \end_inset
7046 7058
7047 7059 \SpecialChar ~
7048 7060 \SpecialChar ~
7049 7061 \SpecialChar ~
7050 7062 \SpecialChar ~
7051 7063 \SpecialChar ~
7052 7064 \SpecialChar ~
7053 7065 \SpecialChar ~
7054 7066 \SpecialChar ~
7055 7067 \SpecialChar ~
7056 7068 \SpecialChar ~
7057 7069 \SpecialChar ~
7058 7070 \SpecialChar ~
7059 7071 \SpecialChar ~
7060 7072 \SpecialChar ~
7061 7073 <10> ['scopes.py', 'strings.py']
7062 7074 \layout Standard
7063 7075
7064 7076 alist is now a normal python list you can loop over.
7065 7077 Using
7066 7078 \family typewriter
7067 7079 $
7068 7080 \family default
7069 7081 will expand back the python values when alias calls are made:
7070 7082 \layout Standard
7071 7083
7072 7084
7073 7085 \family typewriter
7074 7086 fperez[~/test]|11> for f in alist:
7075 7087 \newline
7076 7088
7077 7089 \begin_inset ERT
7078 7090 status Collapsed
7079 7091
7080 7092 \layout Standard
7081 7093
7082 7094 \backslash
7083 7095 hspace*{0mm}
7084 7096 \end_inset
7085 7097
7086 7098 \SpecialChar ~
7087 7099 \SpecialChar ~
7088 7100 \SpecialChar ~
7089 7101 \SpecialChar ~
7090 7102 \SpecialChar ~
7091 7103 \SpecialChar ~
7092 7104 \SpecialChar ~
7093 7105 \SpecialChar ~
7094 7106 \SpecialChar ~
7095 7107 \SpecialChar ~
7096 7108 \SpecialChar ~
7097 7109 \SpecialChar ~
7098 7110 \SpecialChar ~
7099 7111 \SpecialChar ~
7100 7112 |..> \SpecialChar ~
7101 7113 \SpecialChar ~
7102 7114 \SpecialChar ~
7103 7115 \SpecialChar ~
7104 7116 print 'file',f,
7105 7117 \newline
7106 7118
7107 7119 \begin_inset ERT
7108 7120 status Collapsed
7109 7121
7110 7122 \layout Standard
7111 7123
7112 7124 \backslash
7113 7125 hspace*{0mm}
7114 7126 \end_inset
7115 7127
7116 7128 \SpecialChar ~
7117 7129 \SpecialChar ~
7118 7130 \SpecialChar ~
7119 7131 \SpecialChar ~
7120 7132 \SpecialChar ~
7121 7133 \SpecialChar ~
7122 7134 \SpecialChar ~
7123 7135 \SpecialChar ~
7124 7136 \SpecialChar ~
7125 7137 \SpecialChar ~
7126 7138 \SpecialChar ~
7127 7139 \SpecialChar ~
7128 7140 \SpecialChar ~
7129 7141 \SpecialChar ~
7130 7142 |..> \SpecialChar ~
7131 7143 \SpecialChar ~
7132 7144 \SpecialChar ~
7133 7145 \SpecialChar ~
7134 7146 wc -l $f
7135 7147 \newline
7136 7148
7137 7149 \begin_inset ERT
7138 7150 status Collapsed
7139 7151
7140 7152 \layout Standard
7141 7153
7142 7154 \backslash
7143 7155 hspace*{0mm}
7144 7156 \end_inset
7145 7157
7146 7158 \SpecialChar ~
7147 7159 \SpecialChar ~
7148 7160 \SpecialChar ~
7149 7161 \SpecialChar ~
7150 7162 \SpecialChar ~
7151 7163 \SpecialChar ~
7152 7164 \SpecialChar ~
7153 7165 \SpecialChar ~
7154 7166 \SpecialChar ~
7155 7167 \SpecialChar ~
7156 7168 \SpecialChar ~
7157 7169 \SpecialChar ~
7158 7170 \SpecialChar ~
7159 7171 \SpecialChar ~
7160 7172 |..>
7161 7173 \newline
7162 7174 file scopes.py 13 scopes.py
7163 7175 \newline
7164 7176 file strings.py 4 strings.py
7165 7177 \layout Standard
7166 7178
7167 7179 Note that you may need to protect your variables with braces if you want
7168 7180 to append strings to their names.
7169 7181 To copy all files in alist to
7170 7182 \family typewriter
7171 7183 .bak
7172 7184 \family default
7173 7185 extensions, you must use:
7174 7186 \layout Standard
7175 7187
7176 7188
7177 7189 \family typewriter
7178 7190 fperez[~/test]|12> for f in alist:
7179 7191 \newline
7180 7192
7181 7193 \begin_inset ERT
7182 7194 status Collapsed
7183 7195
7184 7196 \layout Standard
7185 7197
7186 7198 \backslash
7187 7199 hspace*{0mm}
7188 7200 \end_inset
7189 7201
7190 7202 \SpecialChar ~
7191 7203 \SpecialChar ~
7192 7204 \SpecialChar ~
7193 7205 \SpecialChar ~
7194 7206 \SpecialChar ~
7195 7207 \SpecialChar ~
7196 7208 \SpecialChar ~
7197 7209 \SpecialChar ~
7198 7210 \SpecialChar ~
7199 7211 \SpecialChar ~
7200 7212 \SpecialChar ~
7201 7213 \SpecialChar ~
7202 7214 \SpecialChar ~
7203 7215 \SpecialChar ~
7204 7216 |..> \SpecialChar ~
7205 7217 \SpecialChar ~
7206 7218 \SpecialChar ~
7207 7219 \SpecialChar ~
7208 7220 cp $f ${f}.bak
7209 7221 \layout Standard
7210 7222
7211 7223 If you try using
7212 7224 \family typewriter
7213 7225 $f.bak
7214 7226 \family default
7215 7227 , you'll get an AttributeError exception saying that your string object
7216 7228 doesn't have a
7217 7229 \family typewriter
7218 7230 .bak
7219 7231 \family default
7220 7232 attribute.
7221 7233 This is because the
7222 7234 \family typewriter
7223 7235 $
7224 7236 \family default
7225 7237 expansion mechanism allows you to expand full Python expressions:
7226 7238 \layout Standard
7227 7239
7228 7240
7229 7241 \family typewriter
7230 7242 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
7231 7243 \newline
7232 7244 sys.platform is: linux2
7233 7245 \layout Standard
7234 7246
7235 7247 IPython's input history handling is still active, which allows you to rerun
7236 7248 a single block of multi-line input by simply using exec:
7237 7249 \newline
7238 7250
7239 7251 \family typewriter
7240 7252 fperez[~/test]|14> $$alist = ls *.eps
7241 7253 \newline
7242 7254 fperez[~/test]|15> exec _i11
7243 7255 \newline
7244 7256 file image2.eps 921 image2.eps
7245 7257 \newline
7246 7258 file image.eps 921 image.eps
7247 7259 \layout Standard
7248 7260
7249 7261 While these are new special-case syntaxes, they are designed to allow very
7250 7262 efficient use of the shell with minimal typing.
7251 7263 At an interactive shell prompt, conciseness of expression wins over readability.
7252 7264 \layout Subsection
7253 7265
7254 7266 Useful functions and modules
7255 7267 \layout Standard
7256 7268
7257 7269 The os, sys and shutil modules from the Python standard library are automaticall
7258 7270 y loaded.
7259 7271 Some additional functions, useful for shell usage, are listed below.
7260 7272 You can request more help about them with `
7261 7273 \family typewriter
7262 7274 ?
7263 7275 \family default
7264 7276 '.
7265 7277 \layout Description
7266 7278
7267 7279
7268 7280 \family typewriter
7269 7281 shell
7270 7282 \family default
7271 7283 - execute a command in the underlying system shell
7272 7284 \layout Description
7273 7285
7274 7286
7275 7287 \family typewriter
7276 7288 system
7277 7289 \family default
7278 7290 - like
7279 7291 \family typewriter
7280 7292 shell()
7281 7293 \family default
7282 7294 , but return the exit status of the command
7283 7295 \layout Description
7284 7296
7285 7297
7286 7298 \family typewriter
7287 7299 sout
7288 7300 \family default
7289 7301 - capture the output of a command as a string
7290 7302 \layout Description
7291 7303
7292 7304
7293 7305 \family typewriter
7294 7306 lout
7295 7307 \family default
7296 7308 - capture the output of a command as a list (split on `
7297 7309 \backslash
7298 7310 n')
7299 7311 \layout Description
7300 7312
7301 7313
7302 7314 \family typewriter
7303 7315 getoutputerror
7304 7316 \family default
7305 7317 - capture (output,error) of a shell commandss
7306 7318 \layout Standard
7307 7319
7308 7320
7309 7321 \family typewriter
7310 7322 sout
7311 7323 \family default
7312 7324 /
7313 7325 \family typewriter
7314 7326 lout
7315 7327 \family default
7316 7328 are the functional equivalents of
7317 7329 \family typewriter
7318 7330 $
7319 7331 \family default
7320 7332 /
7321 7333 \family typewriter
7322 7334 $$
7323 7335 \family default
7324 7336 .
7325 7337 They are provided to allow you to capture system output in the middle of
7326 7338 true python code, function definitions, etc (where
7327 7339 \family typewriter
7328 7340 $
7329 7341 \family default
7330 7342 and
7331 7343 \family typewriter
7332 7344 $$
7333 7345 \family default
7334 7346 are invalid).
7335 7347 \layout Subsection
7336 7348
7337 7349 Directory management
7338 7350 \layout Standard
7339 7351
7340 7352 Since each command passed by pysh to the underlying system is executed in
7341 7353 a subshell which exits immediately, you can NOT use !cd to navigate the
7342 7354 filesystem.
7343 7355 \layout Standard
7344 7356
7345 7357 Pysh provides its own builtin
7346 7358 \family typewriter
7347 7359 `%cd
7348 7360 \family default
7349 7361 ' magic command to move in the filesystem (the
7350 7362 \family typewriter
7351 7363 %
7352 7364 \family default
7353 7365 is not required with automagic on).
7354 7366 It also maintains a list of visited directories (use
7355 7367 \family typewriter
7356 7368 %dhist
7357 7369 \family default
7358 7370 to see it) and allows direct switching to any of them.
7359 7371 Type
7360 7372 \family typewriter
7361 7373 `cd?
7362 7374 \family default
7363 7375 ' for more details.
7364 7376 \layout Standard
7365 7377
7366 7378
7367 7379 \family typewriter
7368 7380 %pushd
7369 7381 \family default
7370 7382 ,
7371 7383 \family typewriter
7372 7384 %popd
7373 7385 \family default
7374 7386 and
7375 7387 \family typewriter
7376 7388 %dirs
7377 7389 \family default
7378 7390 are provided for directory stack handling.
7379 7391 \layout Subsection
7380 7392
7381 7393 Prompt customization
7382 7394 \layout Standard
7383 7395
7384 7396 The supplied
7385 7397 \family typewriter
7386 7398 ipythonrc-pysh
7387 7399 \family default
7388 7400 profile comes with an example of a very colored and detailed prompt, mainly
7389 7401 to serve as an illustration.
7390 7402 The valid escape sequences, besides color names, are:
7391 7403 \layout Description
7392 7404
7393 7405
7394 7406 \backslash
7395 7407 # - Prompt number.
7396 7408 \layout Description
7397 7409
7398 7410
7399 7411 \backslash
7400 7412 D - Dots, as many as there are digits in
7401 7413 \backslash
7402 7414 # (so they align).
7403 7415 \layout Description
7404 7416
7405 7417
7406 7418 \backslash
7407 7419 w - Current working directory (cwd).
7408 7420 \layout Description
7409 7421
7410 7422
7411 7423 \backslash
7412 7424 W - Basename of current working directory.
7413 7425 \layout Description
7414 7426
7415 7427
7416 7428 \backslash
7417 7429 X
7418 7430 \emph on
7419 7431 N
7420 7432 \emph default
7421 7433 - Where
7422 7434 \emph on
7423 7435 N
7424 7436 \emph default
7425 7437 =0..5.
7426 7438 N terms of the cwd, with $HOME written as ~.
7427 7439 \layout Description
7428 7440
7429 7441
7430 7442 \backslash
7431 7443 Y
7432 7444 \emph on
7433 7445 N
7434 7446 \emph default
7435 7447 - Where
7436 7448 \emph on
7437 7449 N
7438 7450 \emph default
7439 7451 =0..5.
7440 7452 Like X
7441 7453 \emph on
7442 7454 N
7443 7455 \emph default
7444 7456 , but if ~ is term
7445 7457 \emph on
7446 7458 N
7447 7459 \emph default
7448 7460 +1 it's also shown.
7449 7461 \layout Description
7450 7462
7451 7463
7452 7464 \backslash
7453 7465 u - Username.
7454 7466 \layout Description
7455 7467
7456 7468
7457 7469 \backslash
7458 7470 H - Full hostname.
7459 7471 \layout Description
7460 7472
7461 7473
7462 7474 \backslash
7463 7475 h - Hostname up to first '.'
7464 7476 \layout Description
7465 7477
7466 7478
7467 7479 \backslash
7468 7480 $ - Root symbol ($ or #).
7469 7481
7470 7482 \layout Description
7471 7483
7472 7484
7473 7485 \backslash
7474 7486 t - Current time, in H:M:S format.
7475 7487 \layout Description
7476 7488
7477 7489
7478 7490 \backslash
7479 7491 v - IPython release version.
7480 7492
7481 7493 \layout Description
7482 7494
7483 7495
7484 7496 \backslash
7485 7497 n - Newline.
7486 7498
7487 7499 \layout Description
7488 7500
7489 7501
7490 7502 \backslash
7491 7503 r - Carriage return.
7492 7504
7493 7505 \layout Description
7494 7506
7495 7507
7496 7508 \backslash
7497 7509
7498 7510 \backslash
7499 7511 - An explicitly escaped '
7500 7512 \backslash
7501 7513 '.
7502 7514 \layout Standard
7503 7515
7504 7516 You can configure your prompt colors using any ANSI color escape.
7505 7517 Each color escape sets the color for any subsequent text, until another
7506 7518 escape comes in and changes things.
7507 7519 The valid color escapes are:
7508 7520 \layout Description
7509 7521
7510 7522
7511 7523 \backslash
7512 7524 C_Black
7513 7525 \layout Description
7514 7526
7515 7527
7516 7528 \backslash
7517 7529 C_Blue
7518 7530 \layout Description
7519 7531
7520 7532
7521 7533 \backslash
7522 7534 C_Brown
7523 7535 \layout Description
7524 7536
7525 7537
7526 7538 \backslash
7527 7539 C_Cyan
7528 7540 \layout Description
7529 7541
7530 7542
7531 7543 \backslash
7532 7544 C_DarkGray
7533 7545 \layout Description
7534 7546
7535 7547
7536 7548 \backslash
7537 7549 C_Green
7538 7550 \layout Description
7539 7551
7540 7552
7541 7553 \backslash
7542 7554 C_LightBlue
7543 7555 \layout Description
7544 7556
7545 7557
7546 7558 \backslash
7547 7559 C_LightCyan
7548 7560 \layout Description
7549 7561
7550 7562
7551 7563 \backslash
7552 7564 C_LightGray
7553 7565 \layout Description
7554 7566
7555 7567
7556 7568 \backslash
7557 7569 C_LightGreen
7558 7570 \layout Description
7559 7571
7560 7572
7561 7573 \backslash
7562 7574 C_LightPurple
7563 7575 \layout Description
7564 7576
7565 7577
7566 7578 \backslash
7567 7579 C_LightRed
7568 7580 \layout Description
7569 7581
7570 7582
7571 7583 \backslash
7572 7584 C_Purple
7573 7585 \layout Description
7574 7586
7575 7587
7576 7588 \backslash
7577 7589 C_Red
7578 7590 \layout Description
7579 7591
7580 7592
7581 7593 \backslash
7582 7594 C_White
7583 7595 \layout Description
7584 7596
7585 7597
7586 7598 \backslash
7587 7599 C_Yellow
7588 7600 \layout Description
7589 7601
7590 7602
7591 7603 \backslash
7592 7604 C_Normal Stop coloring, defaults to your terminal settings.
7593 7605 \layout Section
7594 7606
7595 7607
7596 7608 \begin_inset LatexCommand \label{sec:Threading-support}
7597 7609
7598 7610 \end_inset
7599 7611
7600 7612 Threading support
7601 7613 \layout Standard
7602 7614
7603 7615
7604 7616 \series bold
7605 7617 WARNING:
7606 7618 \series default
7607 7619 The threading support is still somewhat experimental, and it has only seen
7608 7620 reasonable testing under Linux.
7609 7621 Threaded code is particularly tricky to debug, and it tends to show extremely
7610 7622 platform-dependent behavior.
7611 7623 Since I only have access to Linux machines, I will have to rely on user's
7612 7624 experiences and assistance for this area of IPython to improve under other
7613 7625 platforms.
7614 7626 \layout Standard
7615 7627
7616 7628 IPython, via the
7617 7629 \family typewriter
7618 7630 -gthread
7619 7631 \family default
7620 7632 ,
7621 7633 \family typewriter
7622 7634 -qthread
7623 7635 \family default
7624 7636 and
7625 7637 \family typewriter
7626 7638 -wthread
7627 7639 \family default
7628 7640 options (described in Sec.\SpecialChar ~
7629 7641
7630 7642 \begin_inset LatexCommand \ref{sec:threading-opts}
7631 7643
7632 7644 \end_inset
7633 7645
7634 7646 ), can run in multithreaded mode to support pyGTK, Qt and WXPython applications
7635 7647 respectively.
7636 7648 These GUI toolkits need to control the python main loop of execution, so
7637 7649 under a normal Python interpreter, starting a pyGTK, Qt or WXPython application
7638 7650 will immediately freeze the shell.
7639 7651
7640 7652 \layout Standard
7641 7653
7642 7654 IPython, with one of these options (you can only use one at a time), separates
7643 7655 the graphical loop and IPython's code execution run into different threads.
7644 7656 This allows you to test interactively (with
7645 7657 \family typewriter
7646 7658 %run
7647 7659 \family default
7648 7660 , for example) your GUI code without blocking.
7649 7661 \layout Standard
7650 7662
7651 7663 A nice mini-tutorial on using IPython along with the Qt Designer application
7652 7664 is available at the SciPy wiki:
7653 7665 \begin_inset LatexCommand \htmlurl{http://www.scipy.org/wikis/topical_software/QtWithIPythonAndDesigner}
7654 7666
7655 7667 \end_inset
7656 7668
7657 7669 .
7658 7670 \layout Subsection
7659 7671
7660 7672 Tk issues
7661 7673 \layout Standard
7662 7674
7663 7675 As indicated in Sec.\SpecialChar ~
7664 7676
7665 7677 \begin_inset LatexCommand \ref{sec:threading-opts}
7666 7678
7667 7679 \end_inset
7668 7680
7669 7681 , a special
7670 7682 \family typewriter
7671 7683 -tk
7672 7684 \family default
7673 7685 option is provided to try and allow Tk graphical applications to coexist
7674 7686 interactively with WX, Qt or GTK ones.
7675 7687 Whether this works at all, however, is very platform and configuration
7676 7688 dependent.
7677 7689 Please experiment with simple test cases before committing to using this
7678 7690 combination of Tk and GTK/Qt/WX threading in a production environment.
7679 7691 \layout Subsection
7680 7692
7681 7693 Signals and Threads
7682 7694 \layout Standard
7683 7695
7684 7696 When any of the thread systems (GTK, Qt or WX) are active, either directly
7685 7697 or via
7686 7698 \family typewriter
7687 7699 -pylab
7688 7700 \family default
7689 7701 with a threaded backend, it is impossible to interrupt long-running Python
7690 7702 code via
7691 7703 \family typewriter
7692 7704 Ctrl-C
7693 7705 \family default
7694 7706 .
7695 7707 IPython can not pass the KeyboardInterrupt exception (or the underlying
7696 7708
7697 7709 \family typewriter
7698 7710 SIGINT
7699 7711 \family default
7700 7712 ) across threads, so any long-running process started from IPython will
7701 7713 run to completion, or will have to be killed via an external (OS-based)
7702 7714 mechanism.
7703 7715 \layout Standard
7704 7716
7705 7717 To the best of my knowledge, this limitation is imposed by the Python interprete
7706 7718 r itself, and it comes from the difficulty of writing portable signal/threaded
7707 7719 code.
7708 7720 If any user is an expert on this topic and can suggest a better solution,
7709 7721 I would love to hear about it.
7710 7722 In the IPython sources, look at the
7711 7723 \family typewriter
7712 7724 Shell.py
7713 7725 \family default
7714 7726 module, and in particular at the
7715 7727 \family typewriter
7716 7728 runcode()
7717 7729 \family default
7718 7730 method.
7719 7731
7720 7732 \layout Subsection
7721 7733
7722 7734 I/O pitfalls
7723 7735 \layout Standard
7724 7736
7725 7737 Be mindful that the Python interpreter switches between threads every
7726 7738 \begin_inset Formula $N$
7727 7739 \end_inset
7728 7740
7729 7741 bytecodes, where the default value as of Python\SpecialChar ~
7730 7742 2.3 is
7731 7743 \begin_inset Formula $N=100.$
7732 7744 \end_inset
7733 7745
7734 7746 This value can be read by using the
7735 7747 \family typewriter
7736 7748 sys.getcheckinterval()
7737 7749 \family default
7738 7750 function, and it can be reset via
7739 7751 \family typewriter
7740 7752 sys.setcheckinterval(
7741 7753 \emph on
7742 7754 N
7743 7755 \emph default
7744 7756 )
7745 7757 \family default
7746 7758 .
7747 7759 This switching of threads can cause subtly confusing effects if one of
7748 7760 your threads is doing file I/O.
7749 7761 In text mode, most systems only flush file buffers when they encounter
7750 7762 a
7751 7763 \family typewriter
7752 7764 `
7753 7765 \backslash
7754 7766 n'
7755 7767 \family default
7756 7768 .
7757 7769 An instruction as simple as
7758 7770 \family typewriter
7759 7771
7760 7772 \newline
7761 7773 \SpecialChar ~
7762 7774 \SpecialChar ~
7763 7775 print >> filehandle,
7764 7776 \begin_inset Quotes eld
7765 7777 \end_inset
7766 7778
7767 7779 hello world
7768 7780 \begin_inset Quotes erd
7769 7781 \end_inset
7770 7782
7771 7783
7772 7784 \family default
7773 7785
7774 7786 \newline
7775 7787 actually consists of several bytecodes, so it is possible that the newline
7776 7788 does not reach your file before the next thread switch.
7777 7789 Similarly, if you are writing to a file in binary mode, the file won't
7778 7790 be flushed until the buffer fills, and your other thread may see apparently
7779 7791 truncated files.
7780 7792
7781 7793 \layout Standard
7782 7794
7783 7795 For this reason, if you are using IPython's thread support and have (for
7784 7796 example) a GUI application which will read data generated by files written
7785 7797 to from the IPython thread, the safest approach is to open all of your
7786 7798 files in unbuffered mode (the third argument to the
7787 7799 \family typewriter
7788 7800 file/open
7789 7801 \family default
7790 7802 function is the buffering value):
7791 7803 \newline
7792 7804
7793 7805 \family typewriter
7794 7806 \SpecialChar ~
7795 7807 \SpecialChar ~
7796 7808 filehandle = open(filename,mode,0)
7797 7809 \layout Standard
7798 7810
7799 7811 This is obviously a brute force way of avoiding race conditions with the
7800 7812 file buffering.
7801 7813 If you want to do it cleanly, and you have a resource which is being shared
7802 7814 by the interactive IPython loop and your GUI thread, you should really
7803 7815 handle it with thread locking and syncrhonization properties.
7804 7816 The Python documentation discusses these.
7805 7817 \layout Section
7806 7818
7807 7819
7808 7820 \begin_inset LatexCommand \label{sec:interactive-demos}
7809 7821
7810 7822 \end_inset
7811 7823
7812 7824 Interactive demos with IPython
7813 7825 \layout Standard
7814 7826
7815 7827 IPython ships with a basic system for running scripts interactively in sections,
7816 7828 useful when presenting code to audiences.
7817 7829 A few tags embedded in comments (so that the script remains valid Python
7818 7830 code) divide a file into separate blocks, and the demo can be run one block
7819 7831 at a time, with IPython printing (with syntax highlighting) the block before
7820 7832 executing it, and returning to the interactive prompt after each block.
7821 7833 The interactive namespace is updated after each block is run with the contents
7822 7834 of the demo's namespace.
7823 7835 \layout Standard
7824 7836
7825 7837 This allows you to show a piece of code, run it and then execute interactively
7826 7838 commands based on the variables just created.
7827 7839 Once you want to continue, you simply execute the next block of the demo.
7828 7840 The following listing shows the markup necessary for dividing a script
7829 7841 into sections for execution as a demo.
7830 7842 \layout Standard
7831 7843
7832 7844
7833 7845 \begin_inset ERT
7834 7846 status Open
7835 7847
7836 7848 \layout Standard
7837 7849
7838 7850 \backslash
7839 7851 codelist{examples/example-demo.py}
7840 7852 \end_inset
7841 7853
7842 7854
7843 7855 \layout Standard
7844 7856
7845 7857 In order to run a file as a demo, you must first make a
7846 7858 \family typewriter
7847 7859 Demo
7848 7860 \family default
7849 7861 object out of it.
7850 7862 If the file is named
7851 7863 \family typewriter
7852 7864 myscript.py
7853 7865 \family default
7854 7866 , the following code will make a demo:
7855 7867 \layout LyX-Code
7856 7868
7857 7869 from IPython.demo import Demo
7858 7870 \layout LyX-Code
7859 7871
7860 7872 mydemo = Demo('myscript.py')
7861 7873 \layout Standard
7862 7874
7863 7875 This creates the
7864 7876 \family typewriter
7865 7877 mydemo
7866 7878 \family default
7867 7879 object, whose blocks you run one at a time by simply calling the object
7868 7880 with no arguments.
7869 7881 If you have autocall active in IPython (the default), all you need to do
7870 7882 is type
7871 7883 \layout LyX-Code
7872 7884
7873 7885 mydemo
7874 7886 \layout Standard
7875 7887
7876 7888 and IPython will call it, executing each block.
7877 7889 Demo objects can be restarted, you can move forward or back skipping blocks,
7878 7890 re-execute the last block, etc.
7879 7891 Simply use the Tab key on a demo object to see its methods, and call
7880 7892 \family typewriter
7881 7893 `?'
7882 7894 \family default
7883 7895 on them to see their docstrings for more usage details.
7884 7896 In addition, the
7885 7897 \family typewriter
7886 7898 demo
7887 7899 \family default
7888 7900 module itself contains a comprehensive docstring, which you can access
7889 7901 via
7890 7902 \layout LyX-Code
7891 7903
7892 7904 from IPython import demo
7893 7905 \layout LyX-Code
7894 7906
7895 7907 demo?
7896 7908 \layout Standard
7897 7909
7898 7910
7899 7911 \series bold
7900 7912 Limitations:
7901 7913 \series default
7902 7914 It is important to note that these demos are limited to fairly simple uses.
7903 7915 In particular, you can
7904 7916 \emph on
7905 7917 not
7906 7918 \emph default
7907 7919 put division marks in indented code (loops, if statements, function definitions
7908 7920 , etc.) Supporting something like this would basically require tracking the
7909 7921 internal execution state of the Python interpreter, so only top-level divisions
7910 7922 are allowed.
7911 7923 If you want to be able to open an IPython instance at an arbitrary point
7912 7924 in a program, you can use IPython's embedding facilities, described in
7913 7925 detail in Sec\SpecialChar \@.
7914 7926 \SpecialChar ~
7915 7927
7916 7928 \begin_inset LatexCommand \ref{sec:embed}
7917 7929
7918 7930 \end_inset
7919 7931
7920 7932 .
7921 7933 \layout Section
7922 7934
7923 7935
7924 7936 \begin_inset LatexCommand \label{sec:matplotlib-support}
7925 7937
7926 7938 \end_inset
7927 7939
7928 7940 Plotting with
7929 7941 \family typewriter
7930 7942 matplotlib
7931 7943 \family default
7932 7944
7933 7945 \layout Standard
7934 7946
7935 7947 The matplotlib library (
7936 7948 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
7937 7949
7938 7950 \end_inset
7939 7951
7940 7952 ) provides high quality 2D plotting for Python.
7941 7953 Matplotlib can produce plots on screen using a variety of GUI toolkits,
7942 7954 including Tk, GTK and WXPython.
7943 7955 It also provides a number of commands useful for scientific computing,
7944 7956 all with a syntax compatible with that of the popular Matlab program.
7945 7957 \layout Standard
7946 7958
7947 7959 IPython accepts the special option
7948 7960 \family typewriter
7949 7961 -pylab
7950 7962 \family default
7951 7963 (Sec.\SpecialChar ~
7952 7964
7953 7965 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
7954 7966
7955 7967 \end_inset
7956 7968
7957 7969 ).
7958 7970 This configures it to support matplotlib, honoring the settings in the
7959 7971
7960 7972 \family typewriter
7961 7973 .matplotlibrc
7962 7974 \family default
7963 7975 file.
7964 7976 IPython will detect the user's choice of matplotlib GUI backend, and automatica
7965 7977 lly select the proper threading model to prevent blocking.
7966 7978 It also sets matplotlib in interactive mode and modifies
7967 7979 \family typewriter
7968 7980 %run
7969 7981 \family default
7970 7982 slightly, so that any matplotlib-based script can be executed using
7971 7983 \family typewriter
7972 7984 %run
7973 7985 \family default
7974 7986 and the final
7975 7987 \family typewriter
7976 7988 show()
7977 7989 \family default
7978 7990 command does not block the interactive shell.
7979 7991 \layout Standard
7980 7992
7981 7993 The
7982 7994 \family typewriter
7983 7995 -pylab
7984 7996 \family default
7985 7997 option must be given first in order for IPython to configure its threading
7986 7998 mode.
7987 7999 However, you can still issue other options afterwards.
7988 8000 This allows you to have a matplotlib-based environment customized with
7989 8001 additional modules using the standard IPython profile mechanism (Sec.\SpecialChar ~
7990 8002
7991 8003 \begin_inset LatexCommand \ref{sec:profiles}
7992 8004
7993 8005 \end_inset
7994 8006
7995 8007 ): ``
7996 8008 \family typewriter
7997 8009 ipython -pylab -p myprofile
7998 8010 \family default
7999 8011 '' will load the profile defined in
8000 8012 \family typewriter
8001 8013 ipythonrc-myprofile
8002 8014 \family default
8003 8015 after configuring matplotlib.
8004 8016 \layout Section
8005 8017
8006 8018
8007 8019 \begin_inset LatexCommand \label{sec:Gnuplot}
8008 8020
8009 8021 \end_inset
8010 8022
8011 8023 Plotting with
8012 8024 \family typewriter
8013 8025 Gnuplot
8014 8026 \layout Standard
8015 8027
8016 8028 Through the magic extension system described in sec.
8017 8029
8018 8030 \begin_inset LatexCommand \ref{sec:magic}
8019 8031
8020 8032 \end_inset
8021 8033
8022 8034 , IPython incorporates a mechanism for conveniently interfacing with the
8023 8035 Gnuplot system (
8024 8036 \begin_inset LatexCommand \htmlurl{http://www.gnuplot.info}
8025 8037
8026 8038 \end_inset
8027 8039
8028 8040 ).
8029 8041 Gnuplot is a very complete 2D and 3D plotting package available for many
8030 8042 operating systems and commonly included in modern Linux distributions.
8031 8043
8032 8044 \layout Standard
8033 8045
8034 8046 Besides having Gnuplot installed, this functionality requires the
8035 8047 \family typewriter
8036 8048 Gnuplot.py
8037 8049 \family default
8038 8050 module for interfacing python with Gnuplot.
8039 8051 It can be downloaded from:
8040 8052 \begin_inset LatexCommand \htmlurl{http://gnuplot-py.sourceforge.net}
8041 8053
8042 8054 \end_inset
8043 8055
8044 8056 .
8045 8057 \layout Subsection
8046 8058
8047 8059 Proper Gnuplot configuration
8048 8060 \layout Standard
8049 8061
8050 8062 As of version 4.0, Gnuplot has excellent mouse and interactive keyboard support.
8051 8063 However, as of
8052 8064 \family typewriter
8053 8065 Gnuplot.py
8054 8066 \family default
8055 8067 version 1.7, a new option was added to communicate between Python and Gnuplot
8056 8068 via FIFOs (pipes).
8057 8069 This mechanism, while fast, also breaks the mouse system.
8058 8070 You must therefore set the variable
8059 8071 \family typewriter
8060 8072 prefer_fifo_data
8061 8073 \family default
8062 8074 to
8063 8075 \family typewriter
8064 8076 0
8065 8077 \family default
8066 8078 in file
8067 8079 \family typewriter
8068 8080 gp_unix.py
8069 8081 \family default
8070 8082 if you wish to keep the interactive mouse and keyboard features working
8071 8083 properly (
8072 8084 \family typewriter
8073 8085 prefer_inline_data
8074 8086 \family default
8075 8087 also must be
8076 8088 \family typewriter
8077 8089 0
8078 8090 \family default
8079 8091 , but this is the default so unless you've changed it manually you should
8080 8092 be fine).
8081 8093 \layout Standard
8082 8094
8083 8095 'Out of the box', Gnuplot is configured with a rather poor set of size,
8084 8096 color and linewidth choices which make the graphs fairly hard to read on
8085 8097 modern high-resolution displays (although they work fine on old 640x480
8086 8098 ones).
8087 8099 Below is a section of my
8088 8100 \family typewriter
8089 8101 .Xdefaults
8090 8102 \family default
8091 8103 file which I use for having a more convenient Gnuplot setup.
8092 8104 Remember to load it by running
8093 8105 \family typewriter
8094 8106 `xrdb .Xdefaults`
8095 8107 \family default
8096 8108 :
8097 8109 \layout Standard
8098 8110
8099 8111
8100 8112 \family typewriter
8101 8113 !******************************************************************
8102 8114 \newline
8103 8115 ! gnuplot options
8104 8116 \newline
8105 8117 ! modify this for a convenient window size
8106 8118 \newline
8107 8119 gnuplot*geometry: 780x580
8108 8120 \layout Standard
8109 8121
8110 8122
8111 8123 \family typewriter
8112 8124 ! on-screen font (not for PostScript)
8113 8125 \newline
8114 8126 gnuplot*font: -misc-fixed-bold-r-normal--15-120-100-100-c-90-iso8859-1
8115 8127 \layout Standard
8116 8128
8117 8129
8118 8130 \family typewriter
8119 8131 ! color options
8120 8132 \newline
8121 8133 gnuplot*background: black
8122 8134 \newline
8123 8135 gnuplot*textColor: white
8124 8136 \newline
8125 8137 gnuplot*borderColor: white
8126 8138 \newline
8127 8139 gnuplot*axisColor: white
8128 8140 \newline
8129 8141 gnuplot*line1Color: red
8130 8142 \newline
8131 8143 gnuplot*line2Color: green
8132 8144 \newline
8133 8145 gnuplot*line3Color: blue
8134 8146 \newline
8135 8147 gnuplot*line4Color: magenta
8136 8148 \newline
8137 8149 gnuplot*line5Color: cyan
8138 8150 \newline
8139 8151 gnuplot*line6Color: sienna
8140 8152 \newline
8141 8153 gnuplot*line7Color: orange
8142 8154 \newline
8143 8155 gnuplot*line8Color: coral
8144 8156 \layout Standard
8145 8157
8146 8158
8147 8159 \family typewriter
8148 8160 ! multiplicative factor for point styles
8149 8161 \newline
8150 8162 gnuplot*pointsize: 2
8151 8163 \layout Standard
8152 8164
8153 8165
8154 8166 \family typewriter
8155 8167 ! line width options (in pixels)
8156 8168 \newline
8157 8169 gnuplot*borderWidth: 2
8158 8170 \newline
8159 8171 gnuplot*axisWidth: 2
8160 8172 \newline
8161 8173 gnuplot*line1Width: 2
8162 8174 \newline
8163 8175 gnuplot*line2Width: 2
8164 8176 \newline
8165 8177 gnuplot*line3Width: 2
8166 8178 \newline
8167 8179 gnuplot*line4Width: 2
8168 8180 \newline
8169 8181 gnuplot*line5Width: 2
8170 8182 \newline
8171 8183 gnuplot*line6Width: 2
8172 8184 \newline
8173 8185 gnuplot*line7Width: 2
8174 8186 \newline
8175 8187 gnuplot*line8Width: 2
8176 8188 \layout Subsection
8177 8189
8178 8190 The
8179 8191 \family typewriter
8180 8192 IPython.GnuplotRuntime
8181 8193 \family default
8182 8194 module
8183 8195 \layout Standard
8184 8196
8185 8197 IPython includes a module called
8186 8198 \family typewriter
8187 8199 Gnuplot2.py
8188 8200 \family default
8189 8201 which extends and improves the default
8190 8202 \family typewriter
8191 8203 Gnuplot
8192 8204 \family default
8193 8205 .
8194 8206 \family typewriter
8195 8207 py
8196 8208 \family default
8197 8209 (which it still relies upon).
8198 8210 For example, the new
8199 8211 \family typewriter
8200 8212 plot
8201 8213 \family default
8202 8214 function adds several improvements to the original making it more convenient
8203 8215 for interactive use, and
8204 8216 \family typewriter
8205 8217 hardcopy
8206 8218 \family default
8207 8219 fixes a bug in the original which under some circumstances blocks the creation
8208 8220 of PostScript output.
8209 8221 \layout Standard
8210 8222
8211 8223 For scripting use,
8212 8224 \family typewriter
8213 8225 GnuplotRuntime.py
8214 8226 \family default
8215 8227 is provided, which wraps
8216 8228 \family typewriter
8217 8229 Gnuplot2.py
8218 8230 \family default
8219 8231 and creates a series of global aliases.
8220 8232 These make it easy to control Gnuplot plotting jobs through the Python
8221 8233 language.
8222 8234 \layout Standard
8223 8235
8224 8236 Below is some example code which illustrates how to configure Gnuplot inside
8225 8237 your own programs but have it available for further interactive use through
8226 8238 an embedded IPython instance.
8227 8239 Simply run this file at a system prompt.
8228 8240 This file is provided as
8229 8241 \family typewriter
8230 8242 example-gnuplot.py
8231 8243 \family default
8232 8244 in the examples directory:
8233 8245 \layout Standard
8234 8246
8235 8247
8236 8248 \begin_inset ERT
8237 8249 status Open
8238 8250
8239 8251 \layout Standard
8240 8252
8241 8253 \backslash
8242 8254 codelist{examples/example-gnuplot.py}
8243 8255 \end_inset
8244 8256
8245 8257
8246 8258 \layout Subsection
8247 8259
8248 8260 The
8249 8261 \family typewriter
8250 8262 numeric
8251 8263 \family default
8252 8264 profile: a scientific computing environment
8253 8265 \layout Standard
8254 8266
8255 8267 The
8256 8268 \family typewriter
8257 8269 numeric
8258 8270 \family default
8259 8271 IPython profile, which you can activate with
8260 8272 \family typewriter
8261 8273 `ipython -p numeric
8262 8274 \family default
8263 8275 ' will automatically load the IPython Gnuplot extensions (plus Numeric and
8264 8276 other useful things for numerical computing), contained in the
8265 8277 \family typewriter
8266 8278 IPython.GnuplotInteractive
8267 8279 \family default
8268 8280 module.
8269 8281 This will create the globals
8270 8282 \family typewriter
8271 8283 Gnuplot
8272 8284 \family default
8273 8285 (an alias to the improved Gnuplot2 module),
8274 8286 \family typewriter
8275 8287 gp
8276 8288 \family default
8277 8289 (a Gnuplot active instance), the new magic commands
8278 8290 \family typewriter
8279 8291 %gpc
8280 8292 \family default
8281 8293 and
8282 8294 \family typewriter
8283 8295 %gp_set_instance
8284 8296 \family default
8285 8297 and several other convenient globals.
8286 8298 Type
8287 8299 \family typewriter
8288 8300 gphelp()
8289 8301 \family default
8290 8302 for further details.
8291 8303 \layout Standard
8292 8304
8293 8305 This should turn IPython into a convenient environment for numerical computing,
8294 8306 with all the functions in the NumPy library and the Gnuplot facilities
8295 8307 for plotting.
8296 8308 Further improvements can be obtained by loading the SciPy libraries for
8297 8309 scientific computing, available at
8298 8310 \begin_inset LatexCommand \htmlurl{http://scipy.org}
8299 8311
8300 8312 \end_inset
8301 8313
8302 8314 .
8303 8315 \layout Standard
8304 8316
8305 8317 If you are in the middle of a working session with numerical objects and
8306 8318 need to plot them but you didn't start the
8307 8319 \family typewriter
8308 8320 numeric
8309 8321 \family default
8310 8322 profile, you can load these extensions at any time by typing
8311 8323 \newline
8312 8324
8313 8325 \family typewriter
8314 8326 from IPython.GnuplotInteractive import *
8315 8327 \newline
8316 8328
8317 8329 \family default
8318 8330 at the IPython prompt.
8319 8331 This will allow you to keep your objects intact and start using Gnuplot
8320 8332 to view them.
8321 8333 \layout Section
8322 8334
8323 8335 Reporting bugs
8324 8336 \layout Subsection*
8325 8337
8326 8338 Automatic crash reports
8327 8339 \layout Standard
8328 8340
8329 8341 Ideally, IPython itself shouldn't crash.
8330 8342 It will catch exceptions produced by you, but bugs in its internals will
8331 8343 still crash it.
8332 8344 \layout Standard
8333 8345
8334 8346 In such a situation, IPython will leave a file named
8335 8347 \family typewriter
8336 8348 IPython_crash_report.txt
8337 8349 \family default
8338 8350 in your IPYTHONDIR directory (that way if crashes happen several times
8339 8351 it won't litter many directories, the post-mortem file is always located
8340 8352 in the same place and new occurrences just overwrite the previous one).
8341 8353 If you can mail this file to the developers (see sec.
8342 8354
8343 8355 \begin_inset LatexCommand \ref{sec:credits}
8344 8356
8345 8357 \end_inset
8346 8358
8347 8359 for names and addresses), it will help us
8348 8360 \emph on
8349 8361 a lot
8350 8362 \emph default
8351 8363 in understanding the cause of the problem and fixing it sooner.
8352 8364 \layout Subsection*
8353 8365
8354 8366 The bug tracker
8355 8367 \layout Standard
8356 8368
8357 8369 IPython also has an online bug-tracker, located at
8358 8370 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython}
8359 8371
8360 8372 \end_inset
8361 8373
8362 8374 .
8363 8375 In addition to mailing the developers, it would be a good idea to file
8364 8376 a bug report here.
8365 8377 This will ensure that the issue is properly followed to conclusion.
8366 8378 \layout Standard
8367 8379
8368 8380 You can also use this bug tracker to file feature requests.
8369 8381 \layout Section
8370 8382
8371 8383 Brief history
8372 8384 \layout Subsection
8373 8385
8374 8386 Origins
8375 8387 \layout Standard
8376 8388
8377 8389 The current IPython system grew out of the following three projects:
8378 8390 \layout List
8379 8391 \labelwidthstring 00.00.0000
8380 8392
8381 8393 ipython by Fernando Pérez.
8382 8394 I was working on adding Mathematica-type prompts and a flexible configuration
8383 8395 system (something better than
8384 8396 \family typewriter
8385 8397 $PYTHONSTARTUP
8386 8398 \family default
8387 8399 ) to the standard Python interactive interpreter.
8388 8400 \layout List
8389 8401 \labelwidthstring 00.00.0000
8390 8402
8391 8403 IPP by Janko Hauser.
8392 8404 Very well organized, great usability.
8393 8405 Had an old help system.
8394 8406 IPP was used as the `container' code into which I added the functionality
8395 8407 from ipython and LazyPython.
8396 8408 \layout List
8397 8409 \labelwidthstring 00.00.0000
8398 8410
8399 8411 LazyPython by Nathan Gray.
8400 8412 Simple but
8401 8413 \emph on
8402 8414 very
8403 8415 \emph default
8404 8416 powerful.
8405 8417 The quick syntax (auto parens, auto quotes) and verbose/colored tracebacks
8406 8418 were all taken from here.
8407 8419 \layout Standard
8408 8420
8409 8421 When I found out (see sec.
8410 8422
8411 8423 \begin_inset LatexCommand \ref{figgins}
8412 8424
8413 8425 \end_inset
8414 8426
8415 8427 ) about IPP and LazyPython I tried to join all three into a unified system.
8416 8428 I thought this could provide a very nice working environment, both for
8417 8429 regular programming and scientific computing: shell-like features, IDL/Matlab
8418 8430 numerics, Mathematica-type prompt history and great object introspection
8419 8431 and help facilities.
8420 8432 I think it worked reasonably well, though it was a lot more work than I
8421 8433 had initially planned.
8422 8434 \layout Subsection
8423 8435
8424 8436 Current status
8425 8437 \layout Standard
8426 8438
8427 8439 The above listed features work, and quite well for the most part.
8428 8440 But until a major internal restructuring is done (see below), only bug
8429 8441 fixing will be done, no other features will be added (unless very minor
8430 8442 and well localized in the cleaner parts of the code).
8431 8443 \layout Standard
8432 8444
8433 8445 IPython consists of some 12000 lines of pure python code, of which roughly
8434 8446 50% are fairly clean.
8435 8447 The other 50% are fragile, messy code which needs a massive restructuring
8436 8448 before any further major work is done.
8437 8449 Even the messy code is fairly well documented though, and most of the problems
8438 8450 in the (non-existent) class design are well pointed to by a PyChecker run.
8439 8451 So the rewriting work isn't that bad, it will just be time-consuming.
8440 8452 \layout Subsection
8441 8453
8442 8454 Future
8443 8455 \layout Standard
8444 8456
8445 8457 See the separate
8446 8458 \family typewriter
8447 8459 new_design
8448 8460 \family default
8449 8461 document for details.
8450 8462 Ultimately, I would like to see IPython become part of the standard Python
8451 8463 distribution as a `big brother with batteries' to the standard Python interacti
8452 8464 ve interpreter.
8453 8465 But that will never happen with the current state of the code, so all contribut
8454 8466 ions are welcome.
8455 8467 \layout Section
8456 8468
8457 8469 License
8458 8470 \layout Standard
8459 8471
8460 8472 IPython is released under the terms of the BSD license, whose general form
8461 8473 can be found at:
8462 8474 \begin_inset LatexCommand \htmlurl{http://www.opensource.org/licenses/bsd-license.php}
8463 8475
8464 8476 \end_inset
8465 8477
8466 8478 .
8467 8479 The full text of the IPython license is reproduced below:
8468 8480 \layout Quote
8469 8481
8470 8482
8471 8483 \family typewriter
8472 8484 \size small
8473 8485 IPython is released under a BSD-type license.
8474 8486 \layout Quote
8475 8487
8476 8488
8477 8489 \family typewriter
8478 8490 \size small
8479 8491 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
8480 8492 \layout Quote
8481 8493
8482 8494
8483 8495 \family typewriter
8484 8496 \size small
8485 8497 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
8486 8498 \newline
8487 8499 Nathaniel Gray <n8gray@caltech.edu>.
8488 8500 \layout Quote
8489 8501
8490 8502
8491 8503 \family typewriter
8492 8504 \size small
8493 8505 All rights reserved.
8494 8506 \layout Quote
8495 8507
8496 8508
8497 8509 \family typewriter
8498 8510 \size small
8499 8511 Redistribution and use in source and binary forms, with or without modification,
8500 8512 are permitted provided that the following conditions are met:
8501 8513 \layout Quote
8502 8514
8503 8515
8504 8516 \family typewriter
8505 8517 \size small
8506 8518 a.
8507 8519 Redistributions of source code must retain the above copyright notice,
8508 8520 this list of conditions and the following disclaimer.
8509 8521 \layout Quote
8510 8522
8511 8523
8512 8524 \family typewriter
8513 8525 \size small
8514 8526 b.
8515 8527 Redistributions in binary form must reproduce the above copyright notice,
8516 8528 this list of conditions and the following disclaimer in the documentation
8517 8529 and/or other materials provided with the distribution.
8518 8530 \layout Quote
8519 8531
8520 8532
8521 8533 \family typewriter
8522 8534 \size small
8523 8535 c.
8524 8536 Neither the name of the copyright holders nor the names of any contributors
8525 8537 to this software may be used to endorse or promote products derived from
8526 8538 this software without specific prior written permission.
8527 8539 \layout Quote
8528 8540
8529 8541
8530 8542 \family typewriter
8531 8543 \size small
8532 8544 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8533 8545 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
8534 8546 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
8535 8547 PURPOSE ARE DISCLAIMED.
8536 8548 IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
8537 8549 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
8538 8550 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
8539 8551 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
8540 8552 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8541 8553 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8542 8554 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8543 8555
8544 8556 \layout Standard
8545 8557
8546 8558 Individual authors are the holders of the copyright for their code and are
8547 8559 listed in each file.
8548 8560 \layout Standard
8549 8561
8550 8562 Some files (
8551 8563 \family typewriter
8552 8564 DPyGetOpt.py
8553 8565 \family default
8554 8566 , for example) may be licensed under different conditions.
8555 8567 Ultimately each file indicates clearly the conditions under which its author/au
8556 8568 thors have decided to publish the code.
8557 8569 \layout Standard
8558 8570
8559 8571 Versions of IPython up to and including 0.6.3 were released under the GNU
8560 8572 Lesser General Public License (LGPL), available at
8561 8573 \begin_inset LatexCommand \htmlurl{http://www.gnu.org/copyleft/lesser.html}
8562 8574
8563 8575 \end_inset
8564 8576
8565 8577 .
8566 8578 \layout Section
8567 8579
8568 8580
8569 8581 \begin_inset LatexCommand \label{sec:credits}
8570 8582
8571 8583 \end_inset
8572 8584
8573 8585 Credits
8574 8586 \layout Standard
8575 8587
8576 8588 IPython is mainly developed by Fernando Pérez
8577 8589 \family typewriter
8578 8590 <fperez@colorado.edu>
8579 8591 \family default
8580 8592 , but the project was born from mixing in Fernando's code with the IPP project
8581 8593 by Janko Hauser
8582 8594 \family typewriter
8583 8595 <jhauser-AT-zscout.de>
8584 8596 \family default
8585 8597 and LazyPython by Nathan Gray
8586 8598 \family typewriter
8587 8599 <n8gray-AT-caltech.edu>
8588 8600 \family default
8589 8601 .
8590 8602 For all IPython-related requests, please contact Fernando.
8591 8603
8592 8604 \layout Standard
8593 8605
8594 8606 As of late 2005, the following developers have joined the core team:
8595 8607 \layout List
8596 8608 \labelwidthstring 00.00.0000
8597 8609
8598 8610 Robert\SpecialChar ~
8599 8611 Kern
8600 8612 \family typewriter
8601 8613 <rkern-AT-enthought.com>
8602 8614 \family default
8603 8615 : co-mentored the 2005 Google Summer of Code project to develop python interacti
8604 8616 ve notebooks (XML documents) and graphical interface.
8605 8617 This project was awarded to the students Tzanko Matev
8606 8618 \family typewriter
8607 8619 <tsanko-AT-gmail.com>
8608 8620 \family default
8609 8621 and Toni Alatalo
8610 8622 \family typewriter
8611 8623 <antont-AT-an.org>
8612 8624 \layout List
8613 8625 \labelwidthstring 00.00.0000
8614 8626
8615 8627 Brian\SpecialChar ~
8616 8628 Granger
8617 8629 \family typewriter
8618 8630 <bgranger-AT-scu.edu>
8619 8631 \family default
8620 8632 : extending IPython to allow support for interactive parallel computing.
8621 8633 \layout Standard
8622 8634
8623 8635 User or development help should be requested via the IPython mailing lists:
8624 8636 \layout Description
8625 8637
8626 8638 User\SpecialChar ~
8627 8639 list:
8628 8640 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-user}
8629 8641
8630 8642 \end_inset
8631 8643
8632 8644
8633 8645 \layout Description
8634 8646
8635 8647 Developer's\SpecialChar ~
8636 8648 list:
8637 8649 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-dev}
8638 8650
8639 8651 \end_inset
8640 8652
8641 8653
8642 8654 \layout Standard
8643 8655
8644 8656 The IPython project is also very grateful to
8645 8657 \begin_inset Foot
8646 8658 collapsed true
8647 8659
8648 8660 \layout Standard
8649 8661
8650 8662 I've mangled email addresses to reduce spam, since the IPython manuals can
8651 8663 be accessed online.
8652 8664 \end_inset
8653 8665
8654 8666 :
8655 8667 \layout Standard
8656 8668
8657 8669 Bill Bumgarner
8658 8670 \family typewriter
8659 8671 <bbum-AT-friday.com>
8660 8672 \family default
8661 8673 : for providing the DPyGetOpt module which gives very powerful and convenient
8662 8674 handling of command-line options (light years ahead of what Python 2.1.1's
8663 8675 getopt module does).
8664 8676 \layout Standard
8665 8677
8666 8678 Ka-Ping Yee
8667 8679 \family typewriter
8668 8680 <ping-AT-lfw.org>
8669 8681 \family default
8670 8682 : for providing the Itpl module for convenient and powerful string interpolation
8671 8683 with a much nicer syntax than formatting through the '%' operator.
8672 8684 \layout Standard
8673 8685
8674 8686 Arnd Bäcker
8675 8687 \family typewriter
8676 8688 <baecker-AT-physik.tu-dresden.de>
8677 8689 \family default
8678 8690 : for his many very useful suggestions and comments, and lots of help with
8679 8691 testing and documentation checking.
8680 8692 Many of IPython's newer features are a result of discussions with him (bugs
8681 8693 are still my fault, not his).
8682 8694 \layout Standard
8683 8695
8684 8696 Obviously Guido van\SpecialChar ~
8685 8697 Rossum and the whole Python development team, that goes
8686 8698 without saying.
8687 8699 \layout Standard
8688 8700
8689 8701 IPython's website is generously hosted at
8690 8702 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
8691 8703
8692 8704 \end_inset
8693 8705
8694 8706 by Enthought (
8695 8707 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
8696 8708
8697 8709 \end_inset
8698 8710
8699 8711 ).
8700 8712 I am very grateful to them and all of the SciPy team for their contribution.
8701 8713 \layout Standard
8702 8714
8703 8715
8704 8716 \begin_inset LatexCommand \label{figgins}
8705 8717
8706 8718 \end_inset
8707 8719
8708 8720 Fernando would also like to thank Stephen Figgins
8709 8721 \family typewriter
8710 8722 <fig-AT-monitor.net>
8711 8723 \family default
8712 8724 , an O'Reilly Python editor.
8713 8725 His Oct/11/2001 article about IPP and LazyPython, was what got this project
8714 8726 started.
8715 8727 You can read it at:
8716 8728 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html}
8717 8729
8718 8730 \end_inset
8719 8731
8720 8732 .
8721 8733 \layout Standard
8722 8734
8723 8735 And last but not least, all the kind IPython users who have emailed new
8724 8736 code, bug reports, fixes, comments and ideas.
8725 8737 A brief list follows, please let me know if I have ommitted your name by
8726 8738 accident:
8727 8739 \layout List
8728 8740 \labelwidthstring 00.00.0000
8729 8741
8730 8742 Jack\SpecialChar ~
8731 8743 Moffit
8732 8744 \family typewriter
8733 8745 <jack-AT-xiph.org>
8734 8746 \family default
8735 8747 Bug fixes, including the infamous color problem.
8736 8748 This bug alone caused many lost hours and frustration, many thanks to him
8737 8749 for the fix.
8738 8750 I've always been a fan of Ogg & friends, now I have one more reason to
8739 8751 like these folks.
8740 8752 \newline
8741 8753 Jack is also contributing with Debian packaging and many other things.
8742 8754 \layout List
8743 8755 \labelwidthstring 00.00.0000
8744 8756
8745 8757 Alexander\SpecialChar ~
8746 8758 Schmolck
8747 8759 \family typewriter
8748 8760 <a.schmolck-AT-gmx.net>
8749 8761 \family default
8750 8762 Emacs work, bug reports, bug fixes, ideas, lots more.
8751 8763 The ipython.el mode for (X)Emacs is Alex's code, providing full support
8752 8764 for IPython under (X)Emacs.
8753 8765 \layout List
8754 8766 \labelwidthstring 00.00.0000
8755 8767
8756 8768 Andrea\SpecialChar ~
8757 8769 Riciputi
8758 8770 \family typewriter
8759 8771 <andrea.riciputi-AT-libero.it>
8760 8772 \family default
8761 8773 Mac OSX information, Fink package management.
8762 8774 \layout List
8763 8775 \labelwidthstring 00.00.0000
8764 8776
8765 8777 Gary\SpecialChar ~
8766 8778 Bishop
8767 8779 \family typewriter
8768 8780 <gb-AT-cs.unc.edu>
8769 8781 \family default
8770 8782 Bug reports, and patches to work around the exception handling idiosyncracies
8771 8783 of WxPython.
8772 8784 Readline and color support for Windows.
8773 8785 \layout List
8774 8786 \labelwidthstring 00.00.0000
8775 8787
8776 8788 Jeffrey\SpecialChar ~
8777 8789 Collins
8778 8790 \family typewriter
8779 8791 <Jeff.Collins-AT-vexcel.com>
8780 8792 \family default
8781 8793 Bug reports.
8782 8794 Much improved readline support, including fixes for Python 2.3.
8783 8795 \layout List
8784 8796 \labelwidthstring 00.00.0000
8785 8797
8786 8798 Dryice\SpecialChar ~
8787 8799 Liu
8788 8800 \family typewriter
8789 8801 <dryice-AT-liu.com.cn>
8790 8802 \family default
8791 8803 FreeBSD port.
8792 8804 \layout List
8793 8805 \labelwidthstring 00.00.0000
8794 8806
8795 8807 Mike\SpecialChar ~
8796 8808 Heeter
8797 8809 \family typewriter
8798 8810 <korora-AT-SDF.LONESTAR.ORG>
8799 8811 \layout List
8800 8812 \labelwidthstring 00.00.0000
8801 8813
8802 8814 Christopher\SpecialChar ~
8803 8815 Hart
8804 8816 \family typewriter
8805 8817 <hart-AT-caltech.edu>
8806 8818 \family default
8807 8819 PDB integration.
8808 8820 \layout List
8809 8821 \labelwidthstring 00.00.0000
8810 8822
8811 8823 Milan\SpecialChar ~
8812 8824 Zamazal
8813 8825 \family typewriter
8814 8826 <pdm-AT-zamazal.org>
8815 8827 \family default
8816 8828 Emacs info.
8817 8829 \layout List
8818 8830 \labelwidthstring 00.00.0000
8819 8831
8820 8832 Philip\SpecialChar ~
8821 8833 Hisley
8822 8834 \family typewriter
8823 8835 <compsys-AT-starpower.net>
8824 8836 \layout List
8825 8837 \labelwidthstring 00.00.0000
8826 8838
8827 8839 Holger\SpecialChar ~
8828 8840 Krekel
8829 8841 \family typewriter
8830 8842 <pyth-AT-devel.trillke.net>
8831 8843 \family default
8832 8844 Tab completion, lots more.
8833 8845 \layout List
8834 8846 \labelwidthstring 00.00.0000
8835 8847
8836 8848 Robin\SpecialChar ~
8837 8849 Siebler
8838 8850 \family typewriter
8839 8851 <robinsiebler-AT-starband.net>
8840 8852 \layout List
8841 8853 \labelwidthstring 00.00.0000
8842 8854
8843 8855 Ralf\SpecialChar ~
8844 8856 Ahlbrink
8845 8857 \family typewriter
8846 8858 <ralf_ahlbrink-AT-web.de>
8847 8859 \layout List
8848 8860 \labelwidthstring 00.00.0000
8849 8861
8850 8862 Thorsten\SpecialChar ~
8851 8863 Kampe
8852 8864 \family typewriter
8853 8865 <thorsten-AT-thorstenkampe.de>
8854 8866 \layout List
8855 8867 \labelwidthstring 00.00.0000
8856 8868
8857 8869 Fredrik\SpecialChar ~
8858 8870 Kant
8859 8871 \family typewriter
8860 8872 <fredrik.kant-AT-front.com>
8861 8873 \family default
8862 8874 Windows setup.
8863 8875 \layout List
8864 8876 \labelwidthstring 00.00.0000
8865 8877
8866 8878 Syver\SpecialChar ~
8867 8879 Enstad
8868 8880 \family typewriter
8869 8881 <syver-en-AT-online.no>
8870 8882 \family default
8871 8883 Windows setup.
8872 8884 \layout List
8873 8885 \labelwidthstring 00.00.0000
8874 8886
8875 8887 Richard
8876 8888 \family typewriter
8877 8889 <rxe-AT-renre-europe.com>
8878 8890 \family default
8879 8891 Global embedding.
8880 8892 \layout List
8881 8893 \labelwidthstring 00.00.0000
8882 8894
8883 8895 Hayden\SpecialChar ~
8884 8896 Callow
8885 8897 \family typewriter
8886 8898 <h.callow-AT-elec.canterbury.ac.nz>
8887 8899 \family default
8888 8900 Gnuplot.py 1.6 compatibility.
8889 8901 \layout List
8890 8902 \labelwidthstring 00.00.0000
8891 8903
8892 8904 Leonardo\SpecialChar ~
8893 8905 Santagada
8894 8906 \family typewriter
8895 8907 <retype-AT-terra.com.br>
8896 8908 \family default
8897 8909 Fixes for Windows installation.
8898 8910 \layout List
8899 8911 \labelwidthstring 00.00.0000
8900 8912
8901 8913 Christopher\SpecialChar ~
8902 8914 Armstrong
8903 8915 \family typewriter
8904 8916 <radix-AT-twistedmatrix.com>
8905 8917 \family default
8906 8918 Bugfixes.
8907 8919 \layout List
8908 8920 \labelwidthstring 00.00.0000
8909 8921
8910 8922 Francois\SpecialChar ~
8911 8923 Pinard
8912 8924 \family typewriter
8913 8925 <pinard-AT-iro.umontreal.ca>
8914 8926 \family default
8915 8927 Code and documentation fixes.
8916 8928 \layout List
8917 8929 \labelwidthstring 00.00.0000
8918 8930
8919 8931 Cory\SpecialChar ~
8920 8932 Dodt
8921 8933 \family typewriter
8922 8934 <cdodt-AT-fcoe.k12.ca.us>
8923 8935 \family default
8924 8936 Bug reports and Windows ideas.
8925 8937 Patches for Windows installer.
8926 8938 \layout List
8927 8939 \labelwidthstring 00.00.0000
8928 8940
8929 8941 Olivier\SpecialChar ~
8930 8942 Aubert
8931 8943 \family typewriter
8932 8944 <oaubert-AT-bat710.univ-lyon1.fr>
8933 8945 \family default
8934 8946 New magics.
8935 8947 \layout List
8936 8948 \labelwidthstring 00.00.0000
8937 8949
8938 8950 King\SpecialChar ~
8939 8951 C.\SpecialChar ~
8940 8952 Shu
8941 8953 \family typewriter
8942 8954 <kingshu-AT-myrealbox.com>
8943 8955 \family default
8944 8956 Autoindent patch.
8945 8957 \layout List
8946 8958 \labelwidthstring 00.00.0000
8947 8959
8948 8960 Chris\SpecialChar ~
8949 8961 Drexler
8950 8962 \family typewriter
8951 8963 <chris-AT-ac-drexler.de>
8952 8964 \family default
8953 8965 Readline packages for Win32/CygWin.
8954 8966 \layout List
8955 8967 \labelwidthstring 00.00.0000
8956 8968
8957 8969 Gustavo\SpecialChar ~
8958 8970 Córdova\SpecialChar ~
8959 8971 Avila
8960 8972 \family typewriter
8961 8973 <gcordova-AT-sismex.com>
8962 8974 \family default
8963 8975 EvalDict code for nice, lightweight string interpolation.
8964 8976 \layout List
8965 8977 \labelwidthstring 00.00.0000
8966 8978
8967 8979 Kasper\SpecialChar ~
8968 8980 Souren
8969 8981 \family typewriter
8970 8982 <Kasper.Souren-AT-ircam.fr>
8971 8983 \family default
8972 8984 Bug reports, ideas.
8973 8985 \layout List
8974 8986 \labelwidthstring 00.00.0000
8975 8987
8976 8988 Gever\SpecialChar ~
8977 8989 Tulley
8978 8990 \family typewriter
8979 8991 <gever-AT-helium.com>
8980 8992 \family default
8981 8993 Code contributions.
8982 8994 \layout List
8983 8995 \labelwidthstring 00.00.0000
8984 8996
8985 8997 Ralf\SpecialChar ~
8986 8998 Schmitt
8987 8999 \family typewriter
8988 9000 <ralf-AT-brainbot.com>
8989 9001 \family default
8990 9002 Bug reports & fixes.
8991 9003 \layout List
8992 9004 \labelwidthstring 00.00.0000
8993 9005
8994 9006 Oliver\SpecialChar ~
8995 9007 Sander
8996 9008 \family typewriter
8997 9009 <osander-AT-gmx.de>
8998 9010 \family default
8999 9011 Bug reports.
9000 9012 \layout List
9001 9013 \labelwidthstring 00.00.0000
9002 9014
9003 9015 Rod\SpecialChar ~
9004 9016 Holland
9005 9017 \family typewriter
9006 9018 <rhh-AT-structurelabs.com>
9007 9019 \family default
9008 9020 Bug reports and fixes to logging module.
9009 9021 \layout List
9010 9022 \labelwidthstring 00.00.0000
9011 9023
9012 9024 Daniel\SpecialChar ~
9013 9025 'Dang'\SpecialChar ~
9014 9026 Griffith
9015 9027 \family typewriter
9016 9028 <pythondev-dang-AT-lazytwinacres.net>
9017 9029 \family default
9018 9030 Fixes, enhancement suggestions for system shell use.
9019 9031 \layout List
9020 9032 \labelwidthstring 00.00.0000
9021 9033
9022 9034 Viktor\SpecialChar ~
9023 9035 Ransmayr
9024 9036 \family typewriter
9025 9037 <viktor.ransmayr-AT-t-online.de>
9026 9038 \family default
9027 9039 Tests and reports on Windows installation issues.
9028 9040 Contributed a true Windows binary installer.
9029 9041 \layout List
9030 9042 \labelwidthstring 00.00.0000
9031 9043
9032 9044 Mike\SpecialChar ~
9033 9045 Salib
9034 9046 \family typewriter
9035 9047 <msalib-AT-mit.edu>
9036 9048 \family default
9037 9049 Help fixing a subtle bug related to traceback printing.
9038 9050 \layout List
9039 9051 \labelwidthstring 00.00.0000
9040 9052
9041 9053 W.J.\SpecialChar ~
9042 9054 van\SpecialChar ~
9043 9055 der\SpecialChar ~
9044 9056 Laan
9045 9057 \family typewriter
9046 9058 <gnufnork-AT-hetdigitalegat.nl>
9047 9059 \family default
9048 9060 Bash-like prompt specials.
9049 9061 \layout List
9050 9062 \labelwidthstring 00.00.0000
9051 9063
9052 9064 Ville\SpecialChar ~
9053 9065 Vainio
9054 9066 \family typewriter
9055 9067 <vivainio-AT-kolumbus.fi>
9056 9068 \family default
9057 9069 Bugfixes and suggestions.
9058 9070 Excellent patches for many new features.
9059 9071 \layout List
9060 9072 \labelwidthstring 00.00.0000
9061 9073
9062 9074 Antoon\SpecialChar ~
9063 9075 Pardon
9064 9076 \family typewriter
9065 9077 <Antoon.Pardon-AT-rece.vub.ac.be>
9066 9078 \family default
9067 9079 Critical fix for the multithreaded IPython.
9068 9080 \layout List
9069 9081 \labelwidthstring 00.00.0000
9070 9082
9071 9083 John\SpecialChar ~
9072 9084 Hunter
9073 9085 \family typewriter
9074 9086 <jdhunter-AT-nitace.bsd.uchicago.edu>
9075 9087 \family default
9076 9088 Matplotlib author, helped with all the development of support for matplotlib
9077 9089 in IPyhton, including making necessary changes to matplotlib itself.
9078 9090 \layout List
9079 9091 \labelwidthstring 00.00.0000
9080 9092
9081 9093 Matthew\SpecialChar ~
9082 9094 Arnison
9083 9095 \family typewriter
9084 9096 <maffew-AT-cat.org.au>
9085 9097 \family default
9086 9098 Bug reports, `
9087 9099 \family typewriter
9088 9100 %run -d
9089 9101 \family default
9090 9102 ' idea.
9091 9103 \layout List
9092 9104 \labelwidthstring 00.00.0000
9093 9105
9094 9106 Prabhu\SpecialChar ~
9095 9107 Ramachandran
9096 9108 \family typewriter
9097 9109 <prabhu_r-AT-users.sourceforge.net>
9098 9110 \family default
9099 9111 Help with (X)Emacs support, threading patches, ideas...
9100 9112 \layout List
9101 9113 \labelwidthstring 00.00.0000
9102 9114
9103 9115 Norbert\SpecialChar ~
9104 9116 Tretkowski
9105 9117 \family typewriter
9106 9118 <tretkowski-AT-inittab.de>
9107 9119 \family default
9108 9120 help with Debian packaging and distribution.
9109 9121 \layout List
9110 9122 \labelwidthstring 00.00.0000
9111 9123
9112 9124 George\SpecialChar ~
9113 9125 Sakkis <
9114 9126 \family typewriter
9115 9127 gsakkis-AT-eden.rutgers.edu>
9116 9128 \family default
9117 9129 New matcher for tab-completing named arguments of user-defined functions.
9118 9130 \layout List
9119 9131 \labelwidthstring 00.00.0000
9120 9132
9121 9133 J�rgen\SpecialChar ~
9122 9134 Stenarson
9123 9135 \family typewriter
9124 9136 <jorgen.stenarson-AT-bostream.nu>
9125 9137 \family default
9126 9138 Wildcard support implementation for searching namespaces.
9127 9139 \layout List
9128 9140 \labelwidthstring 00.00.0000
9129 9141
9130 9142 Vivian\SpecialChar ~
9131 9143 De\SpecialChar ~
9132 9144 Smedt
9133 9145 \family typewriter
9134 9146 <vivian-AT-vdesmedt.com>
9135 9147 \family default
9136 9148 Debugger enhancements, so that when pdb is activated from within IPython,
9137 9149 coloring, tab completion and other features continue to work seamlessly.
9138 9150 \layout List
9139 9151 \labelwidthstring 00.00.0000
9140 9152
9141 9153 Scott\SpecialChar ~
9142 9154 Tsai
9143 9155 \family typewriter
9144 9156 <scottt958-AT-yahoo.com.tw>
9145 9157 \family default
9146 9158 Support for automatic editor invocation on syntax errors (see
9147 9159 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython/issue36}
9148 9160
9149 9161 \end_inset
9150 9162
9151 9163 ).
9152 9164 \layout List
9153 9165 \labelwidthstring 00.00.0000
9154 9166
9155 9167 Alexander\SpecialChar ~
9156 9168 Belchenko
9157 9169 \family typewriter
9158 9170 <bialix-AT-ukr.net>
9159 9171 \family default
9160 9172 Improvements for win32 paging system.
9161 9173 \the_end
General Comments 0
You need to be logged in to leave comments. Login now