##// END OF EJS Templates
Added support for automatically reopening the editor if the file had a...
fperez -
Show More
@@ -1,2579 +1,2579 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 958 2005-12-27 23:17:51Z fperez $"""
4 $Id: Magic.py 960 2005-12-28 06:51:01Z 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 from cStringIO import StringIO
34 34 from getopt import getopt
35 35 from pprint import pprint, pformat
36 36
37 37 # profile isn't bundled by default in Debian for license reasons
38 38 try:
39 39 import profile,pstats
40 40 except ImportError:
41 41 profile = pstats = None
42 42
43 43 # Homebrewed
44 44 from IPython import Debugger, OInspect, wildcard
45 45 from IPython.FakeModule import FakeModule
46 46 from IPython.Itpl import Itpl, itpl, printpl,itplns
47 47 from IPython.PyColorize import Parser
48 48 from IPython.Struct import Struct
49 49 from IPython.genutils import *
50 50
51 51 # Globals to be set later by Magic constructor
52 52 MAGIC_PREFIX = ''
53 53 MAGIC_ESCAPE = ''
54 54
55 55 #***************************************************************************
56 56 # Utility functions
57 57 def magic2python(cmd):
58 58 """Convert a command string of magic syntax to valid Python code."""
59 59
60 60 if cmd.startswith('#'+MAGIC_ESCAPE) or \
61 61 cmd.startswith(MAGIC_ESCAPE):
62 62 if cmd[0]=='#':
63 63 cmd = cmd[1:]
64 64 # we need to return the proper line end later
65 65 if cmd[-1] == '\n':
66 66 endl = '\n'
67 67 else:
68 68 endl = ''
69 69 try:
70 70 func,args = cmd[1:].split(' ',1)
71 71 except:
72 72 func,args = cmd[1:].rstrip(),''
73 73 args = args.replace('"','\\"').replace("'","\\'").rstrip()
74 74 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
75 75 else:
76 76 return cmd
77 77
78 78 def on_off(tag):
79 79 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
80 80 return ['OFF','ON'][tag]
81 81
82 82
83 83 #****************************************************************************
84 84 # Utility classes
85 85 class Macro:
86 86 """Simple class to store the value of macros as strings.
87 87
88 88 This allows us to later exec them by checking when something is an
89 89 instance of this class."""
90 90
91 91 def __init__(self,cmds):
92 92 """Build a macro from a list of commands."""
93 93
94 94 # Since the list may include multi-line entries, first make sure that
95 95 # they've been all broken up before passing it to magic2python
96 96 cmdlist = map(magic2python,''.join(cmds).split('\n'))
97 97 self.value = '\n'.join(cmdlist)
98 98
99 99 def __str__(self):
100 100 return self.value
101 101
102 102 #***************************************************************************
103 103 # Main class implementing Magic functionality
104 104 class Magic:
105 105 """Magic functions for InteractiveShell.
106 106
107 107 Shell functions which can be reached as %function_name. All magic
108 108 functions should accept a string, which they can parse for their own
109 109 needs. This can make some functions easier to type, eg `%cd ../`
110 110 vs. `%cd("../")`
111 111
112 112 ALL definitions MUST begin with the prefix magic_. The user won't need it
113 113 at the command line, but it is is needed in the definition. """
114 114
115 115 # class globals
116 116 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
117 117 'Automagic is ON, % prefix NOT needed for magic functions.']
118 118
119 119 #......................................................................
120 120 # some utility functions
121 121
122 122 def __init__(self,shell):
123 123 # XXX This is hackish, clean up later to avoid these messy globals
124 124 global MAGIC_PREFIX, MAGIC_ESCAPE
125 125
126 126 self.options_table = {}
127 127 MAGIC_PREFIX = shell.name+'.magic_'
128 128 MAGIC_ESCAPE = shell.ESC_MAGIC
129 129 if profile is None:
130 130 self.magic_prun = self.profile_missing_notice
131 131
132 132 def profile_missing_notice(self, *args, **kwargs):
133 133 error("""\
134 134 The profile module could not be found. If you are a Debian user,
135 135 it has been removed from the standard Debian package because of its non-free
136 136 license. To use profiling, please install"python2.3-profiler" from non-free.""")
137 137
138 138 def default_option(self,fn,optstr):
139 139 """Make an entry in the options_table for fn, with value optstr"""
140 140
141 141 if fn not in self.lsmagic():
142 142 error("%s is not a magic function" % fn)
143 143 self.options_table[fn] = optstr
144 144
145 145 def lsmagic(self):
146 146 """Return a list of currently available magic functions.
147 147
148 148 Gives a list of the bare names after mangling (['ls','cd', ...], not
149 149 ['magic_ls','magic_cd',...]"""
150 150
151 151 # FIXME. This needs a cleanup, in the way the magics list is built.
152 152
153 153 # magics in class definition
154 154 class_magic = lambda fn: fn.startswith('magic_') and \
155 155 callable(Magic.__dict__[fn])
156 156 # in instance namespace (run-time user additions)
157 157 inst_magic = lambda fn: fn.startswith('magic_') and \
158 158 callable(self.__dict__[fn])
159 159 # and bound magics by user (so they can access self):
160 160 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
161 161 callable(self.__class__.__dict__[fn])
162 162 magics = filter(class_magic,Magic.__dict__.keys()) + \
163 163 filter(inst_magic,self.__dict__.keys()) + \
164 164 filter(inst_bound_magic,self.__class__.__dict__.keys())
165 165 out = []
166 166 for fn in magics:
167 167 out.append(fn.replace('magic_','',1))
168 168 out.sort()
169 169 return out
170 170
171 171 def set_shell(self,shell):
172 172 self.shell = shell
173 173 self.alias_table = shell.alias_table
174 174
175 175 def extract_input_slices(self,slices):
176 176 """Return as a string a set of input history slices.
177 177
178 178 The set of slices is given as a list of strings (like ['1','4:8','9'],
179 179 since this function is for use by magic functions which get their
180 180 arguments as strings."""
181 181
182 182 cmds = []
183 183 for chunk in slices:
184 184 if ':' in chunk:
185 185 ini,fin = map(int,chunk.split(':'))
186 186 else:
187 187 ini = int(chunk)
188 188 fin = ini+1
189 189 cmds.append(self.shell.input_hist[ini:fin])
190 190 return cmds
191 191
192 192 def _ofind(self,oname):
193 193 """Find an object in the available namespaces.
194 194
195 195 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
196 196
197 197 Has special code to detect magic functions.
198 198 """
199 199
200 200 oname = oname.strip()
201 201
202 202 # Namespaces to search in:
203 203 user_ns = self.shell.user_ns
204 204 internal_ns = self.shell.internal_ns
205 205 builtin_ns = __builtin__.__dict__
206 206 alias_ns = self.shell.alias_table
207 207
208 208 # Put them in a list. The order is important so that we find things in
209 209 # the same order that Python finds them.
210 210 namespaces = [ ('Interactive',user_ns),
211 211 ('IPython internal',internal_ns),
212 212 ('Python builtin',builtin_ns),
213 213 ('Alias',alias_ns),
214 214 ]
215 215
216 216 # initialize results to 'null'
217 217 found = 0; obj = None; ospace = None; ds = None;
218 218 ismagic = 0; isalias = 0
219 219
220 220 # Look for the given name by splitting it in parts. If the head is
221 221 # found, then we look for all the remaining parts as members, and only
222 222 # declare success if we can find them all.
223 223 oname_parts = oname.split('.')
224 224 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
225 225 for nsname,ns in namespaces:
226 226 try:
227 227 obj = ns[oname_head]
228 228 except KeyError:
229 229 continue
230 230 else:
231 231 for part in oname_rest:
232 232 try:
233 233 obj = getattr(obj,part)
234 234 except:
235 235 # Blanket except b/c some badly implemented objects
236 236 # allow __getattr__ to raise exceptions other than
237 237 # AttributeError, which then crashes IPython.
238 238 break
239 239 else:
240 240 # If we finish the for loop (no break), we got all members
241 241 found = 1
242 242 ospace = nsname
243 243 if ns == alias_ns:
244 244 isalias = 1
245 245 break # namespace loop
246 246
247 247 # Try to see if it's magic
248 248 if not found:
249 249 if oname.startswith(self.shell.ESC_MAGIC):
250 250 oname = oname[1:]
251 251 obj = getattr(self,'magic_'+oname,None)
252 252 if obj is not None:
253 253 found = 1
254 254 ospace = 'IPython internal'
255 255 ismagic = 1
256 256
257 257 # Last try: special-case some literals like '', [], {}, etc:
258 258 if not found and oname_head in ["''",'""','[]','{}','()']:
259 259 obj = eval(oname_head)
260 260 found = 1
261 261 ospace = 'Interactive'
262 262
263 263 return {'found':found, 'obj':obj, 'namespace':ospace,
264 264 'ismagic':ismagic, 'isalias':isalias}
265 265
266 266 def arg_err(self,func):
267 267 """Print docstring if incorrect arguments were passed"""
268 268 print 'Error in arguments:'
269 269 print OInspect.getdoc(func)
270 270
271 271
272 272 def format_latex(self,str):
273 273 """Format a string for latex inclusion."""
274 274
275 275 # Characters that need to be escaped for latex:
276 276 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
277 277 # Magic command names as headers:
278 278 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
279 279 re.MULTILINE)
280 280 # Magic commands
281 281 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
282 282 re.MULTILINE)
283 283 # Paragraph continue
284 284 par_re = re.compile(r'\\$',re.MULTILINE)
285 285
286 286 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
287 287 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
288 288 str = par_re.sub(r'\\\\',str)
289 289 str = escape_re.sub(r'\\\1',str)
290 290 return str
291 291
292 292 def format_screen(self,str):
293 293 """Format a string for screen printing.
294 294
295 295 This removes some latex-type format codes."""
296 296 # Paragraph continue
297 297 par_re = re.compile(r'\\$',re.MULTILINE)
298 298 str = par_re.sub('',str)
299 299 return str
300 300
301 301 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
302 302 """Parse options passed to an argument string.
303 303
304 304 The interface is similar to that of getopt(), but it returns back a
305 305 Struct with the options as keys and the stripped argument string still
306 306 as a string.
307 307
308 308 arg_str is quoted as a true sys.argv vector by using shlex.split.
309 309 This allows us to easily expand variables, glob files, quote
310 310 arguments, etc.
311 311
312 312 Options:
313 313 -mode: default 'string'. If given as 'list', the argument string is
314 314 returned as a list (split on whitespace) instead of a string.
315 315
316 316 -list_all: put all option values in lists. Normally only options
317 317 appearing more than once are put in a list."""
318 318
319 319 # inject default options at the beginning of the input line
320 320 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
321 321 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
322 322
323 323 mode = kw.get('mode','string')
324 324 if mode not in ['string','list']:
325 325 raise ValueError,'incorrect mode given: %s' % mode
326 326 # Get options
327 327 list_all = kw.get('list_all',0)
328 328
329 329 # Check if we have more than one argument to warrant extra processing:
330 330 odict = {} # Dictionary with options
331 331 args = arg_str.split()
332 332 if len(args) >= 1:
333 333 # If the list of inputs only has 0 or 1 thing in it, there's no
334 334 # need to look for options
335 335 argv = shlex_split(arg_str)
336 336 # Do regular option processing
337 337 opts,args = getopt(argv,opt_str,*long_opts)
338 338 for o,a in opts:
339 339 if o.startswith('--'):
340 340 o = o[2:]
341 341 else:
342 342 o = o[1:]
343 343 try:
344 344 odict[o].append(a)
345 345 except AttributeError:
346 346 odict[o] = [odict[o],a]
347 347 except KeyError:
348 348 if list_all:
349 349 odict[o] = [a]
350 350 else:
351 351 odict[o] = a
352 352
353 353 # Prepare opts,args for return
354 354 opts = Struct(odict)
355 355 if mode == 'string':
356 356 args = ' '.join(args)
357 357
358 358 return opts,args
359 359
360 360 #......................................................................
361 361 # And now the actual magic functions
362 362
363 363 # Functions for IPython shell work (vars,funcs, config, etc)
364 364 def magic_lsmagic(self, parameter_s = ''):
365 365 """List currently available magic functions."""
366 366 mesc = self.shell.ESC_MAGIC
367 367 print 'Available magic functions:\n'+mesc+\
368 368 (' '+mesc).join(self.lsmagic())
369 369 print '\n' + Magic.auto_status[self.shell.rc.automagic]
370 370 return None
371 371
372 372 def magic_magic(self, parameter_s = ''):
373 373 """Print information about the magic function system."""
374 374
375 375 mode = ''
376 376 try:
377 377 if parameter_s.split()[0] == '-latex':
378 378 mode = 'latex'
379 379 except:
380 380 pass
381 381
382 382 magic_docs = []
383 383 for fname in self.lsmagic():
384 384 mname = 'magic_' + fname
385 385 for space in (Magic,self,self.__class__):
386 386 try:
387 387 fn = space.__dict__[mname]
388 388 except KeyError:
389 389 pass
390 390 else:
391 391 break
392 392 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
393 393 fname,fn.__doc__))
394 394 magic_docs = ''.join(magic_docs)
395 395
396 396 if mode == 'latex':
397 397 print self.format_latex(magic_docs)
398 398 return
399 399 else:
400 400 magic_docs = self.format_screen(magic_docs)
401 401
402 402 outmsg = """
403 403 IPython's 'magic' functions
404 404 ===========================
405 405
406 406 The magic function system provides a series of functions which allow you to
407 407 control the behavior of IPython itself, plus a lot of system-type
408 408 features. All these functions are prefixed with a % character, but parameters
409 409 are given without parentheses or quotes.
410 410
411 411 NOTE: If you have 'automagic' enabled (via the command line option or with the
412 412 %automagic function), you don't need to type in the % explicitly. By default,
413 413 IPython ships with automagic on, so you should only rarely need the % escape.
414 414
415 415 Example: typing '%cd mydir' (without the quotes) changes you working directory
416 416 to 'mydir', if it exists.
417 417
418 418 You can define your own magic functions to extend the system. See the supplied
419 419 ipythonrc and example-magic.py files for details (in your ipython
420 420 configuration directory, typically $HOME/.ipython/).
421 421
422 422 You can also define your own aliased names for magic functions. In your
423 423 ipythonrc file, placing a line like:
424 424
425 425 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
426 426
427 427 will define %pf as a new name for %profile.
428 428
429 429 You can also call magics in code using the ipmagic() function, which IPython
430 430 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
431 431
432 432 For a list of the available magic functions, use %lsmagic. For a description
433 433 of any of them, type %magic_name?, e.g. '%cd?'.
434 434
435 435 Currently the magic system has the following functions:\n"""
436 436
437 437 mesc = self.shell.ESC_MAGIC
438 438 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
439 439 "\n\n%s%s\n\n%s" % (outmsg,
440 440 magic_docs,mesc,mesc,
441 441 (' '+mesc).join(self.lsmagic()),
442 442 Magic.auto_status[self.shell.rc.automagic] ) )
443 443
444 444 page(outmsg,screen_lines=self.shell.rc.screen_length)
445 445
446 446 def magic_automagic(self, parameter_s = ''):
447 447 """Make magic functions callable without having to type the initial %.
448 448
449 449 Toggles on/off (when off, you must call it as %automagic, of
450 450 course). Note that magic functions have lowest priority, so if there's
451 451 a variable whose name collides with that of a magic fn, automagic
452 452 won't work for that function (you get the variable instead). However,
453 453 if you delete the variable (del var), the previously shadowed magic
454 454 function becomes visible to automagic again."""
455 455
456 456 rc = self.shell.rc
457 457 rc.automagic = not rc.automagic
458 458 print '\n' + Magic.auto_status[rc.automagic]
459 459
460 460 def magic_autocall(self, parameter_s = ''):
461 461 """Make functions callable without having to type parentheses.
462 462
463 463 This toggles the autocall command line option on and off."""
464 464
465 465 rc = self.shell.rc
466 466 rc.autocall = not rc.autocall
467 467 print "Automatic calling is:",['OFF','ON'][rc.autocall]
468 468
469 469 def magic_autoindent(self, parameter_s = ''):
470 470 """Toggle autoindent on/off (if available)."""
471 471
472 472 self.shell.set_autoindent()
473 473 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
474 474
475 475 def magic_system_verbose(self, parameter_s = ''):
476 476 """Toggle verbose printing of system calls on/off."""
477 477
478 478 self.shell.rc_set_toggle('system_verbose')
479 479 print "System verbose printing is:",\
480 480 ['OFF','ON'][self.shell.rc.system_verbose]
481 481
482 482 def magic_history(self, parameter_s = ''):
483 483 """Print input history (_i<n> variables), with most recent last.
484 484
485 485 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
486 486 %history [-n] n -> print at most n inputs\\
487 487 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
488 488
489 489 Each input's number <n> is shown, and is accessible as the
490 490 automatically generated variable _i<n>. Multi-line statements are
491 491 printed starting at a new line for easy copy/paste.
492 492
493 493 If option -n is used, input numbers are not printed. This is useful if
494 494 you want to get a printout of many lines which can be directly pasted
495 495 into a text editor.
496 496
497 497 This feature is only available if numbered prompts are in use."""
498 498
499 499 if not self.do_full_cache:
500 500 print 'This feature is only available if numbered prompts are in use.'
501 501 return
502 502 opts,args = self.parse_options(parameter_s,'n',mode='list')
503 503
504 504 default_length = 40
505 505 if len(args) == 0:
506 506 final = self.outputcache.prompt_count
507 507 init = max(1,final-default_length)
508 508 elif len(args) == 1:
509 509 final = self.outputcache.prompt_count
510 510 init = max(1,final-int(args[0]))
511 511 elif len(args) == 2:
512 512 init,final = map(int,args)
513 513 else:
514 514 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
515 515 print self.magic_hist.__doc__
516 516 return
517 517 width = len(str(final))
518 518 line_sep = ['','\n']
519 519 input_hist = self.shell.input_hist
520 520 print_nums = not opts.has_key('n')
521 521 for in_num in range(init,final):
522 522 inline = input_hist[in_num]
523 523 multiline = inline.count('\n') > 1
524 524 if print_nums:
525 525 print str(in_num).ljust(width)+':'+ line_sep[multiline],
526 526 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
527 527 inline.startswith('#!'):
528 528 print inline[1:],
529 529 else:
530 530 print inline,
531 531
532 532 def magic_hist(self, parameter_s=''):
533 533 """Alternate name for %history."""
534 534 return self.magic_history(parameter_s)
535 535
536 536 def magic_p(self, parameter_s=''):
537 537 """Just a short alias for Python's 'print'."""
538 538 exec 'print ' + parameter_s in self.shell.user_ns
539 539
540 540 def magic_r(self, parameter_s=''):
541 541 """Repeat previous input.
542 542
543 543 If given an argument, repeats the previous command which starts with
544 544 the same string, otherwise it just repeats the previous input.
545 545
546 546 Shell escaped commands (with ! as first character) are not recognized
547 547 by this system, only pure python code and magic commands.
548 548 """
549 549
550 550 start = parameter_s.strip()
551 551 esc_magic = self.shell.ESC_MAGIC
552 552 # Identify magic commands even if automagic is on (which means
553 553 # the in-memory version is different from that typed by the user).
554 554 if self.shell.rc.automagic:
555 555 start_magic = esc_magic+start
556 556 else:
557 557 start_magic = start
558 558 # Look through the input history in reverse
559 559 for n in range(len(self.shell.input_hist)-2,0,-1):
560 560 input = self.shell.input_hist[n]
561 561 # skip plain 'r' lines so we don't recurse to infinity
562 562 if input != 'ipmagic("r")\n' and \
563 563 (input.startswith(start) or input.startswith(start_magic)):
564 564 #print 'match',`input` # dbg
565 565 if input.startswith(esc_magic):
566 566 input = magic2python(input)
567 567 #print 'modified',`input` # dbg
568 568 print 'Executing:',input,
569 569 exec input in self.shell.user_ns
570 570 return
571 571 print 'No previous input matching `%s` found.' % start
572 572
573 573 def magic_page(self, parameter_s=''):
574 574 """Pretty print the object and display it through a pager.
575 575
576 576 If no parameter is given, use _ (last output)."""
577 577 # After a function contributed by Olivier Aubert, slightly modified.
578 578
579 579 oname = parameter_s and parameter_s or '_'
580 580 info = self._ofind(oname)
581 581 if info['found']:
582 582 page(pformat(info['obj']))
583 583 else:
584 584 print 'Object `%s` not found' % oname
585 585
586 586 def magic_profile(self, parameter_s=''):
587 587 """Print your currently active IPyhton profile."""
588 588 if self.shell.rc.profile:
589 589 printpl('Current IPython profile: $self.shell.rc.profile.')
590 590 else:
591 591 print 'No profile active.'
592 592
593 593 def _inspect(self,meth,oname,**kw):
594 594 """Generic interface to the inspector system.
595 595
596 596 This function is meant to be called by pdef, pdoc & friends."""
597 597
598 598 oname = oname.strip()
599 599 info = Struct(self._ofind(oname))
600 600 if info.found:
601 601 pmethod = getattr(self.shell.inspector,meth)
602 602 formatter = info.ismagic and self.format_screen or None
603 603 if meth == 'pdoc':
604 604 pmethod(info.obj,oname,formatter)
605 605 elif meth == 'pinfo':
606 606 pmethod(info.obj,oname,formatter,info,**kw)
607 607 else:
608 608 pmethod(info.obj,oname)
609 609 else:
610 610 print 'Object `%s` not found.' % oname
611 611 return 'not found' # so callers can take other action
612 612
613 613 def magic_pdef(self, parameter_s=''):
614 614 """Print the definition header for any callable object.
615 615
616 616 If the object is a class, print the constructor information."""
617 617 self._inspect('pdef',parameter_s)
618 618
619 619 def magic_pdoc(self, parameter_s=''):
620 620 """Print the docstring for an object.
621 621
622 622 If the given object is a class, it will print both the class and the
623 623 constructor docstrings."""
624 624 self._inspect('pdoc',parameter_s)
625 625
626 626 def magic_psource(self, parameter_s=''):
627 627 """Print (or run through pager) the source code for an object."""
628 628 self._inspect('psource',parameter_s)
629 629
630 630 def magic_pfile(self, parameter_s=''):
631 631 """Print (or run through pager) the file where an object is defined.
632 632
633 633 The file opens at the line where the object definition begins. IPython
634 634 will honor the environment variable PAGER if set, and otherwise will
635 635 do its best to print the file in a convenient form.
636 636
637 637 If the given argument is not an object currently defined, IPython will
638 638 try to interpret it as a filename (automatically adding a .py extension
639 639 if needed). You can thus use %pfile as a syntax highlighting code
640 640 viewer."""
641 641
642 642 # first interpret argument as an object name
643 643 out = self._inspect('pfile',parameter_s)
644 644 # if not, try the input as a filename
645 645 if out == 'not found':
646 646 try:
647 647 filename = get_py_filename(parameter_s)
648 648 except IOError,msg:
649 649 print msg
650 650 return
651 651 page(self.shell.inspector.format(file(filename).read()))
652 652
653 653 def magic_pinfo(self, parameter_s=''):
654 654 """Provide detailed information about an object.
655 655
656 656 '%pinfo object' is just a synonym for object? or ?object."""
657 657
658 658 #print 'pinfo par: <%s>' % parameter_s # dbg
659 659
660 660 # detail_level: 0 -> obj? , 1 -> obj??
661 661 detail_level = 0
662 662 # We need to detect if we got called as 'pinfo pinfo foo', which can
663 663 # happen if the user types 'pinfo foo?' at the cmd line.
664 664 pinfo,qmark1,oname,qmark2 = \
665 665 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
666 666 if pinfo or qmark1 or qmark2:
667 667 detail_level = 1
668 668 if "*" in oname:
669 669 self.magic_psearch(oname)
670 670 else:
671 671 self._inspect('pinfo',oname,detail_level=detail_level)
672 672
673 673 def magic_psearch(self, parameter_s=''):
674 674 """Search for object in namespaces by wildcard.
675 675
676 676 %psearch [options] PATTERN [OBJECT TYPE]
677 677
678 678 Note: ? can be used as a synonym for %psearch, at the beginning or at
679 679 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
680 680 rest of the command line must be unchanged (options come first), so
681 681 for example the following forms are equivalent
682 682
683 683 %psearch -i a* function
684 684 -i a* function?
685 685 ?-i a* function
686 686
687 687 Arguments:
688 688
689 689 PATTERN
690 690
691 691 where PATTERN is a string containing * as a wildcard similar to its
692 692 use in a shell. The pattern is matched in all namespaces on the
693 693 search path. By default objects starting with a single _ are not
694 694 matched, many IPython generated objects have a single
695 695 underscore. The default is case insensitive matching. Matching is
696 696 also done on the attributes of objects and not only on the objects
697 697 in a module.
698 698
699 699 [OBJECT TYPE]
700 700
701 701 Is the name of a python type from the types module. The name is
702 702 given in lowercase without the ending type, ex. StringType is
703 703 written string. By adding a type here only objects matching the
704 704 given type are matched. Using all here makes the pattern match all
705 705 types (this is the default).
706 706
707 707 Options:
708 708
709 709 -a: makes the pattern match even objects whose names start with a
710 710 single underscore. These names are normally ommitted from the
711 711 search.
712 712
713 713 -i/-c: make the pattern case insensitive/sensitive. If neither of
714 714 these options is given, the default is read from your ipythonrc
715 715 file. The option name which sets this value is
716 716 'wildcards_case_sensitive'. If this option is not specified in your
717 717 ipythonrc file, IPython's internal default is to do a case sensitive
718 718 search.
719 719
720 720 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
721 721 specifiy can be searched in any of the following namespaces:
722 722 'builtin', 'user', 'user_global','internal', 'alias', where
723 723 'builtin' and 'user' are the search defaults. Note that you should
724 724 not use quotes when specifying namespaces.
725 725
726 726 'Builtin' contains the python module builtin, 'user' contains all
727 727 user data, 'alias' only contain the shell aliases and no python
728 728 objects, 'internal' contains objects used by IPython. The
729 729 'user_global' namespace is only used by embedded IPython instances,
730 730 and it contains module-level globals. You can add namespaces to the
731 731 search with -s or exclude them with -e (these options can be given
732 732 more than once).
733 733
734 734 Examples:
735 735
736 736 %psearch a* -> objects beginning with an a
737 737 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
738 738 %psearch a* function -> all functions beginning with an a
739 739 %psearch re.e* -> objects beginning with an e in module re
740 740 %psearch r*.e* -> objects that start with e in modules starting in r
741 741 %psearch r*.* string -> all strings in modules beginning with r
742 742
743 743 Case sensitve search:
744 744
745 745 %psearch -c a* list all object beginning with lower case a
746 746
747 747 Show objects beginning with a single _:
748 748
749 749 %psearch -a _* list objects beginning with a single underscore"""
750 750
751 751 # default namespaces to be searched
752 752 def_search = ['user','builtin']
753 753
754 754 # Process options/args
755 755 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
756 756 opt = opts.get
757 757 shell = self.shell
758 758 psearch = shell.inspector.psearch
759 759
760 760 # select case options
761 761 if opts.has_key('i'):
762 762 ignore_case = True
763 763 elif opts.has_key('c'):
764 764 ignore_case = False
765 765 else:
766 766 ignore_case = not shell.rc.wildcards_case_sensitive
767 767
768 768 # Build list of namespaces to search from user options
769 769 def_search.extend(opt('s',[]))
770 770 ns_exclude = ns_exclude=opt('e',[])
771 771 ns_search = [nm for nm in def_search if nm not in ns_exclude]
772 772
773 773 # Call the actual search
774 774 try:
775 775 psearch(args,shell.ns_table,ns_search,
776 776 show_all=opt('a'),ignore_case=ignore_case)
777 777 except:
778 778 shell.showtraceback()
779 779
780 780 def magic_who_ls(self, parameter_s=''):
781 781 """Return a sorted list of all interactive variables.
782 782
783 783 If arguments are given, only variables of types matching these
784 784 arguments are returned."""
785 785
786 786 user_ns = self.shell.user_ns
787 787 out = []
788 788 typelist = parameter_s.split()
789 789 for i in self.shell.user_ns.keys():
790 790 if not (i.startswith('_') or i.startswith('_i')) \
791 791 and not (self.internal_ns.has_key(i) or
792 792 self.user_config_ns.has_key(i)):
793 793 if typelist:
794 794 if type(user_ns[i]).__name__ in typelist:
795 795 out.append(i)
796 796 else:
797 797 out.append(i)
798 798 out.sort()
799 799 return out
800 800
801 801 def magic_who(self, parameter_s=''):
802 802 """Print all interactive variables, with some minimal formatting.
803 803
804 804 If any arguments are given, only variables whose type matches one of
805 805 these are printed. For example:
806 806
807 807 %who function str
808 808
809 809 will only list functions and strings, excluding all other types of
810 810 variables. To find the proper type names, simply use type(var) at a
811 811 command line to see how python prints type names. For example:
812 812
813 813 In [1]: type('hello')\\
814 814 Out[1]: <type 'str'>
815 815
816 816 indicates that the type name for strings is 'str'.
817 817
818 818 %who always excludes executed names loaded through your configuration
819 819 file and things which are internal to IPython.
820 820
821 821 This is deliberate, as typically you may load many modules and the
822 822 purpose of %who is to show you only what you've manually defined."""
823 823
824 824 varlist = self.magic_who_ls(parameter_s)
825 825 if not varlist:
826 826 print 'Interactive namespace is empty.'
827 827 return
828 828
829 829 # if we have variables, move on...
830 830
831 831 # stupid flushing problem: when prompts have no separators, stdout is
832 832 # getting lost. I'm starting to think this is a python bug. I'm having
833 833 # to force a flush with a print because even a sys.stdout.flush
834 834 # doesn't seem to do anything!
835 835
836 836 count = 0
837 837 for i in varlist:
838 838 print i+'\t',
839 839 count += 1
840 840 if count > 8:
841 841 count = 0
842 842 print
843 843 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
844 844
845 845 print # well, this does force a flush at the expense of an extra \n
846 846
847 847 def magic_whos(self, parameter_s=''):
848 848 """Like %who, but gives some extra information about each variable.
849 849
850 850 The same type filtering of %who can be applied here.
851 851
852 852 For all variables, the type is printed. Additionally it prints:
853 853
854 854 - For {},[],(): their length.
855 855
856 856 - For Numeric arrays, a summary with shape, number of elements,
857 857 typecode and size in memory.
858 858
859 859 - Everything else: a string representation, snipping their middle if
860 860 too long."""
861 861
862 862 varnames = self.magic_who_ls(parameter_s)
863 863 if not varnames:
864 864 print 'Interactive namespace is empty.'
865 865 return
866 866
867 867 # if we have variables, move on...
868 868
869 869 # for these types, show len() instead of data:
870 870 seq_types = [types.DictType,types.ListType,types.TupleType]
871 871
872 872 # for Numeric arrays, display summary info
873 873 try:
874 874 import Numeric
875 875 except ImportError:
876 876 array_type = None
877 877 else:
878 878 array_type = Numeric.ArrayType.__name__
879 879
880 880 # Find all variable names and types so we can figure out column sizes
881 881 get_vars = lambda i: self.shell.user_ns[i]
882 882 type_name = lambda v: type(v).__name__
883 883 varlist = map(get_vars,varnames)
884 884 typelist = map(type_name,varlist)
885 885 # column labels and # of spaces as separator
886 886 varlabel = 'Variable'
887 887 typelabel = 'Type'
888 888 datalabel = 'Data/Info'
889 889 colsep = 3
890 890 # variable format strings
891 891 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
892 892 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
893 893 aformat = "%s: %s elems, type `%s`, %s bytes"
894 894 # find the size of the columns to format the output nicely
895 895 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
896 896 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
897 897 # table header
898 898 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
899 899 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
900 900 # and the table itself
901 901 kb = 1024
902 902 Mb = 1048576 # kb**2
903 903 for vname,var,vtype in zip(varnames,varlist,typelist):
904 904 print itpl(vformat),
905 905 if vtype in seq_types:
906 906 print len(var)
907 907 elif vtype==array_type:
908 908 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
909 909 vsize = Numeric.size(var)
910 910 vbytes = vsize*var.itemsize()
911 911 if vbytes < 100000:
912 912 print aformat % (vshape,vsize,var.typecode(),vbytes)
913 913 else:
914 914 print aformat % (vshape,vsize,var.typecode(),vbytes),
915 915 if vbytes < Mb:
916 916 print '(%s kb)' % (vbytes/kb,)
917 917 else:
918 918 print '(%s Mb)' % (vbytes/Mb,)
919 919 else:
920 920 vstr = str(var)
921 921 if len(vstr) < 50:
922 922 print vstr
923 923 else:
924 924 printpl(vfmt_short)
925 925
926 926 def magic_reset(self, parameter_s=''):
927 927 """Resets the namespace by removing all names defined by the user.
928 928
929 929 Input/Output history are left around in case you need them."""
930 930
931 931 ans = raw_input(
932 932 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
933 933 if not ans.lower() == 'y':
934 934 print 'Nothing done.'
935 935 return
936 936 user_ns = self.shell.user_ns
937 937 for i in self.magic_who_ls():
938 938 del(user_ns[i])
939 939
940 940 def magic_config(self,parameter_s=''):
941 941 """Show IPython's internal configuration."""
942 942
943 943 page('Current configuration structure:\n'+
944 944 pformat(self.shell.rc.dict()))
945 945
946 946 def magic_logstart(self,parameter_s=''):
947 947 """Start logging anywhere in a session.
948 948
949 949 %logstart [log_name [log_mode]]
950 950
951 951 If no name is given, it defaults to a file named 'ipython.log' in your
952 952 current directory, in 'rotate' mode (see below).
953 953
954 954 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
955 955 history up to that point and then continues logging.
956 956
957 957 %logstart takes a second optional parameter: logging mode. This can be one
958 958 of (note that the modes are given unquoted):\\
959 959 over: overwrite existing log.\\
960 960 backup: rename (if exists) to name~ and start name.\\
961 961 append: well, that says it.\\
962 962 rotate: create rotating logs name.1~, name.2~, etc.
963 963 """
964 964
965 965 #FIXME. This function should all be moved to the Logger class.
966 966
967 967 valid_modes = qw('over backup append rotate')
968 968 if self.LOG:
969 969 print 'Logging is already in place. Logfile:',self.LOG
970 970 return
971 971
972 972 par = parameter_s.strip()
973 973 if not par:
974 974 logname = self.LOGDEF
975 975 logmode = 'rotate' # use rotate for the auto-generated logs
976 976 else:
977 977 try:
978 978 logname,logmode = par.split()
979 979 except:
980 980 try:
981 981 logname = par
982 982 logmode = 'backup'
983 983 except:
984 984 warn('Usage: %log [log_name [log_mode]]')
985 985 return
986 986 if not logmode in valid_modes:
987 987 warn('Logging NOT activated.\n'
988 988 'Usage: %log [log_name [log_mode]]\n'
989 989 'Valid modes: '+str(valid_modes))
990 990 return
991 991
992 992 # If we made it this far, I think we're ok:
993 993 print 'Activating auto-logging.'
994 994 print 'Current session state plus future input saved to:',logname
995 995 print 'Logging mode: ',logmode
996 996 # put logname into rc struct as if it had been called on the command line,
997 997 # so it ends up saved in the log header
998 998 # Save it in case we need to restore it...
999 999 old_logfile = self.shell.rc.opts.get('logfile','')
1000 1000 logname = os.path.expanduser(logname)
1001 1001 self.shell.rc.opts.logfile = logname
1002 1002 self.LOGMODE = logmode # FIXME: this should be set through a function.
1003 1003 try:
1004 1004 header = str(self.LOGHEAD)
1005 1005 self.create_log(header,logname)
1006 1006 self.logstart(header,logname)
1007 1007 except:
1008 1008 self.LOG = '' # we are NOT logging, something went wrong
1009 1009 self.shell.rc.opts.logfile = old_logfile
1010 1010 warn("Couldn't start log: "+str(sys.exc_info()[1]))
1011 1011 else: # log input history up to this point
1012 1012 self.logfile.write(self.shell.user_ns['_ih'][1:])
1013 1013 self.logfile.flush()
1014 1014
1015 1015 def magic_logoff(self,parameter_s=''):
1016 1016 """Temporarily stop logging.
1017 1017
1018 1018 You must have previously started logging."""
1019 1019 self.switch_log(0)
1020 1020
1021 1021 def magic_logon(self,parameter_s=''):
1022 1022 """Restart logging.
1023 1023
1024 1024 This function is for restarting logging which you've temporarily
1025 1025 stopped with %logoff. For starting logging for the first time, you
1026 1026 must use the %logstart function, which allows you to specify an
1027 1027 optional log filename."""
1028 1028
1029 1029 self.switch_log(1)
1030 1030
1031 1031 def magic_logstate(self,parameter_s=''):
1032 1032 """Print the status of the logging system."""
1033 1033
1034 1034 self.logstate()
1035 1035
1036 1036 def magic_pdb(self, parameter_s=''):
1037 1037 """Control the calling of the pdb interactive debugger.
1038 1038
1039 1039 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1040 1040 argument it works as a toggle.
1041 1041
1042 1042 When an exception is triggered, IPython can optionally call the
1043 1043 interactive pdb debugger after the traceback printout. %pdb toggles
1044 1044 this feature on and off."""
1045 1045
1046 1046 par = parameter_s.strip().lower()
1047 1047
1048 1048 if par:
1049 1049 try:
1050 1050 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1051 1051 except KeyError:
1052 1052 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
1053 1053 return
1054 1054 else:
1055 1055 self.shell.InteractiveTB.call_pdb = pdb
1056 1056 else:
1057 1057 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
1058 1058 print 'Automatic pdb calling has been turned',\
1059 1059 on_off(self.shell.InteractiveTB.call_pdb)
1060 1060
1061 1061
1062 1062 def magic_prun(self, parameter_s ='',user_mode=1,
1063 1063 opts=None,arg_lst=None,prog_ns=None):
1064 1064
1065 1065 """Run a statement through the python code profiler.
1066 1066
1067 1067 Usage:\\
1068 1068 %prun [options] statement
1069 1069
1070 1070 The given statement (which doesn't require quote marks) is run via the
1071 1071 python profiler in a manner similar to the profile.run() function.
1072 1072 Namespaces are internally managed to work correctly; profile.run
1073 1073 cannot be used in IPython because it makes certain assumptions about
1074 1074 namespaces which do not hold under IPython.
1075 1075
1076 1076 Options:
1077 1077
1078 1078 -l <limit>: you can place restrictions on what or how much of the
1079 1079 profile gets printed. The limit value can be:
1080 1080
1081 1081 * A string: only information for function names containing this string
1082 1082 is printed.
1083 1083
1084 1084 * An integer: only these many lines are printed.
1085 1085
1086 1086 * A float (between 0 and 1): this fraction of the report is printed
1087 1087 (for example, use a limit of 0.4 to see the topmost 40% only).
1088 1088
1089 1089 You can combine several limits with repeated use of the option. For
1090 1090 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1091 1091 information about class constructors.
1092 1092
1093 1093 -r: return the pstats.Stats object generated by the profiling. This
1094 1094 object has all the information about the profile in it, and you can
1095 1095 later use it for further analysis or in other functions.
1096 1096
1097 1097 Since magic functions have a particular form of calling which prevents
1098 1098 you from writing something like:\\
1099 1099 In [1]: p = %prun -r print 4 # invalid!\\
1100 1100 you must instead use IPython's automatic variables to assign this:\\
1101 1101 In [1]: %prun -r print 4 \\
1102 1102 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1103 1103 In [2]: stats = _
1104 1104
1105 1105 If you really need to assign this value via an explicit function call,
1106 1106 you can always tap directly into the true name of the magic function
1107 1107 by using the ipmagic function (which IPython automatically adds to the
1108 1108 builtins):\\
1109 1109 In [3]: stats = ipmagic('prun','-r print 4')
1110 1110
1111 1111 You can type ipmagic? for more details on ipmagic.
1112 1112
1113 1113 -s <key>: sort profile by given key. You can provide more than one key
1114 1114 by using the option several times: '-s key1 -s key2 -s key3...'. The
1115 1115 default sorting key is 'time'.
1116 1116
1117 1117 The following is copied verbatim from the profile documentation
1118 1118 referenced below:
1119 1119
1120 1120 When more than one key is provided, additional keys are used as
1121 1121 secondary criteria when the there is equality in all keys selected
1122 1122 before them.
1123 1123
1124 1124 Abbreviations can be used for any key names, as long as the
1125 1125 abbreviation is unambiguous. The following are the keys currently
1126 1126 defined:
1127 1127
1128 1128 Valid Arg Meaning\\
1129 1129 "calls" call count\\
1130 1130 "cumulative" cumulative time\\
1131 1131 "file" file name\\
1132 1132 "module" file name\\
1133 1133 "pcalls" primitive call count\\
1134 1134 "line" line number\\
1135 1135 "name" function name\\
1136 1136 "nfl" name/file/line\\
1137 1137 "stdname" standard name\\
1138 1138 "time" internal time
1139 1139
1140 1140 Note that all sorts on statistics are in descending order (placing
1141 1141 most time consuming items first), where as name, file, and line number
1142 1142 searches are in ascending order (i.e., alphabetical). The subtle
1143 1143 distinction between "nfl" and "stdname" is that the standard name is a
1144 1144 sort of the name as printed, which means that the embedded line
1145 1145 numbers get compared in an odd way. For example, lines 3, 20, and 40
1146 1146 would (if the file names were the same) appear in the string order
1147 1147 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1148 1148 line numbers. In fact, sort_stats("nfl") is the same as
1149 1149 sort_stats("name", "file", "line").
1150 1150
1151 1151 -T <filename>: save profile results as shown on screen to a text
1152 1152 file. The profile is still shown on screen.
1153 1153
1154 1154 -D <filename>: save (via dump_stats) profile statistics to given
1155 1155 filename. This data is in a format understod by the pstats module, and
1156 1156 is generated by a call to the dump_stats() method of profile
1157 1157 objects. The profile is still shown on screen.
1158 1158
1159 1159 If you want to run complete programs under the profiler's control, use
1160 1160 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1161 1161 contains profiler specific options as described here.
1162 1162
1163 1163 You can read the complete documentation for the profile module with:\\
1164 1164 In [1]: import profile; profile.help() """
1165 1165
1166 1166 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1167 1167 # protect user quote marks
1168 1168 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1169 1169
1170 1170 if user_mode: # regular user call
1171 1171 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1172 1172 list_all=1)
1173 1173 namespace = self.shell.user_ns
1174 1174 else: # called to run a program by %run -p
1175 1175 try:
1176 1176 filename = get_py_filename(arg_lst[0])
1177 1177 except IOError,msg:
1178 1178 error(msg)
1179 1179 return
1180 1180
1181 1181 arg_str = 'execfile(filename,prog_ns)'
1182 1182 namespace = locals()
1183 1183
1184 1184 opts.merge(opts_def)
1185 1185
1186 1186 prof = profile.Profile()
1187 1187 try:
1188 1188 prof = prof.runctx(arg_str,namespace,namespace)
1189 1189 sys_exit = ''
1190 1190 except SystemExit:
1191 1191 sys_exit = """*** SystemExit exception caught in code being profiled."""
1192 1192
1193 1193 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1194 1194
1195 1195 lims = opts.l
1196 1196 if lims:
1197 1197 lims = [] # rebuild lims with ints/floats/strings
1198 1198 for lim in opts.l:
1199 1199 try:
1200 1200 lims.append(int(lim))
1201 1201 except ValueError:
1202 1202 try:
1203 1203 lims.append(float(lim))
1204 1204 except ValueError:
1205 1205 lims.append(lim)
1206 1206
1207 1207 # trap output
1208 1208 sys_stdout = sys.stdout
1209 1209 stdout_trap = StringIO()
1210 1210 try:
1211 1211 sys.stdout = stdout_trap
1212 1212 stats.print_stats(*lims)
1213 1213 finally:
1214 1214 sys.stdout = sys_stdout
1215 1215 output = stdout_trap.getvalue()
1216 1216 output = output.rstrip()
1217 1217
1218 1218 page(output,screen_lines=self.shell.rc.screen_length)
1219 1219 print sys_exit,
1220 1220
1221 1221 dump_file = opts.D[0]
1222 1222 text_file = opts.T[0]
1223 1223 if dump_file:
1224 1224 prof.dump_stats(dump_file)
1225 1225 print '\n*** Profile stats marshalled to file',\
1226 1226 `dump_file`+'.',sys_exit
1227 1227 if text_file:
1228 1228 file(text_file,'w').write(output)
1229 1229 print '\n*** Profile printout saved to text file',\
1230 1230 `text_file`+'.',sys_exit
1231 1231
1232 1232 if opts.has_key('r'):
1233 1233 return stats
1234 1234 else:
1235 1235 return None
1236 1236
1237 1237 def magic_run(self, parameter_s ='',runner=None):
1238 1238 """Run the named file inside IPython as a program.
1239 1239
1240 1240 Usage:\\
1241 1241 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1242 1242
1243 1243 Parameters after the filename are passed as command-line arguments to
1244 1244 the program (put in sys.argv). Then, control returns to IPython's
1245 1245 prompt.
1246 1246
1247 1247 This is similar to running at a system prompt:\\
1248 1248 $ python file args\\
1249 1249 but with the advantage of giving you IPython's tracebacks, and of
1250 1250 loading all variables into your interactive namespace for further use
1251 1251 (unless -p is used, see below).
1252 1252
1253 1253 The file is executed in a namespace initially consisting only of
1254 1254 __name__=='__main__' and sys.argv constructed as indicated. It thus
1255 1255 sees its environment as if it were being run as a stand-alone
1256 1256 program. But after execution, the IPython interactive namespace gets
1257 1257 updated with all variables defined in the program (except for __name__
1258 1258 and sys.argv). This allows for very convenient loading of code for
1259 1259 interactive work, while giving each program a 'clean sheet' to run in.
1260 1260
1261 1261 Options:
1262 1262
1263 1263 -n: __name__ is NOT set to '__main__', but to the running file's name
1264 1264 without extension (as python does under import). This allows running
1265 1265 scripts and reloading the definitions in them without calling code
1266 1266 protected by an ' if __name__ == "__main__" ' clause.
1267 1267
1268 1268 -i: run the file in IPython's namespace instead of an empty one. This
1269 1269 is useful if you are experimenting with code written in a text editor
1270 1270 which depends on variables defined interactively.
1271 1271
1272 1272 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1273 1273 being run. This is particularly useful if IPython is being used to
1274 1274 run unittests, which always exit with a sys.exit() call. In such
1275 1275 cases you are interested in the output of the test results, not in
1276 1276 seeing a traceback of the unittest module.
1277 1277
1278 1278 -t: print timing information at the end of the run. IPython will give
1279 1279 you an estimated CPU time consumption for your script, which under
1280 1280 Unix uses the resource module to avoid the wraparound problems of
1281 1281 time.clock(). Under Unix, an estimate of time spent on system tasks
1282 1282 is also given (for Windows platforms this is reported as 0.0).
1283 1283
1284 1284 If -t is given, an additional -N<N> option can be given, where <N>
1285 1285 must be an integer indicating how many times you want the script to
1286 1286 run. The final timing report will include total and per run results.
1287 1287
1288 1288 For example (testing the script uniq_stable.py):
1289 1289
1290 1290 In [1]: run -t uniq_stable
1291 1291
1292 1292 IPython CPU timings (estimated):\\
1293 1293 User : 0.19597 s.\\
1294 1294 System: 0.0 s.\\
1295 1295
1296 1296 In [2]: run -t -N5 uniq_stable
1297 1297
1298 1298 IPython CPU timings (estimated):\\
1299 1299 Total runs performed: 5\\
1300 1300 Times : Total Per run\\
1301 1301 User : 0.910862 s, 0.1821724 s.\\
1302 1302 System: 0.0 s, 0.0 s.
1303 1303
1304 1304 -d: run your program under the control of pdb, the Python debugger.
1305 1305 This allows you to execute your program step by step, watch variables,
1306 1306 etc. Internally, what IPython does is similar to calling:
1307 1307
1308 1308 pdb.run('execfile("YOURFILENAME")')
1309 1309
1310 1310 with a breakpoint set on line 1 of your file. You can change the line
1311 1311 number for this automatic breakpoint to be <N> by using the -bN option
1312 1312 (where N must be an integer). For example:
1313 1313
1314 1314 %run -d -b40 myscript
1315 1315
1316 1316 will set the first breakpoint at line 40 in myscript.py. Note that
1317 1317 the first breakpoint must be set on a line which actually does
1318 1318 something (not a comment or docstring) for it to stop execution.
1319 1319
1320 1320 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1321 1321 first enter 'c' (without qoutes) to start execution up to the first
1322 1322 breakpoint.
1323 1323
1324 1324 Entering 'help' gives information about the use of the debugger. You
1325 1325 can easily see pdb's full documentation with "import pdb;pdb.help()"
1326 1326 at a prompt.
1327 1327
1328 1328 -p: run program under the control of the Python profiler module (which
1329 1329 prints a detailed report of execution times, function calls, etc).
1330 1330
1331 1331 You can pass other options after -p which affect the behavior of the
1332 1332 profiler itself. See the docs for %prun for details.
1333 1333
1334 1334 In this mode, the program's variables do NOT propagate back to the
1335 1335 IPython interactive namespace (because they remain in the namespace
1336 1336 where the profiler executes them).
1337 1337
1338 1338 Internally this triggers a call to %prun, see its documentation for
1339 1339 details on the options available specifically for profiling."""
1340 1340
1341 1341 # get arguments and set sys.argv for program to be run.
1342 1342 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1343 1343 mode='list',list_all=1)
1344 1344
1345 1345 try:
1346 1346 filename = get_py_filename(arg_lst[0])
1347 1347 except IndexError:
1348 1348 warn('you must provide at least a filename.')
1349 1349 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1350 1350 return
1351 1351 except IOError,msg:
1352 1352 error(msg)
1353 1353 return
1354 1354
1355 1355 # Control the response to exit() calls made by the script being run
1356 1356 exit_ignore = opts.has_key('e')
1357 1357
1358 1358 # Make sure that the running script gets a proper sys.argv as if it
1359 1359 # were run from a system shell.
1360 1360 save_argv = sys.argv # save it for later restoring
1361 1361 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1362 1362
1363 1363 if opts.has_key('i'):
1364 1364 prog_ns = self.shell.user_ns
1365 1365 __name__save = self.shell.user_ns['__name__']
1366 1366 prog_ns['__name__'] = '__main__'
1367 1367 else:
1368 1368 if opts.has_key('n'):
1369 1369 name = os.path.splitext(os.path.basename(filename))[0]
1370 1370 else:
1371 1371 name = '__main__'
1372 1372 prog_ns = {'__name__':name}
1373 1373
1374 1374 # pickle fix. See iplib for an explanation
1375 1375 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1376 1376
1377 1377 stats = None
1378 1378 try:
1379 1379 if opts.has_key('p'):
1380 1380 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1381 1381 else:
1382 1382 if opts.has_key('d'):
1383 1383 deb = Debugger.Pdb(self.shell.rc.colors)
1384 1384 # reset Breakpoint state, which is moronically kept
1385 1385 # in a class
1386 1386 bdb.Breakpoint.next = 1
1387 1387 bdb.Breakpoint.bplist = {}
1388 1388 bdb.Breakpoint.bpbynumber = [None]
1389 1389 # Set an initial breakpoint to stop execution
1390 1390 maxtries = 10
1391 1391 bp = int(opts.get('b',[1])[0])
1392 1392 checkline = deb.checkline(filename,bp)
1393 1393 if not checkline:
1394 1394 for bp in range(bp+1,bp+maxtries+1):
1395 1395 if deb.checkline(filename,bp):
1396 1396 break
1397 1397 else:
1398 1398 msg = ("\nI failed to find a valid line to set "
1399 1399 "a breakpoint\n"
1400 1400 "after trying up to line: %s.\n"
1401 1401 "Please set a valid breakpoint manually "
1402 1402 "with the -b option." % bp)
1403 1403 error(msg)
1404 1404 return
1405 1405 # if we find a good linenumber, set the breakpoint
1406 1406 deb.do_break('%s:%s' % (filename,bp))
1407 1407 # Start file run
1408 1408 print "NOTE: Enter 'c' at the",
1409 1409 print "ipdb> prompt to start your script."
1410 1410 try:
1411 1411 deb.run('execfile("%s")' % filename,prog_ns)
1412 1412 except:
1413 1413 etype, value, tb = sys.exc_info()
1414 1414 # Skip three frames in the traceback: the %run one,
1415 1415 # one inside bdb.py, and the command-line typed by the
1416 1416 # user (run by exec in pdb itself).
1417 1417 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1418 1418 else:
1419 1419 if runner is None:
1420 1420 runner = self.shell.safe_execfile
1421 1421 if opts.has_key('t'):
1422 1422 try:
1423 1423 nruns = int(opts['N'][0])
1424 1424 if nruns < 1:
1425 1425 error('Number of runs must be >=1')
1426 1426 return
1427 1427 except (KeyError):
1428 1428 nruns = 1
1429 1429 if nruns == 1:
1430 1430 t0 = clock2()
1431 1431 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1432 1432 t1 = clock2()
1433 1433 t_usr = t1[0]-t0[0]
1434 1434 t_sys = t1[1]-t1[1]
1435 1435 print "\nIPython CPU timings (estimated):"
1436 1436 print " User : %10s s." % t_usr
1437 1437 print " System: %10s s." % t_sys
1438 1438 else:
1439 1439 runs = range(nruns)
1440 1440 t0 = clock2()
1441 1441 for nr in runs:
1442 1442 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1443 1443 t1 = clock2()
1444 1444 t_usr = t1[0]-t0[0]
1445 1445 t_sys = t1[1]-t1[1]
1446 1446 print "\nIPython CPU timings (estimated):"
1447 1447 print "Total runs performed:",nruns
1448 1448 print " Times : %10s %10s" % ('Total','Per run')
1449 1449 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1450 1450 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1451 1451
1452 1452 else:
1453 1453 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1454 1454 if opts.has_key('i'):
1455 1455 self.shell.user_ns['__name__'] = __name__save
1456 1456 else:
1457 1457 # update IPython interactive namespace
1458 1458 del prog_ns['__name__']
1459 1459 self.shell.user_ns.update(prog_ns)
1460 1460 finally:
1461 1461 sys.argv = save_argv
1462 1462 return stats
1463 1463
1464 1464 def magic_runlog(self, parameter_s =''):
1465 1465 """Run files as logs.
1466 1466
1467 1467 Usage:\\
1468 1468 %runlog file1 file2 ...
1469 1469
1470 1470 Run the named files (treating them as log files) in sequence inside
1471 1471 the interpreter, and return to the prompt. This is much slower than
1472 1472 %run because each line is executed in a try/except block, but it
1473 1473 allows running files with syntax errors in them.
1474 1474
1475 1475 Normally IPython will guess when a file is one of its own logfiles, so
1476 1476 you can typically use %run even for logs. This shorthand allows you to
1477 1477 force any file to be treated as a log file."""
1478 1478
1479 1479 for f in parameter_s.split():
1480 1480 self.shell.safe_execfile(f,self.shell.user_ns,
1481 1481 self.shell.user_ns,islog=1)
1482 1482
1483 1483 def magic_time(self,parameter_s = ''):
1484 1484 """Time execution of a Python statement or expression.
1485 1485
1486 1486 The CPU and wall clock times are printed, and the value of the
1487 1487 expression (if any) is returned. Note that under Win32, system time
1488 1488 is always reported as 0, since it can not be measured.
1489 1489
1490 1490 This function provides very basic timing functionality. In Python
1491 1491 2.3, the timeit module offers more control and sophistication, but for
1492 1492 now IPython supports Python 2.2, so we can not rely on timeit being
1493 1493 present.
1494 1494
1495 1495 Some examples:
1496 1496
1497 1497 In [1]: time 2**128
1498 1498 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1499 1499 Wall time: 0.00
1500 1500 Out[1]: 340282366920938463463374607431768211456L
1501 1501
1502 1502 In [2]: n = 1000000
1503 1503
1504 1504 In [3]: time sum(range(n))
1505 1505 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1506 1506 Wall time: 1.37
1507 1507 Out[3]: 499999500000L
1508 1508
1509 1509 In [4]: time print 'hello world'
1510 1510 hello world
1511 1511 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1512 1512 Wall time: 0.00
1513 1513 """
1514 1514
1515 1515 # fail immediately if the given expression can't be compiled
1516 1516 try:
1517 1517 mode = 'eval'
1518 1518 code = compile(parameter_s,'<timed eval>',mode)
1519 1519 except SyntaxError:
1520 1520 mode = 'exec'
1521 1521 code = compile(parameter_s,'<timed exec>',mode)
1522 1522 # skew measurement as little as possible
1523 1523 glob = self.shell.user_ns
1524 1524 clk = clock2
1525 1525 wtime = time.time
1526 1526 # time execution
1527 1527 wall_st = wtime()
1528 1528 if mode=='eval':
1529 1529 st = clk()
1530 1530 out = eval(code,glob)
1531 1531 end = clk()
1532 1532 else:
1533 1533 st = clk()
1534 1534 exec code in glob
1535 1535 end = clk()
1536 1536 out = None
1537 1537 wall_end = wtime()
1538 1538 # Compute actual times and report
1539 1539 wall_time = wall_end-wall_st
1540 1540 cpu_user = end[0]-st[0]
1541 1541 cpu_sys = end[1]-st[1]
1542 1542 cpu_tot = cpu_user+cpu_sys
1543 1543 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1544 1544 (cpu_user,cpu_sys,cpu_tot)
1545 1545 print "Wall time: %.2f" % wall_time
1546 1546 return out
1547 1547
1548 1548 def magic_macro(self,parameter_s = ''):
1549 1549 """Define a set of input lines as a macro for future re-execution.
1550 1550
1551 1551 Usage:\\
1552 1552 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1553 1553
1554 1554 This will define a global variable called `name` which is a string
1555 1555 made of joining the slices and lines you specify (n1,n2,... numbers
1556 1556 above) from your input history into a single string. This variable
1557 1557 acts like an automatic function which re-executes those lines as if
1558 1558 you had typed them. You just type 'name' at the prompt and the code
1559 1559 executes.
1560 1560
1561 1561 Note that the slices use the standard Python slicing notation (5:8
1562 1562 means include lines numbered 5,6,7).
1563 1563
1564 1564 For example, if your history contains (%hist prints it):
1565 1565
1566 1566 44: x=1\\
1567 1567 45: y=3\\
1568 1568 46: z=x+y\\
1569 1569 47: print x\\
1570 1570 48: a=5\\
1571 1571 49: print 'x',x,'y',y\\
1572 1572
1573 1573 you can create a macro with lines 44 through 47 (included) and line 49
1574 1574 called my_macro with:
1575 1575
1576 1576 In [51]: %macro my_macro 44:48 49
1577 1577
1578 1578 Now, typing `my_macro` (without quotes) will re-execute all this code
1579 1579 in one pass.
1580 1580
1581 1581 You don't need to give the line-numbers in order, and any given line
1582 1582 number can appear multiple times. You can assemble macros with any
1583 1583 lines from your input history in any order.
1584 1584
1585 1585 The macro is a simple object which holds its value in an attribute,
1586 1586 but IPython's display system checks for macros and executes them as
1587 1587 code instead of printing them when you type their name.
1588 1588
1589 1589 You can view a macro's contents by explicitly printing it with:
1590 1590
1591 1591 'print macro_name'.
1592 1592
1593 1593 For one-off cases which DON'T contain magic function calls in them you
1594 1594 can obtain similar results by explicitly executing slices from your
1595 1595 input history with:
1596 1596
1597 1597 In [60]: exec In[44:48]+In[49]"""
1598 1598
1599 1599 args = parameter_s.split()
1600 1600 name,ranges = args[0], args[1:]
1601 1601 #print 'rng',ranges # dbg
1602 1602 cmds = self.extract_input_slices(ranges)
1603 1603 macro = Macro(cmds)
1604 1604 self.shell.user_ns.update({name:macro})
1605 1605 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1606 1606 print 'Macro contents:'
1607 1607 print str(macro).rstrip(),
1608 1608
1609 1609 def magic_save(self,parameter_s = ''):
1610 1610 """Save a set of lines to a given filename.
1611 1611
1612 1612 Usage:\\
1613 1613 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1614 1614
1615 1615 This function uses the same syntax as %macro for line extraction, but
1616 1616 instead of creating a macro it saves the resulting string to the
1617 1617 filename you specify.
1618 1618
1619 1619 It adds a '.py' extension to the file if you don't do so yourself, and
1620 1620 it asks for confirmation before overwriting existing files."""
1621 1621
1622 1622 args = parameter_s.split()
1623 1623 fname,ranges = args[0], args[1:]
1624 1624 if not fname.endswith('.py'):
1625 1625 fname += '.py'
1626 1626 if os.path.isfile(fname):
1627 1627 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1628 1628 if ans.lower() not in ['y','yes']:
1629 1629 print 'Operation cancelled.'
1630 1630 return
1631 1631 cmds = ''.join(self.extract_input_slices(ranges))
1632 1632 f = file(fname,'w')
1633 1633 f.write(cmds)
1634 1634 f.close()
1635 1635 print 'The following commands were written to file `%s`:' % fname
1636 1636 print cmds
1637 1637
1638 1638 def magic_ed(self,parameter_s = ''):
1639 1639 """Alias to %edit."""
1640 1640 return self.magic_edit(parameter_s)
1641 1641
1642 1642 def magic_edit(self,parameter_s = '',last_call=['','']):
1643 1643 """Bring up an editor and execute the resulting code.
1644 1644
1645 1645 Usage:
1646 1646 %edit [options] [args]
1647 1647
1648 1648 %edit runs IPython's editor hook. The default version of this hook is
1649 1649 set to call the __IPYTHON__.rc.editor command. This is read from your
1650 1650 environment variable $EDITOR. If this isn't found, it will default to
1651 1651 vi under Linux/Unix and to notepad under Windows. See the end of this
1652 1652 docstring for how to change the editor hook.
1653 1653
1654 1654 You can also set the value of this editor via the command line option
1655 1655 '-editor' or in your ipythonrc file. This is useful if you wish to use
1656 1656 specifically for IPython an editor different from your typical default
1657 1657 (and for Windows users who typically don't set environment variables).
1658 1658
1659 1659 This command allows you to conveniently edit multi-line code right in
1660 1660 your IPython session.
1661 1661
1662 1662 If called without arguments, %edit opens up an empty editor with a
1663 1663 temporary file and will execute the contents of this file when you
1664 1664 close it (don't forget to save it!).
1665 1665
1666 1666 Options:
1667 1667
1668 1668 -p: this will call the editor with the same data as the previous time
1669 1669 it was used, regardless of how long ago (in your current session) it
1670 1670 was.
1671 1671
1672 1672 -x: do not execute the edited code immediately upon exit. This is
1673 1673 mainly useful if you are editing programs which need to be called with
1674 1674 command line arguments, which you can then do using %run.
1675 1675
1676 1676 Arguments:
1677 1677
1678 1678 If arguments are given, the following possibilites exist:
1679 1679
1680 1680 - The arguments are numbers or pairs of colon-separated numbers (like
1681 1681 1 4:8 9). These are interpreted as lines of previous input to be
1682 1682 loaded into the editor. The syntax is the same of the %macro command.
1683 1683
1684 1684 - If the argument doesn't start with a number, it is evaluated as a
1685 1685 variable and its contents loaded into the editor. You can thus edit
1686 1686 any string which contains python code (including the result of
1687 1687 previous edits).
1688 1688
1689 1689 - If the argument is the name of an object (other than a string),
1690 1690 IPython will try to locate the file where it was defined and open the
1691 1691 editor at the point where it is defined. You can use `%edit function`
1692 1692 to load an editor exactly at the point where 'function' is defined,
1693 1693 edit it and have the file be executed automatically.
1694 1694
1695 1695 Note: opening at an exact line is only supported under Unix, and some
1696 1696 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1697 1697 '+NUMBER' parameter necessary for this feature. Good editors like
1698 1698 (X)Emacs, vi, jed, pico and joe all do.
1699 1699
1700 1700 - If the argument is not found as a variable, IPython will look for a
1701 1701 file with that name (adding .py if necessary) and load it into the
1702 1702 editor. It will execute its contents with execfile() when you exit,
1703 1703 loading any code in the file into your interactive namespace.
1704 1704
1705 1705 After executing your code, %edit will return as output the code you
1706 1706 typed in the editor (except when it was an existing file). This way
1707 1707 you can reload the code in further invocations of %edit as a variable,
1708 1708 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1709 1709 the output.
1710 1710
1711 1711 Note that %edit is also available through the alias %ed.
1712 1712
1713 1713 This is an example of creating a simple function inside the editor and
1714 1714 then modifying it. First, start up the editor:
1715 1715
1716 1716 In [1]: ed\\
1717 1717 Editing... done. Executing edited code...\\
1718 1718 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1719 1719
1720 1720 We can then call the function foo():
1721 1721
1722 1722 In [2]: foo()\\
1723 1723 foo() was defined in an editing session
1724 1724
1725 1725 Now we edit foo. IPython automatically loads the editor with the
1726 1726 (temporary) file where foo() was previously defined:
1727 1727
1728 1728 In [3]: ed foo\\
1729 1729 Editing... done. Executing edited code...
1730 1730
1731 1731 And if we call foo() again we get the modified version:
1732 1732
1733 1733 In [4]: foo()\\
1734 1734 foo() has now been changed!
1735 1735
1736 1736 Here is an example of how to edit a code snippet successive
1737 1737 times. First we call the editor:
1738 1738
1739 1739 In [8]: ed\\
1740 1740 Editing... done. Executing edited code...\\
1741 1741 hello\\
1742 1742 Out[8]: "print 'hello'\\n"
1743 1743
1744 1744 Now we call it again with the previous output (stored in _):
1745 1745
1746 1746 In [9]: ed _\\
1747 1747 Editing... done. Executing edited code...\\
1748 1748 hello world\\
1749 1749 Out[9]: "print 'hello world'\\n"
1750 1750
1751 1751 Now we call it with the output #8 (stored in _8, also as Out[8]):
1752 1752
1753 1753 In [10]: ed _8\\
1754 1754 Editing... done. Executing edited code...\\
1755 1755 hello again\\
1756 1756 Out[10]: "print 'hello again'\\n"
1757 1757
1758 1758
1759 1759 Changing the default editor hook:
1760 1760
1761 1761 If you wish to write your own editor hook, you can put it in a
1762 1762 configuration file which you load at startup time. The default hook
1763 1763 is defined in the IPython.hooks module, and you can use that as a
1764 1764 starting example for further modifications. That file also has
1765 1765 general instructions on how to set a new hook for use once you've
1766 1766 defined it."""
1767 1767
1768 1768 # FIXME: This function has become a convoluted mess. It needs a
1769 1769 # ground-up rewrite with clean, simple logic.
1770 1770
1771 1771 def make_filename(arg):
1772 1772 "Make a filename from the given args"
1773 1773 try:
1774 1774 filename = get_py_filename(arg)
1775 1775 except IOError:
1776 1776 if args.endswith('.py'):
1777 1777 filename = arg
1778 1778 else:
1779 1779 filename = None
1780 1780 return filename
1781 1781
1782 1782 # custom exceptions
1783 1783 class DataIsObject(Exception): pass
1784 1784
1785 1785 opts,args = self.parse_options(parameter_s,'px')
1786 1786
1787 1787 # Default line number value
1788 1788 lineno = None
1789 1789 if opts.has_key('p'):
1790 1790 args = '_%s' % last_call[0]
1791 1791 if not self.shell.user_ns.has_key(args):
1792 1792 args = last_call[1]
1793 1793
1794 1794 # use last_call to remember the state of the previous call, but don't
1795 1795 # let it be clobbered by successive '-p' calls.
1796 1796 try:
1797 1797 last_call[0] = self.shell.outputcache.prompt_count
1798 1798 if not opts.has_key('p'):
1799 1799 last_call[1] = parameter_s
1800 1800 except:
1801 1801 pass
1802 1802
1803 1803 # by default this is done with temp files, except when the given
1804 1804 # arg is a filename
1805 1805 use_temp = 1
1806 1806
1807 1807 if re.match(r'\d',args):
1808 1808 # Mode where user specifies ranges of lines, like in %macro.
1809 1809 # This means that you can't edit files whose names begin with
1810 1810 # numbers this way. Tough.
1811 1811 ranges = args.split()
1812 1812 data = ''.join(self.extract_input_slices(ranges))
1813 1813 elif args.endswith('.py'):
1814 1814 filename = make_filename(args)
1815 1815 data = ''
1816 1816 use_temp = 0
1817 1817 elif args:
1818 1818 try:
1819 1819 # Load the parameter given as a variable. If not a string,
1820 1820 # process it as an object instead (below)
1821 1821
1822 1822 #print '*** args',args,'type',type(args) # dbg
1823 1823 data = eval(args,self.shell.user_ns)
1824 1824 if not type(data) in StringTypes:
1825 1825 raise DataIsObject
1826 1826 except (NameError,SyntaxError):
1827 1827 # given argument is not a variable, try as a filename
1828 1828 filename = make_filename(args)
1829 1829 if filename is None:
1830 1830 warn("Argument given (%s) can't be found as a variable "
1831 1831 "or as a filename." % args)
1832 1832 return
1833 1833 data = ''
1834 1834 use_temp = 0
1835 1835 except DataIsObject:
1836 1836 # For objects, try to edit the file where they are defined
1837 1837 try:
1838 1838 filename = inspect.getabsfile(data)
1839 1839 datafile = 1
1840 1840 except TypeError:
1841 1841 filename = make_filename(args)
1842 1842 datafile = 1
1843 1843 warn('Could not find file where `%s` is defined.\n'
1844 1844 'Opening a file named `%s`' % (args,filename))
1845 1845 # Now, make sure we can actually read the source (if it was in
1846 1846 # a temp file it's gone by now).
1847 1847 if datafile:
1848 1848 try:
1849 1849 lineno = inspect.getsourcelines(data)[1]
1850 1850 except IOError:
1851 1851 filename = make_filename(args)
1852 1852 if filename is None:
1853 1853 warn('The file `%s` where `%s` was defined cannot '
1854 1854 'be read.' % (filename,data))
1855 1855 return
1856 1856 use_temp = 0
1857 1857 else:
1858 1858 data = ''
1859 1859
1860 1860 if use_temp:
1861 1861 filename = tempfile.mktemp('.py')
1862 1862 self.shell.tempfiles.append(filename)
1863 1863
1864 1864 if data and use_temp:
1865 1865 tmp_file = open(filename,'w')
1866 1866 tmp_file.write(data)
1867 1867 tmp_file.close()
1868 1868
1869 1869 # do actual editing here
1870 1870 print 'Editing...',
1871 1871 sys.stdout.flush()
1872 1872 self.shell.hooks.editor(filename,lineno)
1873 1873 if opts.has_key('x'): # -x prevents actual execution
1874 1874 print
1875 1875 else:
1876 1876 print 'done. Executing edited code...'
1877 1877 try:
1878 execfile(filename,self.shell.user_ns)
1878 self.shell.safe_execfile(filename,self.shell.user_ns)
1879 1879 except IOError,msg:
1880 1880 if msg.filename == filename:
1881 1881 warn('File not found. Did you forget to save?')
1882 1882 return
1883 1883 else:
1884 1884 self.shell.showtraceback()
1885 1885 except:
1886 1886 self.shell.showtraceback()
1887 1887 if use_temp:
1888 1888 contents = open(filename).read()
1889 1889 return contents
1890 1890
1891 1891 def magic_xmode(self,parameter_s = ''):
1892 1892 """Switch modes for the exception handlers.
1893 1893
1894 1894 Valid modes: Plain, Context and Verbose.
1895 1895
1896 1896 If called without arguments, acts as a toggle."""
1897 1897
1898 1898 new_mode = parameter_s.strip().capitalize()
1899 1899 try:
1900 1900 self.InteractiveTB.set_mode(mode = new_mode)
1901 1901 print 'Exception reporting mode:',self.InteractiveTB.mode
1902 1902 except:
1903 1903 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1904 1904
1905 1905 def magic_colors(self,parameter_s = ''):
1906 1906 """Switch color scheme for prompts, info system and exception handlers.
1907 1907
1908 1908 Currently implemented schemes: NoColor, Linux, LightBG.
1909 1909
1910 1910 Color scheme names are not case-sensitive."""
1911 1911
1912 1912 new_scheme = parameter_s.strip()
1913 1913 if not new_scheme:
1914 1914 print 'You must specify a color scheme.'
1915 1915 return
1916 1916 # Under Windows, check for Gary Bishop's readline, which is necessary
1917 1917 # for ANSI coloring
1918 1918 if os.name in ['nt','dos']:
1919 1919 try:
1920 1920 import readline
1921 1921 except ImportError:
1922 1922 has_readline = 0
1923 1923 else:
1924 1924 try:
1925 1925 readline.GetOutputFile()
1926 1926 except AttributeError:
1927 1927 has_readline = 0
1928 1928 else:
1929 1929 has_readline = 1
1930 1930 if not has_readline:
1931 1931 msg = """\
1932 1932 Proper color support under MS Windows requires Gary Bishop's readline library.
1933 1933 You can find it at:
1934 1934 http://sourceforge.net/projects/uncpythontools
1935 1935 Gary's readline needs the ctypes module, from:
1936 1936 http://starship.python.net/crew/theller/ctypes
1937 1937
1938 1938 Defaulting color scheme to 'NoColor'"""
1939 1939 new_scheme = 'NoColor'
1940 1940 warn(msg)
1941 1941
1942 1942 # Set prompt colors
1943 1943 try:
1944 1944 self.shell.outputcache.set_colors(new_scheme)
1945 1945 except:
1946 1946 warn('Error changing prompt color schemes.\n'
1947 1947 + str(sys.exc_info()[1]))
1948 1948 else:
1949 1949 self.shell.rc.colors = \
1950 1950 self.shell.outputcache.color_table.active_scheme_name
1951 1951 # Set exception colors
1952 1952 try:
1953 1953 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1954 1954 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1955 1955 except:
1956 1956 warn('Error changing exception color schemes.\n'
1957 1957 + str(sys.exc_info()[1]))
1958 1958 # Set info (for 'object?') colors
1959 1959 if self.shell.rc.color_info:
1960 1960 try:
1961 1961 self.shell.inspector.set_active_scheme(new_scheme)
1962 1962 except:
1963 1963 warn('Error changing object inspector color schemes.\n'
1964 1964 + str(sys.exc_info()[1]))
1965 1965 else:
1966 1966 self.shell.inspector.set_active_scheme('NoColor')
1967 1967
1968 1968 def magic_color_info(self,parameter_s = ''):
1969 1969 """Toggle color_info.
1970 1970
1971 1971 The color_info configuration parameter controls whether colors are
1972 1972 used for displaying object details (by things like %psource, %pfile or
1973 1973 the '?' system). This function toggles this value with each call.
1974 1974
1975 1975 Note that unless you have a fairly recent pager (less works better
1976 1976 than more) in your system, using colored object information displays
1977 1977 will not work properly. Test it and see."""
1978 1978
1979 1979 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1980 1980 self.magic_colors(self.shell.rc.colors)
1981 1981 print 'Object introspection functions have now coloring:',
1982 1982 print ['OFF','ON'][self.shell.rc.color_info]
1983 1983
1984 1984 def magic_Pprint(self, parameter_s=''):
1985 1985 """Toggle pretty printing on/off."""
1986 1986
1987 1987 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1988 1988 print 'Pretty printing has been turned', \
1989 1989 ['OFF','ON'][self.shell.outputcache.Pprint]
1990 1990
1991 1991 def magic_Exit(self, parameter_s=''):
1992 1992 """Exit IPython without confirmation."""
1993 1993
1994 1994 self.shell.exit_now = True
1995 1995
1996 1996 def magic_Quit(self, parameter_s=''):
1997 1997 """Exit IPython without confirmation (like %Exit)."""
1998 1998
1999 1999 self.shell.exit_now = True
2000 2000
2001 2001 #......................................................................
2002 2002 # Functions to implement unix shell-type things
2003 2003
2004 2004 def magic_alias(self, parameter_s = ''):
2005 2005 """Define an alias for a system command.
2006 2006
2007 2007 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2008 2008
2009 2009 Then, typing 'alias_name params' will execute the system command 'cmd
2010 2010 params' (from your underlying operating system).
2011 2011
2012 2012 Aliases have lower precedence than magic functions and Python normal
2013 2013 variables, so if 'foo' is both a Python variable and an alias, the
2014 2014 alias can not be executed until 'del foo' removes the Python variable.
2015 2015
2016 2016 You can use the %l specifier in an alias definition to represent the
2017 2017 whole line when the alias is called. For example:
2018 2018
2019 2019 In [2]: alias all echo "Input in brackets: <%l>"\\
2020 2020 In [3]: all hello world\\
2021 2021 Input in brackets: <hello world>
2022 2022
2023 2023 You can also define aliases with parameters using %s specifiers (one
2024 2024 per parameter):
2025 2025
2026 2026 In [1]: alias parts echo first %s second %s\\
2027 2027 In [2]: %parts A B\\
2028 2028 first A second B\\
2029 2029 In [3]: %parts A\\
2030 2030 Incorrect number of arguments: 2 expected.\\
2031 2031 parts is an alias to: 'echo first %s second %s'
2032 2032
2033 2033 Note that %l and %s are mutually exclusive. You can only use one or
2034 2034 the other in your aliases.
2035 2035
2036 2036 Aliases expand Python variables just like system calls using ! or !!
2037 2037 do: all expressions prefixed with '$' get expanded. For details of
2038 2038 the semantic rules, see PEP-215:
2039 2039 http://www.python.org/peps/pep-0215.html. This is the library used by
2040 2040 IPython for variable expansion. If you want to access a true shell
2041 2041 variable, an extra $ is necessary to prevent its expansion by IPython:
2042 2042
2043 2043 In [6]: alias show echo\\
2044 2044 In [7]: PATH='A Python string'\\
2045 2045 In [8]: show $PATH\\
2046 2046 A Python string\\
2047 2047 In [9]: show $$PATH\\
2048 2048 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2049 2049
2050 2050 You can use the alias facility to acess all of $PATH. See the %rehash
2051 2051 and %rehashx functions, which automatically create aliases for the
2052 2052 contents of your $PATH.
2053 2053
2054 2054 If called with no parameters, %alias prints the current alias table."""
2055 2055
2056 2056 par = parameter_s.strip()
2057 2057 if not par:
2058 2058 if self.shell.rc.automagic:
2059 2059 prechar = ''
2060 2060 else:
2061 2061 prechar = self.shell.ESC_MAGIC
2062 2062 print 'Alias\t\tSystem Command\n'+'-'*30
2063 2063 atab = self.shell.alias_table
2064 2064 aliases = atab.keys()
2065 2065 aliases.sort()
2066 2066 for alias in aliases:
2067 2067 print prechar+alias+'\t\t'+atab[alias][1]
2068 2068 print '-'*30+'\nTotal number of aliases:',len(aliases)
2069 2069 return
2070 2070 try:
2071 2071 alias,cmd = par.split(None,1)
2072 2072 except:
2073 2073 print OInspect.getdoc(self.magic_alias)
2074 2074 else:
2075 2075 nargs = cmd.count('%s')
2076 2076 if nargs>0 and cmd.find('%l')>=0:
2077 2077 error('The %s and %l specifiers are mutually exclusive '
2078 2078 'in alias definitions.')
2079 2079 else: # all looks OK
2080 2080 self.shell.alias_table[alias] = (nargs,cmd)
2081 2081 self.shell.alias_table_validate(verbose=1)
2082 2082 # end magic_alias
2083 2083
2084 2084 def magic_unalias(self, parameter_s = ''):
2085 2085 """Remove an alias"""
2086 2086
2087 2087 aname = parameter_s.strip()
2088 2088 if aname in self.shell.alias_table:
2089 2089 del self.shell.alias_table[aname]
2090 2090
2091 2091 def magic_rehash(self, parameter_s = ''):
2092 2092 """Update the alias table with all entries in $PATH.
2093 2093
2094 2094 This version does no checks on execute permissions or whether the
2095 2095 contents of $PATH are truly files (instead of directories or something
2096 2096 else). For such a safer (but slower) version, use %rehashx."""
2097 2097
2098 2098 # This function (and rehashx) manipulate the alias_table directly
2099 2099 # rather than calling magic_alias, for speed reasons. A rehash on a
2100 2100 # typical Linux box involves several thousand entries, so efficiency
2101 2101 # here is a top concern.
2102 2102
2103 2103 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2104 2104 alias_table = self.shell.alias_table
2105 2105 for pdir in path:
2106 2106 for ff in os.listdir(pdir):
2107 2107 # each entry in the alias table must be (N,name), where
2108 2108 # N is the number of positional arguments of the alias.
2109 2109 alias_table[ff] = (0,ff)
2110 2110 # Make sure the alias table doesn't contain keywords or builtins
2111 2111 self.shell.alias_table_validate()
2112 2112 # Call again init_auto_alias() so we get 'rm -i' and other modified
2113 2113 # aliases since %rehash will probably clobber them
2114 2114 self.shell.init_auto_alias()
2115 2115
2116 2116 def magic_rehashx(self, parameter_s = ''):
2117 2117 """Update the alias table with all executable files in $PATH.
2118 2118
2119 2119 This version explicitly checks that every entry in $PATH is a file
2120 2120 with execute access (os.X_OK), so it is much slower than %rehash.
2121 2121
2122 2122 Under Windows, it checks executability as a match agains a
2123 2123 '|'-separated string of extensions, stored in the IPython config
2124 2124 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2125 2125
2126 2126 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2127 2127 alias_table = self.shell.alias_table
2128 2128
2129 2129 if os.name == 'posix':
2130 2130 isexec = lambda fname:os.path.isfile(fname) and \
2131 2131 os.access(fname,os.X_OK)
2132 2132 else:
2133 2133
2134 2134 try:
2135 2135 winext = os.environ['pathext'].replace(';','|').replace('.','')
2136 2136 except KeyError:
2137 2137 winext = 'exe|com|bat'
2138 2138
2139 2139 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2140 2140 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2141 2141 savedir = os.getcwd()
2142 2142 try:
2143 2143 # write the whole loop for posix/Windows so we don't have an if in
2144 2144 # the innermost part
2145 2145 if os.name == 'posix':
2146 2146 for pdir in path:
2147 2147 os.chdir(pdir)
2148 2148 for ff in os.listdir(pdir):
2149 2149 if isexec(ff):
2150 2150 # each entry in the alias table must be (N,name),
2151 2151 # where N is the number of positional arguments of the
2152 2152 # alias.
2153 2153 alias_table[ff] = (0,ff)
2154 2154 else:
2155 2155 for pdir in path:
2156 2156 os.chdir(pdir)
2157 2157 for ff in os.listdir(pdir):
2158 2158 if isexec(ff):
2159 2159 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2160 2160 # Make sure the alias table doesn't contain keywords or builtins
2161 2161 self.shell.alias_table_validate()
2162 2162 # Call again init_auto_alias() so we get 'rm -i' and other
2163 2163 # modified aliases since %rehashx will probably clobber them
2164 2164 self.shell.init_auto_alias()
2165 2165 finally:
2166 2166 os.chdir(savedir)
2167 2167
2168 2168 def magic_pwd(self, parameter_s = ''):
2169 2169 """Return the current working directory path."""
2170 2170 return os.getcwd()
2171 2171
2172 2172 def magic_cd(self, parameter_s=''):
2173 2173 """Change the current working directory.
2174 2174
2175 2175 This command automatically maintains an internal list of directories
2176 2176 you visit during your IPython session, in the variable _dh. The
2177 2177 command %dhist shows this history nicely formatted.
2178 2178
2179 2179 Usage:
2180 2180
2181 2181 cd 'dir': changes to directory 'dir'.
2182 2182
2183 2183 cd -: changes to the last visited directory.
2184 2184
2185 2185 cd -<n>: changes to the n-th directory in the directory history.
2186 2186
2187 2187 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2188 2188 (note: cd <bookmark_name> is enough if there is no
2189 2189 directory <bookmark_name>, but a bookmark with the name exists.)
2190 2190
2191 2191 Options:
2192 2192
2193 2193 -q: quiet. Do not print the working directory after the cd command is
2194 2194 executed. By default IPython's cd command does print this directory,
2195 2195 since the default prompts do not display path information.
2196 2196
2197 2197 Note that !cd doesn't work for this purpose because the shell where
2198 2198 !command runs is immediately discarded after executing 'command'."""
2199 2199
2200 2200 parameter_s = parameter_s.strip()
2201 2201 bkms = self.shell.persist.get("bookmarks",{})
2202 2202
2203 2203 numcd = re.match(r'(-)(\d+)$',parameter_s)
2204 2204 # jump in directory history by number
2205 2205 if numcd:
2206 2206 nn = int(numcd.group(2))
2207 2207 try:
2208 2208 ps = self.shell.user_ns['_dh'][nn]
2209 2209 except IndexError:
2210 2210 print 'The requested directory does not exist in history.'
2211 2211 return
2212 2212 else:
2213 2213 opts = {}
2214 2214 else:
2215 2215 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2216 2216 # jump to previous
2217 2217 if ps == '-':
2218 2218 try:
2219 2219 ps = self.shell.user_ns['_dh'][-2]
2220 2220 except IndexError:
2221 2221 print 'No previous directory to change to.'
2222 2222 return
2223 2223 # jump to bookmark
2224 2224 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2225 2225 if bkms.has_key(ps):
2226 2226 target = bkms[ps]
2227 2227 print '(bookmark:%s) -> %s' % (ps,target)
2228 2228 ps = target
2229 2229 else:
2230 2230 if bkms:
2231 2231 error("Bookmark '%s' not found. "
2232 2232 "Use '%bookmark -l' to see your bookmarks." % ps)
2233 2233 else:
2234 2234 print "Bookmarks not set - use %bookmark <bookmarkname>"
2235 2235 return
2236 2236
2237 2237 # at this point ps should point to the target dir
2238 2238 if ps:
2239 2239 try:
2240 2240 os.chdir(os.path.expanduser(ps))
2241 2241 except OSError:
2242 2242 print sys.exc_info()[1]
2243 2243 else:
2244 2244 self.shell.user_ns['_dh'].append(os.getcwd())
2245 2245 else:
2246 2246 os.chdir(self.home_dir)
2247 2247 self.shell.user_ns['_dh'].append(os.getcwd())
2248 2248 if not 'q' in opts:
2249 2249 print self.shell.user_ns['_dh'][-1]
2250 2250
2251 2251 def magic_dhist(self, parameter_s=''):
2252 2252 """Print your history of visited directories.
2253 2253
2254 2254 %dhist -> print full history\\
2255 2255 %dhist n -> print last n entries only\\
2256 2256 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2257 2257
2258 2258 This history is automatically maintained by the %cd command, and
2259 2259 always available as the global list variable _dh. You can use %cd -<n>
2260 2260 to go to directory number <n>."""
2261 2261
2262 2262 dh = self.shell.user_ns['_dh']
2263 2263 if parameter_s:
2264 2264 try:
2265 2265 args = map(int,parameter_s.split())
2266 2266 except:
2267 2267 self.arg_err(Magic.magic_dhist)
2268 2268 return
2269 2269 if len(args) == 1:
2270 2270 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2271 2271 elif len(args) == 2:
2272 2272 ini,fin = args
2273 2273 else:
2274 2274 self.arg_err(Magic.magic_dhist)
2275 2275 return
2276 2276 else:
2277 2277 ini,fin = 0,len(dh)
2278 2278 nlprint(dh,
2279 2279 header = 'Directory history (kept in _dh)',
2280 2280 start=ini,stop=fin)
2281 2281
2282 2282 def magic_env(self, parameter_s=''):
2283 2283 """List environment variables."""
2284 2284
2285 2285 # environ is an instance of UserDict
2286 2286 return os.environ.data
2287 2287
2288 2288 def magic_pushd(self, parameter_s=''):
2289 2289 """Place the current dir on stack and change directory.
2290 2290
2291 2291 Usage:\\
2292 2292 %pushd ['dirname']
2293 2293
2294 2294 %pushd with no arguments does a %pushd to your home directory.
2295 2295 """
2296 2296 if parameter_s == '': parameter_s = '~'
2297 2297 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2298 2298 os.path.expanduser(self.dir_stack[0]):
2299 2299 try:
2300 2300 self.magic_cd(parameter_s)
2301 2301 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2302 2302 self.magic_dirs()
2303 2303 except:
2304 2304 print 'Invalid directory'
2305 2305 else:
2306 2306 print 'You are already there!'
2307 2307
2308 2308 def magic_popd(self, parameter_s=''):
2309 2309 """Change to directory popped off the top of the stack.
2310 2310 """
2311 2311 if len (self.dir_stack) > 1:
2312 2312 self.dir_stack.pop(0)
2313 2313 self.magic_cd(self.dir_stack[0])
2314 2314 print self.dir_stack[0]
2315 2315 else:
2316 2316 print "You can't remove the starting directory from the stack:",\
2317 2317 self.dir_stack
2318 2318
2319 2319 def magic_dirs(self, parameter_s=''):
2320 2320 """Return the current directory stack."""
2321 2321
2322 2322 return self.dir_stack[:]
2323 2323
2324 2324 def magic_sc(self, parameter_s=''):
2325 2325 """Shell capture - execute a shell command and capture its output.
2326 2326
2327 2327 %sc [options] varname=command
2328 2328
2329 2329 IPython will run the given command using commands.getoutput(), and
2330 2330 will then update the user's interactive namespace with a variable
2331 2331 called varname, containing the value of the call. Your command can
2332 2332 contain shell wildcards, pipes, etc.
2333 2333
2334 2334 The '=' sign in the syntax is mandatory, and the variable name you
2335 2335 supply must follow Python's standard conventions for valid names.
2336 2336
2337 2337 Options:
2338 2338
2339 2339 -l: list output. Split the output on newlines into a list before
2340 2340 assigning it to the given variable. By default the output is stored
2341 2341 as a single string.
2342 2342
2343 2343 -v: verbose. Print the contents of the variable.
2344 2344
2345 2345 In most cases you should not need to split as a list, because the
2346 2346 returned value is a special type of string which can automatically
2347 2347 provide its contents either as a list (split on newlines) or as a
2348 2348 space-separated string. These are convenient, respectively, either
2349 2349 for sequential processing or to be passed to a shell command.
2350 2350
2351 2351 For example:
2352 2352
2353 2353 # Capture into variable a
2354 2354 In [9]: sc a=ls *py
2355 2355
2356 2356 # a is a string with embedded newlines
2357 2357 In [10]: a
2358 2358 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2359 2359
2360 2360 # which can be seen as a list:
2361 2361 In [11]: a.l
2362 2362 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2363 2363
2364 2364 # or as a whitespace-separated string:
2365 2365 In [12]: a.s
2366 2366 Out[12]: 'setup.py win32_manual_post_install.py'
2367 2367
2368 2368 # a.s is useful to pass as a single command line:
2369 2369 In [13]: !wc -l $a.s
2370 2370 146 setup.py
2371 2371 130 win32_manual_post_install.py
2372 2372 276 total
2373 2373
2374 2374 # while the list form is useful to loop over:
2375 2375 In [14]: for f in a.l:
2376 2376 ....: !wc -l $f
2377 2377 ....:
2378 2378 146 setup.py
2379 2379 130 win32_manual_post_install.py
2380 2380
2381 2381 Similiarly, the lists returned by the -l option are also special, in
2382 2382 the sense that you can equally invoke the .s attribute on them to
2383 2383 automatically get a whitespace-separated string from their contents:
2384 2384
2385 2385 In [1]: sc -l b=ls *py
2386 2386
2387 2387 In [2]: b
2388 2388 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2389 2389
2390 2390 In [3]: b.s
2391 2391 Out[3]: 'setup.py win32_manual_post_install.py'
2392 2392
2393 2393 In summary, both the lists and strings used for ouptut capture have
2394 2394 the following special attributes:
2395 2395
2396 2396 .l (or .list) : value as list.
2397 2397 .n (or .nlstr): value as newline-separated string.
2398 2398 .s (or .spstr): value as space-separated string.
2399 2399 """
2400 2400
2401 2401 opts,args = self.parse_options(parameter_s,'lv')
2402 2402 # Try to get a variable name and command to run
2403 2403 try:
2404 2404 # the variable name must be obtained from the parse_options
2405 2405 # output, which uses shlex.split to strip options out.
2406 2406 var,_ = args.split('=',1)
2407 2407 var = var.strip()
2408 2408 # But the the command has to be extracted from the original input
2409 2409 # parameter_s, not on what parse_options returns, to avoid the
2410 2410 # quote stripping which shlex.split performs on it.
2411 2411 _,cmd = parameter_s.split('=',1)
2412 2412 except ValueError:
2413 2413 var,cmd = '',''
2414 2414 if not var:
2415 2415 error('you must specify a variable to assign the command to.')
2416 2416 return
2417 2417 # If all looks ok, proceed
2418 2418 out,err = self.shell.getoutputerror(cmd)
2419 2419 if err:
2420 2420 print >> Term.cerr,err
2421 2421 if opts.has_key('l'):
2422 2422 out = SList(out.split('\n'))
2423 2423 else:
2424 2424 out = LSString(out)
2425 2425 if opts.has_key('v'):
2426 2426 print '%s ==\n%s' % (var,pformat(out))
2427 2427 self.shell.user_ns.update({var:out})
2428 2428
2429 2429 def magic_sx(self, parameter_s=''):
2430 2430 """Shell execute - run a shell command and capture its output.
2431 2431
2432 2432 %sx command
2433 2433
2434 2434 IPython will run the given command using commands.getoutput(), and
2435 2435 return the result formatted as a list (split on '\\n'). Since the
2436 2436 output is _returned_, it will be stored in ipython's regular output
2437 2437 cache Out[N] and in the '_N' automatic variables.
2438 2438
2439 2439 Notes:
2440 2440
2441 2441 1) If an input line begins with '!!', then %sx is automatically
2442 2442 invoked. That is, while:
2443 2443 !ls
2444 2444 causes ipython to simply issue system('ls'), typing
2445 2445 !!ls
2446 2446 is a shorthand equivalent to:
2447 2447 %sx ls
2448 2448
2449 2449 2) %sx differs from %sc in that %sx automatically splits into a list,
2450 2450 like '%sc -l'. The reason for this is to make it as easy as possible
2451 2451 to process line-oriented shell output via further python commands.
2452 2452 %sc is meant to provide much finer control, but requires more
2453 2453 typing.
2454 2454
2455 2455 3) Just like %sc -l, this is a list with special attributes:
2456 2456
2457 2457 .l (or .list) : value as list.
2458 2458 .n (or .nlstr): value as newline-separated string.
2459 2459 .s (or .spstr): value as whitespace-separated string.
2460 2460
2461 2461 This is very useful when trying to use such lists as arguments to
2462 2462 system commands."""
2463 2463
2464 2464 if parameter_s:
2465 2465 out,err = self.shell.getoutputerror(parameter_s)
2466 2466 if err:
2467 2467 print >> Term.cerr,err
2468 2468 return SList(out.split('\n'))
2469 2469
2470 2470 def magic_bg(self, parameter_s=''):
2471 2471 """Run a job in the background, in a separate thread.
2472 2472
2473 2473 For example,
2474 2474
2475 2475 %bg myfunc(x,y,z=1)
2476 2476
2477 2477 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2478 2478 execution starts, a message will be printed indicating the job
2479 2479 number. If your job number is 5, you can use
2480 2480
2481 2481 myvar = jobs.result(5) or myvar = jobs[5].result
2482 2482
2483 2483 to assign this result to variable 'myvar'.
2484 2484
2485 2485 IPython has a job manager, accessible via the 'jobs' object. You can
2486 2486 type jobs? to get more information about it, and use jobs.<TAB> to see
2487 2487 its attributes. All attributes not starting with an underscore are
2488 2488 meant for public use.
2489 2489
2490 2490 In particular, look at the jobs.new() method, which is used to create
2491 2491 new jobs. This magic %bg function is just a convenience wrapper
2492 2492 around jobs.new(), for expression-based jobs. If you want to create a
2493 2493 new job with an explicit function object and arguments, you must call
2494 2494 jobs.new() directly.
2495 2495
2496 2496 The jobs.new docstring also describes in detail several important
2497 2497 caveats associated with a thread-based model for background job
2498 2498 execution. Type jobs.new? for details.
2499 2499
2500 2500 You can check the status of all jobs with jobs.status().
2501 2501
2502 2502 The jobs variable is set by IPython into the Python builtin namespace.
2503 2503 If you ever declare a variable named 'jobs', you will shadow this
2504 2504 name. You can either delete your global jobs variable to regain
2505 2505 access to the job manager, or make a new name and assign it manually
2506 2506 to the manager (stored in IPython's namespace). For example, to
2507 2507 assign the job manager to the Jobs name, use:
2508 2508
2509 2509 Jobs = __builtins__.jobs"""
2510 2510
2511 2511 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2512 2512
2513 2513 def magic_bookmark(self, parameter_s=''):
2514 2514 """Manage IPython's bookmark system.
2515 2515
2516 2516 %bookmark <name> - set bookmark to current dir
2517 2517 %bookmark <name> <dir> - set bookmark to <dir>
2518 2518 %bookmark -l - list all bookmarks
2519 2519 %bookmark -d <name> - remove bookmark
2520 2520 %bookmark -r - remove all bookmarks
2521 2521
2522 2522 You can later on access a bookmarked folder with:
2523 2523 %cd -b <name>
2524 2524 or simply '%cd <name>' if there is no directory called <name> AND
2525 2525 there is such a bookmark defined.
2526 2526
2527 2527 Your bookmarks persist through IPython sessions, but they are
2528 2528 associated with each profile."""
2529 2529
2530 2530 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2531 2531 if len(args) > 2:
2532 2532 error('You can only give at most two arguments')
2533 2533 return
2534 2534
2535 2535 bkms = self.shell.persist.get('bookmarks',{})
2536 2536
2537 2537 if opts.has_key('d'):
2538 2538 try:
2539 2539 todel = args[0]
2540 2540 except IndexError:
2541 2541 error('You must provide a bookmark to delete')
2542 2542 else:
2543 2543 try:
2544 2544 del bkms[todel]
2545 2545 except:
2546 2546 error("Can't delete bookmark '%s'" % todel)
2547 2547 elif opts.has_key('r'):
2548 2548 bkms = {}
2549 2549 elif opts.has_key('l'):
2550 2550 bks = bkms.keys()
2551 2551 bks.sort()
2552 2552 if bks:
2553 2553 size = max(map(len,bks))
2554 2554 else:
2555 2555 size = 0
2556 2556 fmt = '%-'+str(size)+'s -> %s'
2557 2557 print 'Current bookmarks:'
2558 2558 for bk in bks:
2559 2559 print fmt % (bk,bkms[bk])
2560 2560 else:
2561 2561 if not args:
2562 2562 error("You must specify the bookmark name")
2563 2563 elif len(args)==1:
2564 2564 bkms[args[0]] = os.getcwd()
2565 2565 elif len(args)==2:
2566 2566 bkms[args[0]] = args[1]
2567 2567 self.persist['bookmarks'] = bkms
2568 2568
2569 2569 def magic_pycat(self, parameter_s=''):
2570 2570 """Show a syntax-highlighted file through a pager.
2571 2571
2572 2572 This magic is similar to the cat utility, but it will assume the file
2573 2573 to be Python source and will show it with syntax highlighting. """
2574 2574
2575 2575 filename = get_py_filename(parameter_s)
2576 2576 page(self.shell.colorize(file_read(filename)),
2577 2577 screen_lines=self.shell.rc.screen_length)
2578 2578
2579 2579 # end Magic
@@ -1,576 +1,578 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Classes for handling input/output prompts.
4 4
5 $Id: Prompts.py 958 2005-12-27 23:17:51Z fperez $"""
5 $Id: Prompts.py 960 2005-12-28 06:51:01Z fperez $"""
6 6
7 7 #*****************************************************************************
8 8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 from IPython import Release
15 15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 16 __license__ = Release.license
17 17 __version__ = Release.version
18 18
19 19 #****************************************************************************
20 20 # Required modules
21 21 import __builtin__
22 22 import os
23 23 import socket
24 24 import sys
25 25 import time
26 26 from pprint import pprint,pformat
27 27
28 28 # IPython's own
29 29 from IPython.genutils import *
30 30 from IPython.Struct import Struct
31 31 from IPython.Magic import Macro
32 32 from IPython.Itpl import ItplNS
33 33 from IPython import ColorANSI
34 34
35 35 #****************************************************************************
36 36 #Color schemes for Prompts.
37 37
38 38 PromptColors = ColorANSI.ColorSchemeTable()
39 39 InputColors = ColorANSI.InputTermColors # just a shorthand
40 40 Colors = ColorANSI.TermColors # just a shorthand
41 41
42 42 PromptColors.add_scheme(ColorANSI.ColorScheme(
43 43 'NoColor',
44 44 in_prompt = InputColors.NoColor, # Input prompt
45 45 in_number = InputColors.NoColor, # Input prompt number
46 46 in_prompt2 = InputColors.NoColor, # Continuation prompt
47 47 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
48 48
49 49 out_prompt = Colors.NoColor, # Output prompt
50 50 out_number = Colors.NoColor, # Output prompt number
51 51
52 52 normal = Colors.NoColor # color off (usu. Colors.Normal)
53 53 ))
54 54
55 55 # make some schemes as instances so we can copy them for modification easily:
56 56 __PColLinux = ColorANSI.ColorScheme(
57 57 'Linux',
58 58 in_prompt = InputColors.Green,
59 59 in_number = InputColors.LightGreen,
60 60 in_prompt2 = InputColors.Green,
61 61 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
62 62
63 63 out_prompt = Colors.Red,
64 64 out_number = Colors.LightRed,
65 65
66 66 normal = Colors.Normal
67 67 )
68 68 # Don't forget to enter it into the table!
69 69 PromptColors.add_scheme(__PColLinux)
70 70
71 71 # Slightly modified Linux for light backgrounds
72 72 __PColLightBG = __PColLinux.copy('LightBG')
73 73
74 74 __PColLightBG.colors.update(
75 75 in_prompt = InputColors.Blue,
76 76 in_number = InputColors.LightBlue,
77 77 in_prompt2 = InputColors.Blue
78 78 )
79 79 PromptColors.add_scheme(__PColLightBG)
80 80
81 81 del Colors,InputColors
82 82
83 83 #-----------------------------------------------------------------------------
84 84 def multiple_replace(dict, text):
85 85 """ Replace in 'text' all occurences of any key in the given
86 86 dictionary by its corresponding value. Returns the new string."""
87 87
88 88 # Function by Xavier Defrang, originally found at:
89 89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
90 90
91 91 # Create a regular expression from the dictionary keys
92 92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
93 93 # For each match, look-up corresponding value in dictionary
94 94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
95 95
96 96 #-----------------------------------------------------------------------------
97 97 # Special characters that can be used in prompt templates, mainly bash-like
98 98
99 99 # If $HOME isn't defined (Windows), make it an absurd string so that it can
100 100 # never be expanded out into '~'. Basically anything which can never be a
101 101 # reasonable directory name will do, we just want the $HOME -> '~' operation
102 102 # to become a no-op. We pre-compute $HOME here so it's not done on every
103 103 # prompt call.
104 104
105 105 # FIXME:
106 106
107 107 # - This should be turned into a class which does proper namespace management,
108 108 # since the prompt specials need to be evaluated in a certain namespace.
109 109 # Currently it's just globals, which need to be managed manually by code
110 110 # below.
111 111
112 112 # - I also need to split up the color schemes from the prompt specials
113 113 # somehow. I don't have a clean design for that quite yet.
114 114
115 115 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
116 116
117 117 # We precompute a few more strings here for the prompt_specials, which are
118 118 # fixed once ipython starts. This reduces the runtime overhead of computing
119 119 # prompt strings.
120 120 USER = os.environ.get("USER")
121 121 HOSTNAME = socket.gethostname()
122 122 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
123 123 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
124 124
125 125 prompt_specials_color = {
126 126 # Prompt/history count
127 127 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 128 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
129 129 # Prompt/history count, with the actual digits replaced by dots. Used
130 130 # mainly in continuation prompts (prompt_in2)
131 131 '\\D': '${"."*len(str(self.cache.prompt_count))}',
132 132 # Current working directory
133 133 '\\w': '${os.getcwd()}',
134 134 # Current time
135 135 '\\t' : '${time.strftime("%H:%M:%S")}',
136 136 # Basename of current working directory.
137 137 # (use os.sep to make this portable across OSes)
138 138 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
139 139 # These X<N> are an extension to the normal bash prompts. They return
140 140 # N terms of the path, after replacing $HOME with '~'
141 141 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
142 142 '\\X1': '${self.cwd_filt(1)}',
143 143 '\\X2': '${self.cwd_filt(2)}',
144 144 '\\X3': '${self.cwd_filt(3)}',
145 145 '\\X4': '${self.cwd_filt(4)}',
146 146 '\\X5': '${self.cwd_filt(5)}',
147 147 # Y<N> are similar to X<N>, but they show '~' if it's the directory
148 148 # N+1 in the list. Somewhat like %cN in tcsh.
149 149 '\\Y0': '${self.cwd_filt2(0)}',
150 150 '\\Y1': '${self.cwd_filt2(1)}',
151 151 '\\Y2': '${self.cwd_filt2(2)}',
152 152 '\\Y3': '${self.cwd_filt2(3)}',
153 153 '\\Y4': '${self.cwd_filt2(4)}',
154 154 '\\Y5': '${self.cwd_filt2(5)}',
155 155 # Hostname up to first .
156 156 '\\h': HOSTNAME_SHORT,
157 157 # Full hostname
158 158 '\\H': HOSTNAME,
159 159 # Username of current user
160 160 '\\u': USER,
161 161 # Escaped '\'
162 162 '\\\\': '\\',
163 163 # Newline
164 164 '\\n': '\n',
165 165 # Carriage return
166 166 '\\r': '\r',
167 167 # Release version
168 168 '\\v': __version__,
169 169 # Root symbol ($ or #)
170 170 '\\$': ROOT_SYMBOL,
171 171 }
172 172
173 173 # A copy of the prompt_specials dictionary but with all color escapes removed,
174 174 # so we can correctly compute the prompt length for the auto_rewrite method.
175 175 prompt_specials_nocolor = prompt_specials_color.copy()
176 176 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
177 177 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
178 178
179 179 # Add in all the InputTermColors color escapes as valid prompt characters.
180 180 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
181 181 # with a color name which may begin with a letter used by any other of the
182 182 # allowed specials. This of course means that \\C will never be allowed for
183 183 # anything else.
184 184 input_colors = ColorANSI.InputTermColors
185 185 for _color in dir(input_colors):
186 186 if _color[0] != '_':
187 187 c_name = '\\C_'+_color
188 188 prompt_specials_color[c_name] = getattr(input_colors,_color)
189 189 prompt_specials_nocolor[c_name] = ''
190 190
191 191 # we default to no color for safety. Note that prompt_specials is a global
192 192 # variable used by all prompt objects.
193 193 prompt_specials = prompt_specials_nocolor
194 194
195 195 #-----------------------------------------------------------------------------
196 196 def str_safe(arg):
197 197 """Convert to a string, without ever raising an exception.
198 198
199 199 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
200 200 error message."""
201 201
202 202 try:
203 203 out = str(arg)
204 204 except UnicodeError:
205 205 try:
206 206 out = arg.encode('utf_8','replace')
207 207 except Exception,msg:
208 208 # let's keep this little duplication here, so that the most common
209 209 # case doesn't suffer from a double try wrapping.
210 210 out = '<ERROR: %s>' % msg
211 211 except Exception,msg:
212 212 out = '<ERROR: %s>' % msg
213 213 return out
214 214
215 215 class BasePrompt:
216 216 """Interactive prompt similar to Mathematica's."""
217 217 def __init__(self,cache,sep,prompt,pad_left=False):
218 218
219 219 # Hack: we access information about the primary prompt through the
220 220 # cache argument. We need this, because we want the secondary prompt
221 221 # to be aligned with the primary one. Color table info is also shared
222 222 # by all prompt classes through the cache. Nice OO spaghetti code!
223 223 self.cache = cache
224 224 self.sep = sep
225 225
226 226 # regexp to count the number of spaces at the end of a prompt
227 227 # expression, useful for prompt auto-rewriting
228 228 self.rspace = re.compile(r'(\s*)$')
229 229 # Flag to left-pad prompt strings to match the length of the primary
230 230 # prompt
231 231 self.pad_left = pad_left
232 232 # Set template to create each actual prompt (where numbers change)
233 233 self.p_template = prompt
234 234 self.set_p_str()
235 235
236 236 def set_p_str(self):
237 237 """ Set the interpolating prompt strings.
238 238
239 239 This must be called every time the color settings change, because the
240 240 prompt_specials global may have changed."""
241 241
242 242 import os,time # needed in locals for prompt string handling
243 243 loc = locals()
244 244 self.p_str = ItplNS('%s%s%s' %
245 245 ('${self.sep}${self.col_p}',
246 246 multiple_replace(prompt_specials, self.p_template),
247 247 '${self.col_norm}'),self.cache.user_ns,loc)
248 248
249 249 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
250 250 self.p_template),
251 251 self.cache.user_ns,loc)
252 252
253 253 def write(self,msg): # dbg
254 254 sys.stdout.write(msg)
255 255 return ''
256 256
257 257 def __str__(self):
258 258 """Return a string form of the prompt.
259 259
260 260 This for is useful for continuation and output prompts, since it is
261 261 left-padded to match lengths with the primary one (if the
262 262 self.pad_left attribute is set)."""
263 263
264 264 out_str = str_safe(self.p_str)
265 265 if self.pad_left:
266 266 # We must find the amount of padding required to match lengths,
267 267 # taking the color escapes (which are invisible on-screen) into
268 268 # account.
269 269 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
270 270 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
271 271 return format % out_str
272 272 else:
273 273 return out_str
274 274
275 275 # these path filters are put in as methods so that we can control the
276 276 # namespace where the prompt strings get evaluated
277 277 def cwd_filt(self,depth):
278 278 """Return the last depth elements of the current working directory.
279 279
280 280 $HOME is always replaced with '~'.
281 281 If depth==0, the full path is returned."""
282 282
283 283 cwd = os.getcwd().replace(HOME,"~")
284 284 out = os.sep.join(cwd.split(os.sep)[-depth:])
285 285 if out:
286 286 return out
287 287 else:
288 288 return os.sep
289 289
290 290 def cwd_filt2(self,depth):
291 291 """Return the last depth elements of the current working directory.
292 292
293 293 $HOME is always replaced with '~'.
294 294 If depth==0, the full path is returned."""
295 295
296 296 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
297 297 if '~' in cwd and len(cwd) == depth+1:
298 298 depth += 1
299 299 out = os.sep.join(cwd[-depth:])
300 300 if out:
301 301 return out
302 302 else:
303 303 return os.sep
304 304
305 305 class Prompt1(BasePrompt):
306 306 """Input interactive prompt similar to Mathematica's."""
307 307
308 308 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
309 309 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
310 310
311 311 def set_colors(self):
312 312 self.set_p_str()
313 313 Colors = self.cache.color_table.active_colors # shorthand
314 314 self.col_p = Colors.in_prompt
315 315 self.col_num = Colors.in_number
316 316 self.col_norm = Colors.in_normal
317 317 # We need a non-input version of these escapes for the '--->'
318 318 # auto-call prompts used in the auto_rewrite() method.
319 319 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
320 320 self.col_norm_ni = Colors.normal
321 321
322 322 def __str__(self):
323 323 self.cache.prompt_count += 1
324 324 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
325 325 return str_safe(self.p_str)
326 326
327 327 def auto_rewrite(self):
328 328 """Print a string of the form '--->' which lines up with the previous
329 329 input string. Useful for systems which re-write the user input when
330 330 handling automatically special syntaxes."""
331 331
332 332 curr = str(self.cache.last_prompt)
333 333 nrspaces = len(self.rspace.search(curr).group())
334 334 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
335 335 ' '*nrspaces,self.col_norm_ni)
336 336
337 337 class PromptOut(BasePrompt):
338 338 """Output interactive prompt similar to Mathematica's."""
339 339
340 340 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
341 341 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
342 342 if not self.p_template:
343 343 self.__str__ = lambda: ''
344 344
345 345 def set_colors(self):
346 346 self.set_p_str()
347 347 Colors = self.cache.color_table.active_colors # shorthand
348 348 self.col_p = Colors.out_prompt
349 349 self.col_num = Colors.out_number
350 350 self.col_norm = Colors.normal
351 351
352 352 class Prompt2(BasePrompt):
353 353 """Interactive continuation prompt."""
354 354
355 355 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
356 356 self.cache = cache
357 357 self.p_template = prompt
358 358 self.pad_left = pad_left
359 359 self.set_p_str()
360 360
361 361 def set_p_str(self):
362 362 import os,time # needed in locals for prompt string handling
363 363 loc = locals()
364 364 self.p_str = ItplNS('%s%s%s' %
365 365 ('${self.col_p2}',
366 366 multiple_replace(prompt_specials, self.p_template),
367 367 '$self.col_norm'),
368 368 self.cache.user_ns,loc)
369 369 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
370 370 self.p_template),
371 371 self.cache.user_ns,loc)
372 372
373 373 def set_colors(self):
374 374 self.set_p_str()
375 375 Colors = self.cache.color_table.active_colors
376 376 self.col_p2 = Colors.in_prompt2
377 377 self.col_norm = Colors.in_normal
378 378 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
379 379 # updated their prompt_in2 definitions. Remove eventually.
380 380 self.col_p = Colors.out_prompt
381 381 self.col_num = Colors.out_number
382 382
383 383 #-----------------------------------------------------------------------------
384 384 class CachedOutput:
385 385 """Class for printing output from calculations while keeping a cache of
386 386 reults. It dynamically creates global variables prefixed with _ which
387 387 contain these results.
388 388
389 389 Meant to be used as a sys.displayhook replacement, providing numbered
390 390 prompts and cache services.
391 391
392 392 Initialize with initial and final values for cache counter (this defines
393 393 the maximum size of the cache."""
394 394
395 395 def __init__(self,cache_size,Pprint,colors='NoColor',input_sep='\n',
396 396 output_sep='\n',output_sep2='',user_ns={},
397 397 ps1 = None, ps2 = None,ps_out = None,
398 398 input_hist = None,pad_left=True):
399 399
400 400 cache_size_min = 20
401 401 if cache_size <= 0:
402 402 self.do_full_cache = 0
403 403 cache_size = 0
404 404 elif cache_size < cache_size_min:
405 405 self.do_full_cache = 0
406 406 cache_size = 0
407 407 warn('caching was disabled (min value for cache size is %s).' %
408 408 cache_size_min,level=3)
409 409 else:
410 410 self.do_full_cache = 1
411 411
412 412 self.cache_size = cache_size
413 413 self.input_sep = input_sep
414 414
415 415 # we need a reference to the user-level namespace
416 416 self.user_ns = user_ns
417 417 # and to the user's input
418 418 self.input_hist = input_hist
419 419
420 420 # Set input prompt strings and colors
421 421 if cache_size == 0:
422 422 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
423 423 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
424 424 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
425 425 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
426 426 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
427 427
428 428 self.color_table = PromptColors
429 429 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
430 430 pad_left=pad_left)
431 431 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
432 432 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
433 433 pad_left=pad_left)
434 434 self.set_colors(colors)
435 435
436 436 # other more normal stuff
437 437 # b/c each call to the In[] prompt raises it by 1, even the first.
438 438 self.prompt_count = 0
439 439 self.cache_count = 1
440 440 # Store the last prompt string each time, we need it for aligning
441 441 # continuation and auto-rewrite prompts
442 442 self.last_prompt = ''
443 443 self.entries = [None] # output counter starts at 1 for the user
444 444 self.Pprint = Pprint
445 445 self.output_sep = output_sep
446 446 self.output_sep2 = output_sep2
447 447 self._,self.__,self.___ = '','',''
448 448 self.pprint_types = map(type,[(),[],{}])
449 449
450 450 # these are deliberately global:
451 451 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
452 452 self.user_ns.update(to_user_ns)
453 453
454 454 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
455 455 if p_str is None:
456 456 if self.do_full_cache:
457 457 return cache_def
458 458 else:
459 459 return no_cache_def
460 460 else:
461 461 return p_str
462 462
463 463 def set_colors(self,colors):
464 464 """Set the active color scheme and configure colors for the three
465 465 prompt subsystems."""
466 466
467 467 # FIXME: the prompt_specials global should be gobbled inside this
468 468 # class instead. Do it when cleaning up the whole 3-prompt system.
469 469 global prompt_specials
470 470 if colors.lower()=='nocolor':
471 471 prompt_specials = prompt_specials_nocolor
472 472 else:
473 473 prompt_specials = prompt_specials_color
474 474
475 475 self.color_table.set_active_scheme(colors)
476 476 self.prompt1.set_colors()
477 477 self.prompt2.set_colors()
478 478 self.prompt_out.set_colors()
479 479
480 480 def __call__(self,arg=None):
481 481 """Printing with history cache management.
482 482
483 483 This is invoked everytime the interpreter needs to print, and is
484 484 activated by setting the variable sys.displayhook to it."""
485 485
486 486 # If something injected a '_' variable in __builtin__, delete
487 487 # ipython's automatic one so we don't clobber that. gettext() in
488 488 # particular uses _, so we need to stay away from it.
489 489 if '_' in __builtin__.__dict__:
490 490 try:
491 491 del self.user_ns['_']
492 492 except KeyError:
493 493 pass
494 494 if arg is not None:
495 495 cout_write = Term.cout.write # fast lookup
496 496 # first handle the cache and counters
497 self.update(arg)
497 # but avoid recursive reference when displaying _oh/Out
498 if arg is not self.user_ns['_oh']:
499 self.update(arg)
498 500 # do not print output if input ends in ';'
499 501 if self.input_hist[self.prompt_count].endswith(';\n'):
500 502 return
501 503 # don't use print, puts an extra space
502 504 cout_write(self.output_sep)
503 505 if self.do_full_cache:
504 506 cout_write(str(self.prompt_out))
505 507
506 508 if isinstance(arg,Macro):
507 509 print 'Executing Macro...'
508 510 # in case the macro takes a long time to execute
509 511 Term.cout.flush()
510 512 exec arg.value in self.user_ns
511 513 return None
512 514
513 515 # and now call a possibly user-defined print mechanism
514 516 self.display(arg)
515 517 cout_write(self.output_sep2)
516 518 Term.cout.flush()
517 519
518 520 def _display(self,arg):
519 521 """Default printer method, uses pprint.
520 522
521 523 This can be over-ridden by the users to implement special formatting
522 524 of certain types of output."""
523 525
524 526 if self.Pprint:
525 527 out = pformat(arg)
526 528 if '\n' in out:
527 529 # So that multi-line strings line up with the left column of
528 530 # the screen, instead of having the output prompt mess up
529 531 # their first line.
530 532 Term.cout.write('\n')
531 533 print >>Term.cout, out
532 534 else:
533 535 print >>Term.cout, arg
534 536
535 537 # Assign the default display method:
536 538 display = _display
537 539
538 540 def update(self,arg):
539 541 #print '***cache_count', self.cache_count # dbg
540 542 if self.cache_count >= self.cache_size and self.do_full_cache:
541 543 self.flush()
542 544 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
543 545 # we cause buggy behavior for things like gettext).
544 546 if '_' not in __builtin__.__dict__:
545 547 self.___ = self.__
546 548 self.__ = self._
547 549 self._ = arg
548 550 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
549 551
550 552 # hackish access to top-level namespace to create _1,_2... dynamically
551 553 to_main = {}
552 554 if self.do_full_cache:
553 555 self.cache_count += 1
554 556 self.entries.append(arg)
555 557 new_result = '_'+`self.prompt_count`
556 558 to_main[new_result] = self.entries[-1]
557 559 self.user_ns.update(to_main)
558 560 self.user_ns['_oh'][self.prompt_count] = arg
559 561
560 562 def flush(self):
561 563 if not self.do_full_cache:
562 564 raise ValueError,"You shouldn't have reached the cache flush "\
563 565 "if full caching is not enabled!"
564 566 warn('Output cache limit (currently '+\
565 567 `self.cache_count`+' entries) hit.\n'
566 568 'Flushing cache and resetting history counter...\n'
567 569 'The only history variables available will be _,__,___ and _1\n'
568 570 'with the current result.')
569 571 # delete auto-generated vars from global namespace
570 572 for n in range(1,self.prompt_count + 1):
571 573 key = '_'+`n`
572 574 try:
573 575 del self.user_ns[key]
574 576 except: pass
575 577 self.prompt_count = 1
576 578 self.cache_count = 1
@@ -1,1609 +1,1609 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 958 2005-12-27 23:17:51Z fperez $"""
8 $Id: genutils.py 960 2005-12-28 06:51:01Z 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 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
41 41 # 2.2-friendly
42 42 try:
43 43 basestring
44 44 except NameError:
45 45 import types
46 46 basestring = (types.StringType, types.UnicodeType)
47 47 True = 1==1
48 48 False = 1==0
49 49
50 50 def enumerate(obj):
51 51 i = -1
52 52 for item in obj:
53 53 i += 1
54 54 yield i, item
55 55
56 56 # add these to the builtin namespace, so that all modules find them
57 57 import __builtin__
58 58 __builtin__.basestring = basestring
59 59 __builtin__.True = True
60 60 __builtin__.False = False
61 61 __builtin__.enumerate = enumerate
62 62
63 63 # Try to use shlex.split for converting an input string into a sys.argv-type
64 64 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
65 65 try:
66 66 shlex_split = shlex.split
67 67 except AttributeError:
68 68 _quotesre = re.compile(r'[\'"](.*)[\'"]')
69 69 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
70 70 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
71 71 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
72 72 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
73 73 % os.sep)
74 74
75 75 def shlex_split(s):
76 76 """Simplified backport to Python 2.2 of shlex.split().
77 77
78 78 This is a quick and dirty hack, since the shlex module under 2.2 lacks
79 79 several of the features needed to really match the functionality of
80 80 shlex.split() in 2.3."""
81 81
82 82 lex = shlex.shlex(StringIO(s))
83 83 # Try to get options, extensions and path separators as characters
84 84 lex.wordchars = _wordchars
85 85 lex.commenters = ''
86 86 # Make a list out of the lexer by hand, since in 2.2 it's not an
87 87 # iterator.
88 88 lout = []
89 89 while 1:
90 90 token = lex.get_token()
91 91 if token == '':
92 92 break
93 93 # Try to handle quoted tokens correctly
94 94 quotes = _quotesre.match(token)
95 95 if quotes:
96 96 token = quotes.group(1)
97 97 lout.append(token)
98 98 return lout
99 99
100 100 #****************************************************************************
101 101 # Exceptions
102 102 class Error(Exception):
103 103 """Base class for exceptions in this module."""
104 104 pass
105 105
106 106 #----------------------------------------------------------------------------
107 107 class IOStream:
108 108 def __init__(self,stream,fallback):
109 109 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
110 110 stream = fallback
111 111 self.stream = stream
112 112 self._swrite = stream.write
113 113 self.flush = stream.flush
114 114
115 115 def write(self,data):
116 116 try:
117 117 self._swrite(data)
118 118 except:
119 119 try:
120 120 # print handles some unicode issues which may trip a plain
121 121 # write() call. Attempt to emulate write() by using a
122 122 # trailing comma
123 123 print >> self.stream, data,
124 124 except:
125 125 # if we get here, something is seriously broken.
126 126 print >> sys.stderr, \
127 127 'ERROR - failed to write data to stream:', stream
128 128
129 129 class IOTerm:
130 130 """ Term holds the file or file-like objects for handling I/O operations.
131 131
132 132 These are normally just sys.stdin, sys.stdout and sys.stderr but for
133 133 Windows they can can replaced to allow editing the strings before they are
134 134 displayed."""
135 135
136 136 # In the future, having IPython channel all its I/O operations through
137 137 # this class will make it easier to embed it into other environments which
138 138 # are not a normal terminal (such as a GUI-based shell)
139 139 def __init__(self,cin=None,cout=None,cerr=None):
140 140 self.cin = IOStream(cin,sys.stdin)
141 141 self.cout = IOStream(cout,sys.stdout)
142 142 self.cerr = IOStream(cerr,sys.stderr)
143 143
144 144 # Global variable to be used for all I/O
145 145 Term = IOTerm()
146 146
147 147 # Windows-specific code to load Gary Bishop's readline and configure it
148 148 # automatically for the users
149 149 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
150 150 # windows. Cygwin returns 'cygwin' for sys.platform.
151 151 if os.name == 'nt':
152 152 try:
153 153 import readline
154 154 except ImportError:
155 155 pass
156 156 else:
157 157 try:
158 158 _out = readline.GetOutputFile()
159 159 except AttributeError:
160 160 pass
161 161 else:
162 162 # Remake Term to use the readline i/o facilities
163 163 Term = IOTerm(cout=_out,cerr=_out)
164 164 del _out
165 165
166 166 #****************************************************************************
167 167 # Generic warning/error printer, used by everything else
168 168 def warn(msg,level=2,exit_val=1):
169 169 """Standard warning printer. Gives formatting consistency.
170 170
171 171 Output is sent to Term.cerr (sys.stderr by default).
172 172
173 173 Options:
174 174
175 175 -level(2): allows finer control:
176 176 0 -> Do nothing, dummy function.
177 177 1 -> Print message.
178 178 2 -> Print 'WARNING:' + message. (Default level).
179 179 3 -> Print 'ERROR:' + message.
180 180 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
181 181
182 182 -exit_val (1): exit value returned by sys.exit() for a level 4
183 183 warning. Ignored for all other levels."""
184 184
185 185 if level>0:
186 186 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
187 187 print >> Term.cerr, '%s%s' % (header[level],msg)
188 188 if level == 4:
189 189 print >> Term.cerr,'Exiting.\n'
190 190 sys.exit(exit_val)
191 191
192 192 def info(msg):
193 193 """Equivalent to warn(msg,level=1)."""
194 194
195 195 warn(msg,level=1)
196 196
197 197 def error(msg):
198 198 """Equivalent to warn(msg,level=3)."""
199 199
200 200 warn(msg,level=3)
201 201
202 202 def fatal(msg,exit_val=1):
203 203 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
204 204
205 205 warn(msg,exit_val=exit_val,level=4)
206 206
207 207 #----------------------------------------------------------------------------
208 208 StringTypes = types.StringTypes
209 209
210 210 # Basic timing functionality
211 211
212 212 # If possible (Unix), use the resource module instead of time.clock()
213 213 try:
214 214 import resource
215 215 def clock():
216 216 """clock() -> floating point number
217 217
218 218 Return the CPU time in seconds (user time only, system time is
219 219 ignored) since the start of the process. This is done via a call to
220 220 resource.getrusage, so it avoids the wraparound problems in
221 221 time.clock()."""
222 222
223 223 return resource.getrusage(resource.RUSAGE_SELF)[0]
224 224
225 225 def clock2():
226 226 """clock2() -> (t_user,t_system)
227 227
228 228 Similar to clock(), but return a tuple of user/system times."""
229 229 return resource.getrusage(resource.RUSAGE_SELF)[:2]
230 230
231 231 except ImportError:
232 232 clock = time.clock
233 233 def clock2():
234 234 """Under windows, system CPU time can't be measured.
235 235
236 236 This just returns clock() and zero."""
237 237 return time.clock(),0.0
238 238
239 239 def timings_out(reps,func,*args,**kw):
240 240 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
241 241
242 242 Execute a function reps times, return a tuple with the elapsed total
243 243 CPU time in seconds, the time per call and the function's output.
244 244
245 245 Under Unix, the return value is the sum of user+system time consumed by
246 246 the process, computed via the resource module. This prevents problems
247 247 related to the wraparound effect which the time.clock() function has.
248 248
249 249 Under Windows the return value is in wall clock seconds. See the
250 250 documentation for the time module for more details."""
251 251
252 252 reps = int(reps)
253 253 assert reps >=1, 'reps must be >= 1'
254 254 if reps==1:
255 255 start = clock()
256 256 out = func(*args,**kw)
257 257 tot_time = clock()-start
258 258 else:
259 259 rng = xrange(reps-1) # the last time is executed separately to store output
260 260 start = clock()
261 261 for dummy in rng: func(*args,**kw)
262 262 out = func(*args,**kw) # one last time
263 263 tot_time = clock()-start
264 264 av_time = tot_time / reps
265 265 return tot_time,av_time,out
266 266
267 267 def timings(reps,func,*args,**kw):
268 268 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
269 269
270 270 Execute a function reps times, return a tuple with the elapsed total CPU
271 271 time in seconds and the time per call. These are just the first two values
272 272 in timings_out()."""
273 273
274 274 return timings_out(reps,func,*args,**kw)[0:2]
275 275
276 276 def timing(func,*args,**kw):
277 277 """timing(func,*args,**kw) -> t_total
278 278
279 279 Execute a function once, return the elapsed total CPU time in
280 280 seconds. This is just the first value in timings_out()."""
281 281
282 282 return timings_out(1,func,*args,**kw)[0]
283 283
284 284 #****************************************************************************
285 285 # file and system
286 286
287 287 def system(cmd,verbose=0,debug=0,header=''):
288 288 """Execute a system command, return its exit status.
289 289
290 290 Options:
291 291
292 292 - verbose (0): print the command to be executed.
293 293
294 294 - debug (0): only print, do not actually execute.
295 295
296 296 - header (''): Header to print on screen prior to the executed command (it
297 297 is only prepended to the command, no newlines are added).
298 298
299 299 Note: a stateful version of this function is available through the
300 300 SystemExec class."""
301 301
302 302 stat = 0
303 303 if verbose or debug: print header+cmd
304 304 sys.stdout.flush()
305 305 if not debug: stat = os.system(cmd)
306 306 return stat
307 307
308 308 def shell(cmd,verbose=0,debug=0,header=''):
309 309 """Execute a command in the system shell, always return None.
310 310
311 311 Options:
312 312
313 313 - verbose (0): print the command to be executed.
314 314
315 315 - debug (0): only print, do not actually execute.
316 316
317 317 - header (''): Header to print on screen prior to the executed command (it
318 318 is only prepended to the command, no newlines are added).
319 319
320 320 Note: this is similar to genutils.system(), but it returns None so it can
321 321 be conveniently used in interactive loops without getting the return value
322 322 (typically 0) printed many times."""
323 323
324 324 stat = 0
325 325 if verbose or debug: print header+cmd
326 326 # flush stdout so we don't mangle python's buffering
327 327 sys.stdout.flush()
328 328 if not debug:
329 329 os.system(cmd)
330 330
331 331 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
332 332 """Dummy substitute for perl's backquotes.
333 333
334 334 Executes a command and returns the output.
335 335
336 336 Accepts the same arguments as system(), plus:
337 337
338 338 - split(0): if true, the output is returned as a list split on newlines.
339 339
340 340 Note: a stateful version of this function is available through the
341 341 SystemExec class."""
342 342
343 343 if verbose or debug: print header+cmd
344 344 if not debug:
345 345 output = commands.getoutput(cmd)
346 346 if split:
347 347 return output.split('\n')
348 348 else:
349 349 return output
350 350
351 351 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
352 352 """Return (standard output,standard error) of executing cmd in a shell.
353 353
354 354 Accepts the same arguments as system(), plus:
355 355
356 356 - split(0): if true, each of stdout/err is returned as a list split on
357 357 newlines.
358 358
359 359 Note: a stateful version of this function is available through the
360 360 SystemExec class."""
361 361
362 362 if verbose or debug: print header+cmd
363 363 if not cmd:
364 364 if split:
365 365 return [],[]
366 366 else:
367 367 return '',''
368 368 if not debug:
369 369 pin,pout,perr = os.popen3(cmd)
370 370 tout = pout.read().rstrip()
371 371 terr = perr.read().rstrip()
372 372 pin.close()
373 373 pout.close()
374 374 perr.close()
375 375 if split:
376 376 return tout.split('\n'),terr.split('\n')
377 377 else:
378 378 return tout,terr
379 379
380 380 # for compatibility with older naming conventions
381 381 xsys = system
382 382 bq = getoutput
383 383
384 384 class SystemExec:
385 385 """Access the system and getoutput functions through a stateful interface.
386 386
387 387 Note: here we refer to the system and getoutput functions from this
388 388 library, not the ones from the standard python library.
389 389
390 390 This class offers the system and getoutput functions as methods, but the
391 391 verbose, debug and header parameters can be set for the instance (at
392 392 creation time or later) so that they don't need to be specified on each
393 393 call.
394 394
395 395 For efficiency reasons, there's no way to override the parameters on a
396 396 per-call basis other than by setting instance attributes. If you need
397 397 local overrides, it's best to directly call system() or getoutput().
398 398
399 399 The following names are provided as alternate options:
400 400 - xsys: alias to system
401 401 - bq: alias to getoutput
402 402
403 403 An instance can then be created as:
404 404 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
405 405
406 406 And used as:
407 407 >>> sysexec.xsys('pwd')
408 408 >>> dirlist = sysexec.bq('ls -l')
409 409 """
410 410
411 411 def __init__(self,verbose=0,debug=0,header='',split=0):
412 412 """Specify the instance's values for verbose, debug and header."""
413 413 setattr_list(self,'verbose debug header split')
414 414
415 415 def system(self,cmd):
416 416 """Stateful interface to system(), with the same keyword parameters."""
417 417
418 418 system(cmd,self.verbose,self.debug,self.header)
419 419
420 420 def shell(self,cmd):
421 421 """Stateful interface to shell(), with the same keyword parameters."""
422 422
423 423 shell(cmd,self.verbose,self.debug,self.header)
424 424
425 425 xsys = system # alias
426 426
427 427 def getoutput(self,cmd):
428 428 """Stateful interface to getoutput()."""
429 429
430 430 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
431 431
432 432 def getoutputerror(self,cmd):
433 433 """Stateful interface to getoutputerror()."""
434 434
435 435 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
436 436
437 437 bq = getoutput # alias
438 438
439 439 #-----------------------------------------------------------------------------
440 440 def mutex_opts(dict,ex_op):
441 441 """Check for presence of mutually exclusive keys in a dict.
442 442
443 443 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
444 444 for op1,op2 in ex_op:
445 445 if op1 in dict and op2 in dict:
446 446 raise ValueError,'\n*** ERROR in Arguments *** '\
447 447 'Options '+op1+' and '+op2+' are mutually exclusive.'
448 448
449 449 #-----------------------------------------------------------------------------
450 450 def get_py_filename(name):
451 451 """Return a valid python filename in the current directory.
452 452
453 453 If the given name is not a file, it adds '.py' and searches again.
454 454 Raises IOError with an informative message if the file isn't found."""
455 455
456 456 name = os.path.expanduser(name)
457 457 if not os.path.isfile(name) and not name.endswith('.py'):
458 458 name += '.py'
459 459 if os.path.isfile(name):
460 460 return name
461 461 else:
462 462 raise IOError,'File `%s` not found.' % name
463 463
464 464 #-----------------------------------------------------------------------------
465 465 def filefind(fname,alt_dirs = None):
466 466 """Return the given filename either in the current directory, if it
467 467 exists, or in a specified list of directories.
468 468
469 469 ~ expansion is done on all file and directory names.
470 470
471 471 Upon an unsuccessful search, raise an IOError exception."""
472 472
473 473 if alt_dirs is None:
474 474 try:
475 475 alt_dirs = get_home_dir()
476 476 except HomeDirError:
477 477 alt_dirs = os.getcwd()
478 478 search = [fname] + list_strings(alt_dirs)
479 479 search = map(os.path.expanduser,search)
480 480 #print 'search list for',fname,'list:',search # dbg
481 481 fname = search[0]
482 482 if os.path.isfile(fname):
483 483 return fname
484 484 for direc in search[1:]:
485 485 testname = os.path.join(direc,fname)
486 486 #print 'testname',testname # dbg
487 487 if os.path.isfile(testname):
488 488 return testname
489 489 raise IOError,'File' + `fname` + \
490 490 ' not found in current or supplied directories:' + `alt_dirs`
491 491
492 492 #----------------------------------------------------------------------------
493 493 def file_read(filename):
494 494 """Read a file and close it. Returns the file source."""
495 495 fobj=open(filename,'r');
496 496 source = fobj.read();
497 497 fobj.close()
498 498 return source
499 499
500 500 #----------------------------------------------------------------------------
501 501 def target_outdated(target,deps):
502 502 """Determine whether a target is out of date.
503 503
504 504 target_outdated(target,deps) -> 1/0
505 505
506 506 deps: list of filenames which MUST exist.
507 507 target: single filename which may or may not exist.
508 508
509 509 If target doesn't exist or is older than any file listed in deps, return
510 510 true, otherwise return false.
511 511 """
512 512 try:
513 513 target_time = os.path.getmtime(target)
514 514 except os.error:
515 515 return 1
516 516 for dep in deps:
517 517 dep_time = os.path.getmtime(dep)
518 518 if dep_time > target_time:
519 519 #print "For target",target,"Dep failed:",dep # dbg
520 520 #print "times (dep,tar):",dep_time,target_time # dbg
521 521 return 1
522 522 return 0
523 523
524 524 #-----------------------------------------------------------------------------
525 525 def target_update(target,deps,cmd):
526 526 """Update a target with a given command given a list of dependencies.
527 527
528 528 target_update(target,deps,cmd) -> runs cmd if target is outdated.
529 529
530 530 This is just a wrapper around target_outdated() which calls the given
531 531 command if target is outdated."""
532 532
533 533 if target_outdated(target,deps):
534 534 xsys(cmd)
535 535
536 536 #----------------------------------------------------------------------------
537 537 def unquote_ends(istr):
538 538 """Remove a single pair of quotes from the endpoints of a string."""
539 539
540 540 if not istr:
541 541 return istr
542 542 if (istr[0]=="'" and istr[-1]=="'") or \
543 543 (istr[0]=='"' and istr[-1]=='"'):
544 544 return istr[1:-1]
545 545 else:
546 546 return istr
547 547
548 548 #----------------------------------------------------------------------------
549 549 def process_cmdline(argv,names=[],defaults={},usage=''):
550 550 """ Process command-line options and arguments.
551 551
552 552 Arguments:
553 553
554 554 - argv: list of arguments, typically sys.argv.
555 555
556 556 - names: list of option names. See DPyGetOpt docs for details on options
557 557 syntax.
558 558
559 559 - defaults: dict of default values.
560 560
561 561 - usage: optional usage notice to print if a wrong argument is passed.
562 562
563 563 Return a dict of options and a list of free arguments."""
564 564
565 565 getopt = DPyGetOpt.DPyGetOpt()
566 566 getopt.setIgnoreCase(0)
567 567 getopt.parseConfiguration(names)
568 568
569 569 try:
570 570 getopt.processArguments(argv)
571 571 except:
572 572 print usage
573 573 warn(`sys.exc_value`,level=4)
574 574
575 575 defaults.update(getopt.optionValues)
576 576 args = getopt.freeValues
577 577
578 578 return defaults,args
579 579
580 580 #----------------------------------------------------------------------------
581 581 def optstr2types(ostr):
582 582 """Convert a string of option names to a dict of type mappings.
583 583
584 584 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
585 585
586 586 This is used to get the types of all the options in a string formatted
587 587 with the conventions of DPyGetOpt. The 'type' None is used for options
588 588 which are strings (they need no further conversion). This function's main
589 589 use is to get a typemap for use with read_dict().
590 590 """
591 591
592 592 typeconv = {None:'',int:'',float:''}
593 593 typemap = {'s':None,'i':int,'f':float}
594 594 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
595 595
596 596 for w in ostr.split():
597 597 oname,alias,otype = opt_re.match(w).groups()
598 598 if otype == '' or alias == '!': # simple switches are integers too
599 599 otype = 'i'
600 600 typeconv[typemap[otype]] += oname + ' '
601 601 return typeconv
602 602
603 603 #----------------------------------------------------------------------------
604 604 def read_dict(filename,type_conv=None,**opt):
605 605
606 606 """Read a dictionary of key=value pairs from an input file, optionally
607 607 performing conversions on the resulting values.
608 608
609 609 read_dict(filename,type_conv,**opt) -> dict
610 610
611 611 Only one value per line is accepted, the format should be
612 612 # optional comments are ignored
613 613 key value\n
614 614
615 615 Args:
616 616
617 617 - type_conv: A dictionary specifying which keys need to be converted to
618 618 which types. By default all keys are read as strings. This dictionary
619 619 should have as its keys valid conversion functions for strings
620 620 (int,long,float,complex, or your own). The value for each key
621 621 (converter) should be a whitespace separated string containing the names
622 622 of all the entries in the file to be converted using that function. For
623 623 keys to be left alone, use None as the conversion function (only needed
624 624 with purge=1, see below).
625 625
626 626 - opt: dictionary with extra options as below (default in parens)
627 627
628 628 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
629 629 of the dictionary to be returned. If purge is going to be used, the
630 630 set of keys to be left as strings also has to be explicitly specified
631 631 using the (non-existent) conversion function None.
632 632
633 633 fs(None): field separator. This is the key/value separator to be used
634 634 when parsing the file. The None default means any whitespace [behavior
635 635 of string.split()].
636 636
637 637 strip(0): if 1, strip string values of leading/trailinig whitespace.
638 638
639 639 warn(1): warning level if requested keys are not found in file.
640 640 - 0: silently ignore.
641 641 - 1: inform but proceed.
642 642 - 2: raise KeyError exception.
643 643
644 644 no_empty(0): if 1, remove keys with whitespace strings as a value.
645 645
646 646 unique([]): list of keys (or space separated string) which can't be
647 647 repeated. If one such key is found in the file, each new instance
648 648 overwrites the previous one. For keys not listed here, the behavior is
649 649 to make a list of all appearances.
650 650
651 651 Example:
652 652 If the input file test.ini has:
653 653 i 3
654 654 x 4.5
655 655 y 5.5
656 656 s hi ho
657 657 Then:
658 658
659 659 >>> type_conv={int:'i',float:'x',None:'s'}
660 660 >>> read_dict('test.ini')
661 661 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
662 662 >>> read_dict('test.ini',type_conv)
663 663 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
664 664 >>> read_dict('test.ini',type_conv,purge=1)
665 665 {'i': 3, 's': 'hi ho', 'x': 4.5}
666 666 """
667 667
668 668 # starting config
669 669 opt.setdefault('purge',0)
670 670 opt.setdefault('fs',None) # field sep defaults to any whitespace
671 671 opt.setdefault('strip',0)
672 672 opt.setdefault('warn',1)
673 673 opt.setdefault('no_empty',0)
674 674 opt.setdefault('unique','')
675 675 if type(opt['unique']) in StringTypes:
676 676 unique_keys = qw(opt['unique'])
677 677 elif type(opt['unique']) in (types.TupleType,types.ListType):
678 678 unique_keys = opt['unique']
679 679 else:
680 680 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
681 681
682 682 dict = {}
683 683 # first read in table of values as strings
684 684 file = open(filename,'r')
685 685 for line in file.readlines():
686 686 line = line.strip()
687 687 if len(line) and line[0]=='#': continue
688 688 if len(line)>0:
689 689 lsplit = line.split(opt['fs'],1)
690 690 try:
691 691 key,val = lsplit
692 692 except ValueError:
693 693 key,val = lsplit[0],''
694 694 key = key.strip()
695 695 if opt['strip']: val = val.strip()
696 696 if val == "''" or val == '""': val = ''
697 697 if opt['no_empty'] and (val=='' or val.isspace()):
698 698 continue
699 699 # if a key is found more than once in the file, build a list
700 700 # unless it's in the 'unique' list. In that case, last found in file
701 701 # takes precedence. User beware.
702 702 try:
703 703 if dict[key] and key in unique_keys:
704 704 dict[key] = val
705 705 elif type(dict[key]) is types.ListType:
706 706 dict[key].append(val)
707 707 else:
708 708 dict[key] = [dict[key],val]
709 709 except KeyError:
710 710 dict[key] = val
711 711 # purge if requested
712 712 if opt['purge']:
713 713 accepted_keys = qwflat(type_conv.values())
714 714 for key in dict.keys():
715 715 if key in accepted_keys: continue
716 716 del(dict[key])
717 717 # now convert if requested
718 718 if type_conv==None: return dict
719 719 conversions = type_conv.keys()
720 720 try: conversions.remove(None)
721 721 except: pass
722 722 for convert in conversions:
723 723 for val in qw(type_conv[convert]):
724 724 try:
725 725 dict[val] = convert(dict[val])
726 726 except KeyError,e:
727 727 if opt['warn'] == 0:
728 728 pass
729 729 elif opt['warn'] == 1:
730 730 print >>sys.stderr, 'Warning: key',val,\
731 731 'not found in file',filename
732 732 elif opt['warn'] == 2:
733 733 raise KeyError,e
734 734 else:
735 735 raise ValueError,'Warning level must be 0,1 or 2'
736 736
737 737 return dict
738 738
739 739 #----------------------------------------------------------------------------
740 740 def flag_calls(func):
741 741 """Wrap a function to detect and flag when it gets called.
742 742
743 743 This is a decorator which takes a function and wraps it in a function with
744 744 a 'called' attribute. wrapper.called is initialized to False.
745 745
746 746 The wrapper.called attribute is set to False right before each call to the
747 747 wrapped function, so if the call fails it remains False. After the call
748 748 completes, wrapper.called is set to True and the output is returned.
749 749
750 750 Testing for truth in wrapper.called allows you to determine if a call to
751 751 func() was attempted and succeeded."""
752 752
753 753 def wrapper(*args,**kw):
754 754 wrapper.called = False
755 755 out = func(*args,**kw)
756 756 wrapper.called = True
757 757 return out
758 758
759 759 wrapper.called = False
760 760 wrapper.__doc__ = func.__doc__
761 761 return wrapper
762 762
763 763 #----------------------------------------------------------------------------
764 764 class HomeDirError(Error):
765 765 pass
766 766
767 767 def get_home_dir():
768 768 """Return the closest possible equivalent to a 'home' directory.
769 769
770 770 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
771 771
772 772 Currently only Posix and NT are implemented, a HomeDirError exception is
773 773 raised for all other OSes. """
774 774
775 775 isdir = os.path.isdir
776 776 env = os.environ
777 777 try:
778 778 homedir = env['HOME']
779 779 if not isdir(homedir):
780 780 # in case a user stuck some string which does NOT resolve to a
781 781 # valid path, it's as good as if we hadn't foud it
782 782 raise KeyError
783 783 return homedir
784 784 except KeyError:
785 785 if os.name == 'posix':
786 786 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
787 787 elif os.name == 'nt':
788 788 # For some strange reason, win9x returns 'nt' for os.name.
789 789 try:
790 790 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
791 791 if not isdir(homedir):
792 792 homedir = os.path.join(env['USERPROFILE'])
793 793 if not isdir(homedir):
794 794 raise HomeDirError
795 795 return homedir
796 796 except:
797 797 try:
798 798 # Use the registry to get the 'My Documents' folder.
799 799 import _winreg as wreg
800 800 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
801 801 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
802 802 homedir = wreg.QueryValueEx(key,'Personal')[0]
803 803 key.Close()
804 804 if not isdir(homedir):
805 805 e = ('Invalid "Personal" folder registry key '
806 806 'typically "My Documents".\n'
807 807 'Value: %s\n'
808 808 'This is not a valid directory on your system.' %
809 809 homedir)
810 810 raise HomeDirError(e)
811 811 return homedir
812 812 except HomeDirError:
813 813 raise
814 814 except:
815 815 return 'C:\\'
816 816 elif os.name == 'dos':
817 817 # Desperate, may do absurd things in classic MacOS. May work under DOS.
818 818 return 'C:\\'
819 819 else:
820 820 raise HomeDirError,'support for your operating system not implemented.'
821 821
822 822 #****************************************************************************
823 823 # strings and text
824 824
825 825 class LSString(str):
826 826 """String derivative with a special access attributes.
827 827
828 828 These are normal strings, but with the special attributes:
829 829
830 830 .l (or .list) : value as list (split on newlines).
831 831 .n (or .nlstr): original value (the string itself).
832 832 .s (or .spstr): value as whitespace-separated string.
833 833
834 834 Any values which require transformations are computed only once and
835 835 cached.
836 836
837 837 Such strings are very useful to efficiently interact with the shell, which
838 838 typically only understands whitespace-separated options for commands."""
839 839
840 840 def get_list(self):
841 841 try:
842 842 return self.__list
843 843 except AttributeError:
844 844 self.__list = self.split('\n')
845 845 return self.__list
846 846
847 847 l = list = property(get_list)
848 848
849 849 def get_spstr(self):
850 850 try:
851 851 return self.__spstr
852 852 except AttributeError:
853 853 self.__spstr = self.replace('\n',' ')
854 854 return self.__spstr
855 855
856 856 s = spstr = property(get_spstr)
857 857
858 858 def get_nlstr(self):
859 859 return self
860 860
861 861 n = nlstr = property(get_nlstr)
862 862
863 863 class SList(list):
864 864 """List derivative with a special access attributes.
865 865
866 866 These are normal lists, but with the special attributes:
867 867
868 868 .l (or .list) : value as list (the list itself).
869 869 .n (or .nlstr): value as a string, joined on newlines.
870 870 .s (or .spstr): value as a string, joined on spaces.
871 871
872 872 Any values which require transformations are computed only once and
873 873 cached."""
874 874
875 875 def get_list(self):
876 876 return self
877 877
878 878 l = list = property(get_list)
879 879
880 880 def get_spstr(self):
881 881 try:
882 882 return self.__spstr
883 883 except AttributeError:
884 884 self.__spstr = ' '.join(self)
885 885 return self.__spstr
886 886
887 887 s = spstr = property(get_spstr)
888 888
889 889 def get_nlstr(self):
890 890 try:
891 891 return self.__nlstr
892 892 except AttributeError:
893 893 self.__nlstr = '\n'.join(self)
894 894 return self.__nlstr
895 895
896 896 n = nlstr = property(get_nlstr)
897 897
898 898 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
899 899 """Take multiple lines of input.
900 900
901 901 A list with each line of input as a separate element is returned when a
902 902 termination string is entered (defaults to a single '.'). Input can also
903 903 terminate via EOF (^D in Unix, ^Z-RET in Windows).
904 904
905 905 Lines of input which end in \\ are joined into single entries (and a
906 906 secondary continuation prompt is issued as long as the user terminates
907 907 lines with \\). This allows entering very long strings which are still
908 908 meant to be treated as single entities.
909 909 """
910 910
911 911 try:
912 912 if header:
913 913 header += '\n'
914 914 lines = [raw_input(header + ps1)]
915 915 except EOFError:
916 916 return []
917 917 terminate = [terminate_str]
918 918 try:
919 919 while lines[-1:] != terminate:
920 920 new_line = raw_input(ps1)
921 921 while new_line.endswith('\\'):
922 922 new_line = new_line[:-1] + raw_input(ps2)
923 923 lines.append(new_line)
924 924
925 925 return lines[:-1] # don't return the termination command
926 926 except EOFError:
927 927 print
928 928 return lines
929 929
930 930 #----------------------------------------------------------------------------
931 931 def raw_input_ext(prompt='', ps2='... '):
932 932 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
933 933
934 934 line = raw_input(prompt)
935 935 while line.endswith('\\'):
936 936 line = line[:-1] + raw_input(ps2)
937 937 return line
938 938
939 939 #----------------------------------------------------------------------------
940 940 def ask_yes_no(prompt,default=None):
941 941 """Asks a question and returns an integer 1/0 (y/n) answer.
942 942
943 943 If default is given (one of 'y','n'), it is used if the user input is
944 944 empty. Otherwise the question is repeated until an answer is given.
945 945 If EOF occurs 20 times consecutively, the default answer is assumed,
946 946 or if there is no default, an exception is raised to prevent infinite
947 947 loops.
948 948
949 949 Valid answers are: y/yes/n/no (match is not case sensitive)."""
950 950
951 answers = {'y':1,'n':0,'yes':1,'no':0}
951 answers = {'y':True,'n':False,'yes':True,'no':False}
952 952 ans = None
953 953 eofs, max_eofs = 0, 20
954 954 while ans not in answers.keys():
955 955 try:
956 956 ans = raw_input(prompt+' ').lower()
957 957 if not ans: # response was an empty string
958 958 ans = default
959 959 eofs = 0
960 960 except (EOFError,KeyboardInterrupt):
961 961 eofs = eofs + 1
962 962 if eofs >= max_eofs:
963 963 if default in answers.keys():
964 964 ans = default
965 965 else:
966 966 raise
967 967
968 968 return answers[ans]
969 969
970 970 #----------------------------------------------------------------------------
971 971 def marquee(txt='',width=78,mark='*'):
972 972 """Return the input string centered in a 'marquee'."""
973 973 if not txt:
974 974 return (mark*width)[:width]
975 975 nmark = (width-len(txt)-2)/len(mark)/2
976 976 if nmark < 0: nmark =0
977 977 marks = mark*nmark
978 978 return '%s %s %s' % (marks,txt,marks)
979 979
980 980 #----------------------------------------------------------------------------
981 981 class EvalDict:
982 982 """
983 983 Emulate a dict which evaluates its contents in the caller's frame.
984 984
985 985 Usage:
986 986 >>>number = 19
987 987 >>>text = "python"
988 988 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
989 989 """
990 990
991 991 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
992 992 # modified (shorter) version of:
993 993 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
994 994 # Skip Montanaro (skip@pobox.com).
995 995
996 996 def __getitem__(self, name):
997 997 frame = sys._getframe(1)
998 998 return eval(name, frame.f_globals, frame.f_locals)
999 999
1000 1000 EvalString = EvalDict # for backwards compatibility
1001 1001 #----------------------------------------------------------------------------
1002 1002 def qw(words,flat=0,sep=None,maxsplit=-1):
1003 1003 """Similar to Perl's qw() operator, but with some more options.
1004 1004
1005 1005 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1006 1006
1007 1007 words can also be a list itself, and with flat=1, the output will be
1008 1008 recursively flattened. Examples:
1009 1009
1010 1010 >>> qw('1 2')
1011 1011 ['1', '2']
1012 1012 >>> qw(['a b','1 2',['m n','p q']])
1013 1013 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1014 1014 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1015 1015 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1016 1016
1017 1017 if type(words) in StringTypes:
1018 1018 return [word.strip() for word in words.split(sep,maxsplit)
1019 1019 if word and not word.isspace() ]
1020 1020 if flat:
1021 1021 return flatten(map(qw,words,[1]*len(words)))
1022 1022 return map(qw,words)
1023 1023
1024 1024 #----------------------------------------------------------------------------
1025 1025 def qwflat(words,sep=None,maxsplit=-1):
1026 1026 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1027 1027 return qw(words,1,sep,maxsplit)
1028 1028
1029 1029 #-----------------------------------------------------------------------------
1030 1030 def list_strings(arg):
1031 1031 """Always return a list of strings, given a string or list of strings
1032 1032 as input."""
1033 1033
1034 1034 if type(arg) in StringTypes: return [arg]
1035 1035 else: return arg
1036 1036
1037 1037 #----------------------------------------------------------------------------
1038 1038 def grep(pat,list,case=1):
1039 1039 """Simple minded grep-like function.
1040 1040 grep(pat,list) returns occurrences of pat in list, None on failure.
1041 1041
1042 1042 It only does simple string matching, with no support for regexps. Use the
1043 1043 option case=0 for case-insensitive matching."""
1044 1044
1045 1045 # This is pretty crude. At least it should implement copying only references
1046 1046 # to the original data in case it's big. Now it copies the data for output.
1047 1047 out=[]
1048 1048 if case:
1049 1049 for term in list:
1050 1050 if term.find(pat)>-1: out.append(term)
1051 1051 else:
1052 1052 lpat=pat.lower()
1053 1053 for term in list:
1054 1054 if term.lower().find(lpat)>-1: out.append(term)
1055 1055
1056 1056 if len(out): return out
1057 1057 else: return None
1058 1058
1059 1059 #----------------------------------------------------------------------------
1060 1060 def dgrep(pat,*opts):
1061 1061 """Return grep() on dir()+dir(__builtins__).
1062 1062
1063 1063 A very common use of grep() when working interactively."""
1064 1064
1065 1065 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1066 1066
1067 1067 #----------------------------------------------------------------------------
1068 1068 def idgrep(pat):
1069 1069 """Case-insensitive dgrep()"""
1070 1070
1071 1071 return dgrep(pat,0)
1072 1072
1073 1073 #----------------------------------------------------------------------------
1074 1074 def igrep(pat,list):
1075 1075 """Synonym for case-insensitive grep."""
1076 1076
1077 1077 return grep(pat,list,case=0)
1078 1078
1079 1079 #----------------------------------------------------------------------------
1080 1080 def indent(str,nspaces=4,ntabs=0):
1081 1081 """Indent a string a given number of spaces or tabstops.
1082 1082
1083 1083 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1084 1084 """
1085 1085 if str is None:
1086 1086 return
1087 1087 ind = '\t'*ntabs+' '*nspaces
1088 1088 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1089 1089 if outstr.endswith(os.linesep+ind):
1090 1090 return outstr[:-len(ind)]
1091 1091 else:
1092 1092 return outstr
1093 1093
1094 1094 #-----------------------------------------------------------------------------
1095 1095 def native_line_ends(filename,backup=1):
1096 1096 """Convert (in-place) a file to line-ends native to the current OS.
1097 1097
1098 1098 If the optional backup argument is given as false, no backup of the
1099 1099 original file is left. """
1100 1100
1101 1101 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1102 1102
1103 1103 bak_filename = filename + backup_suffixes[os.name]
1104 1104
1105 1105 original = open(filename).read()
1106 1106 shutil.copy2(filename,bak_filename)
1107 1107 try:
1108 1108 new = open(filename,'wb')
1109 1109 new.write(os.linesep.join(original.splitlines()))
1110 1110 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1111 1111 new.close()
1112 1112 except:
1113 1113 os.rename(bak_filename,filename)
1114 1114 if not backup:
1115 1115 try:
1116 1116 os.remove(bak_filename)
1117 1117 except:
1118 1118 pass
1119 1119
1120 1120 #----------------------------------------------------------------------------
1121 1121 def get_pager_cmd(pager_cmd = None):
1122 1122 """Return a pager command.
1123 1123
1124 1124 Makes some attempts at finding an OS-correct one."""
1125 1125
1126 1126 if os.name == 'posix':
1127 1127 default_pager_cmd = 'less -r' # -r for color control sequences
1128 1128 elif os.name in ['nt','dos']:
1129 1129 default_pager_cmd = 'type'
1130 1130
1131 1131 if pager_cmd is None:
1132 1132 try:
1133 1133 pager_cmd = os.environ['PAGER']
1134 1134 except:
1135 1135 pager_cmd = default_pager_cmd
1136 1136 return pager_cmd
1137 1137
1138 1138 #-----------------------------------------------------------------------------
1139 1139 def get_pager_start(pager,start):
1140 1140 """Return the string for paging files with an offset.
1141 1141
1142 1142 This is the '+N' argument which less and more (under Unix) accept.
1143 1143 """
1144 1144
1145 1145 if pager in ['less','more']:
1146 1146 if start:
1147 1147 start_string = '+' + str(start)
1148 1148 else:
1149 1149 start_string = ''
1150 1150 else:
1151 1151 start_string = ''
1152 1152 return start_string
1153 1153
1154 1154 #----------------------------------------------------------------------------
1155 1155 def page_dumb(strng,start=0,screen_lines=25):
1156 1156 """Very dumb 'pager' in Python, for when nothing else works.
1157 1157
1158 1158 Only moves forward, same interface as page(), except for pager_cmd and
1159 1159 mode."""
1160 1160
1161 1161 out_ln = strng.splitlines()[start:]
1162 1162 screens = chop(out_ln,screen_lines-1)
1163 1163 if len(screens) == 1:
1164 1164 print >>Term.cout, os.linesep.join(screens[0])
1165 1165 else:
1166 1166 for scr in screens[0:-1]:
1167 1167 print >>Term.cout, os.linesep.join(scr)
1168 1168 ans = raw_input('---Return to continue, q to quit--- ')
1169 1169 if ans.lower().startswith('q'):
1170 1170 return
1171 1171 print >>Term.cout, os.linesep.join(screens[-1])
1172 1172
1173 1173 #----------------------------------------------------------------------------
1174 1174 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1175 1175 """Print a string, piping through a pager after a certain length.
1176 1176
1177 1177 The screen_lines parameter specifies the number of *usable* lines of your
1178 1178 terminal screen (total lines minus lines you need to reserve to show other
1179 1179 information).
1180 1180
1181 1181 If you set screen_lines to a number <=0, page() will try to auto-determine
1182 1182 your screen size and will only use up to (screen_size+screen_lines) for
1183 1183 printing, paging after that. That is, if you want auto-detection but need
1184 1184 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1185 1185 auto-detection without any lines reserved simply use screen_lines = 0.
1186 1186
1187 1187 If a string won't fit in the allowed lines, it is sent through the
1188 1188 specified pager command. If none given, look for PAGER in the environment,
1189 1189 and ultimately default to less.
1190 1190
1191 1191 If no system pager works, the string is sent through a 'dumb pager'
1192 1192 written in python, very simplistic.
1193 1193 """
1194 1194
1195 1195 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1196 1196 TERM = os.environ.get('TERM','dumb')
1197 1197 if TERM in ['dumb','emacs'] and os.name != 'nt':
1198 1198 print strng
1199 1199 return
1200 1200 # chop off the topmost part of the string we don't want to see
1201 1201 str_lines = strng.split(os.linesep)[start:]
1202 1202 str_toprint = os.linesep.join(str_lines)
1203 1203 num_newlines = len(str_lines)
1204 1204 len_str = len(str_toprint)
1205 1205
1206 1206 # Dumb heuristics to guesstimate number of on-screen lines the string
1207 1207 # takes. Very basic, but good enough for docstrings in reasonable
1208 1208 # terminals. If someone later feels like refining it, it's not hard.
1209 1209 numlines = max(num_newlines,int(len_str/80)+1)
1210 1210
1211 1211 screen_lines_def = 25 # default value if we can't auto-determine
1212 1212
1213 1213 # auto-determine screen size
1214 1214 if screen_lines <= 0:
1215 1215 if TERM=='xterm':
1216 1216 try:
1217 1217 import curses
1218 1218 if hasattr(curses,'initscr'):
1219 1219 use_curses = 1
1220 1220 else:
1221 1221 use_curses = 0
1222 1222 except ImportError:
1223 1223 use_curses = 0
1224 1224 else:
1225 1225 # curses causes problems on many terminals other than xterm.
1226 1226 use_curses = 0
1227 1227 if use_curses:
1228 1228 scr = curses.initscr()
1229 1229 screen_lines_real,screen_cols = scr.getmaxyx()
1230 1230 curses.endwin()
1231 1231 screen_lines += screen_lines_real
1232 1232 #print '***Screen size:',screen_lines_real,'lines x',\
1233 1233 #screen_cols,'columns.' # dbg
1234 1234 else:
1235 1235 screen_lines += screen_lines_def
1236 1236
1237 1237 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1238 1238 if numlines <= screen_lines :
1239 1239 #print '*** normal print' # dbg
1240 1240 print >>Term.cout, str_toprint
1241 1241 else:
1242 1242 # Try to open pager and default to internal one if that fails.
1243 1243 # All failure modes are tagged as 'retval=1', to match the return
1244 1244 # value of a failed system command. If any intermediate attempt
1245 1245 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1246 1246 pager_cmd = get_pager_cmd(pager_cmd)
1247 1247 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1248 1248 if os.name == 'nt':
1249 1249 if pager_cmd.startswith('type'):
1250 1250 # The default WinXP 'type' command is failing on complex strings.
1251 1251 retval = 1
1252 1252 else:
1253 1253 tmpname = tempfile.mktemp('.txt')
1254 1254 tmpfile = file(tmpname,'wt')
1255 1255 tmpfile.write(strng)
1256 1256 tmpfile.close()
1257 1257 cmd = "%s < %s" % (pager_cmd,tmpname)
1258 1258 if os.system(cmd):
1259 1259 retval = 1
1260 1260 else:
1261 1261 retval = None
1262 1262 os.remove(tmpname)
1263 1263 else:
1264 1264 try:
1265 1265 retval = None
1266 1266 # if I use popen4, things hang. No idea why.
1267 1267 #pager,shell_out = os.popen4(pager_cmd)
1268 1268 pager = os.popen(pager_cmd,'w')
1269 1269 pager.write(strng)
1270 1270 pager.close()
1271 1271 retval = pager.close() # success returns None
1272 1272 except IOError,msg: # broken pipe when user quits
1273 1273 if msg.args == (32,'Broken pipe'):
1274 1274 retval = None
1275 1275 else:
1276 1276 retval = 1
1277 1277 except OSError:
1278 1278 # Other strange problems, sometimes seen in Win2k/cygwin
1279 1279 retval = 1
1280 1280 if retval is not None:
1281 1281 page_dumb(strng,screen_lines=screen_lines)
1282 1282
1283 1283 #----------------------------------------------------------------------------
1284 1284 def page_file(fname,start = 0, pager_cmd = None):
1285 1285 """Page a file, using an optional pager command and starting line.
1286 1286 """
1287 1287
1288 1288 pager_cmd = get_pager_cmd(pager_cmd)
1289 1289 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1290 1290
1291 1291 try:
1292 1292 if os.environ['TERM'] in ['emacs','dumb']:
1293 1293 raise EnvironmentError
1294 1294 xsys(pager_cmd + ' ' + fname)
1295 1295 except:
1296 1296 try:
1297 1297 if start > 0:
1298 1298 start -= 1
1299 1299 page(open(fname).read(),start)
1300 1300 except:
1301 1301 print 'Unable to show file',`fname`
1302 1302
1303 1303 #----------------------------------------------------------------------------
1304 1304 def snip_print(str,width = 75,print_full = 0,header = ''):
1305 1305 """Print a string snipping the midsection to fit in width.
1306 1306
1307 1307 print_full: mode control:
1308 1308 - 0: only snip long strings
1309 1309 - 1: send to page() directly.
1310 1310 - 2: snip long strings and ask for full length viewing with page()
1311 1311 Return 1 if snipping was necessary, 0 otherwise."""
1312 1312
1313 1313 if print_full == 1:
1314 1314 page(header+str)
1315 1315 return 0
1316 1316
1317 1317 print header,
1318 1318 if len(str) < width:
1319 1319 print str
1320 1320 snip = 0
1321 1321 else:
1322 1322 whalf = int((width -5)/2)
1323 1323 print str[:whalf] + ' <...> ' + str[-whalf:]
1324 1324 snip = 1
1325 1325 if snip and print_full == 2:
1326 1326 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1327 1327 page(str)
1328 1328 return snip
1329 1329
1330 1330 #****************************************************************************
1331 1331 # lists, dicts and structures
1332 1332
1333 1333 def belong(candidates,checklist):
1334 1334 """Check whether a list of items appear in a given list of options.
1335 1335
1336 1336 Returns a list of 1 and 0, one for each candidate given."""
1337 1337
1338 1338 return [x in checklist for x in candidates]
1339 1339
1340 1340 #----------------------------------------------------------------------------
1341 1341 def uniq_stable(elems):
1342 1342 """uniq_stable(elems) -> list
1343 1343
1344 1344 Return from an iterable, a list of all the unique elements in the input,
1345 1345 but maintaining the order in which they first appear.
1346 1346
1347 1347 A naive solution to this problem which just makes a dictionary with the
1348 1348 elements as keys fails to respect the stability condition, since
1349 1349 dictionaries are unsorted by nature.
1350 1350
1351 1351 Note: All elements in the input must be valid dictionary keys for this
1352 1352 routine to work, as it internally uses a dictionary for efficiency
1353 1353 reasons."""
1354 1354
1355 1355 unique = []
1356 1356 unique_dict = {}
1357 1357 for nn in elems:
1358 1358 if nn not in unique_dict:
1359 1359 unique.append(nn)
1360 1360 unique_dict[nn] = None
1361 1361 return unique
1362 1362
1363 1363 #----------------------------------------------------------------------------
1364 1364 class NLprinter:
1365 1365 """Print an arbitrarily nested list, indicating index numbers.
1366 1366
1367 1367 An instance of this class called nlprint is available and callable as a
1368 1368 function.
1369 1369
1370 1370 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1371 1371 and using 'sep' to separate the index from the value. """
1372 1372
1373 1373 def __init__(self):
1374 1374 self.depth = 0
1375 1375
1376 1376 def __call__(self,lst,pos='',**kw):
1377 1377 """Prints the nested list numbering levels."""
1378 1378 kw.setdefault('indent',' ')
1379 1379 kw.setdefault('sep',': ')
1380 1380 kw.setdefault('start',0)
1381 1381 kw.setdefault('stop',len(lst))
1382 1382 # we need to remove start and stop from kw so they don't propagate
1383 1383 # into a recursive call for a nested list.
1384 1384 start = kw['start']; del kw['start']
1385 1385 stop = kw['stop']; del kw['stop']
1386 1386 if self.depth == 0 and 'header' in kw.keys():
1387 1387 print kw['header']
1388 1388
1389 1389 for idx in range(start,stop):
1390 1390 elem = lst[idx]
1391 1391 if type(elem)==type([]):
1392 1392 self.depth += 1
1393 1393 self.__call__(elem,itpl('$pos$idx,'),**kw)
1394 1394 self.depth -= 1
1395 1395 else:
1396 1396 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1397 1397
1398 1398 nlprint = NLprinter()
1399 1399 #----------------------------------------------------------------------------
1400 1400 def all_belong(candidates,checklist):
1401 1401 """Check whether a list of items ALL appear in a given list of options.
1402 1402
1403 1403 Returns a single 1 or 0 value."""
1404 1404
1405 1405 return 1-(0 in [x in checklist for x in candidates])
1406 1406
1407 1407 #----------------------------------------------------------------------------
1408 1408 def sort_compare(lst1,lst2,inplace = 1):
1409 1409 """Sort and compare two lists.
1410 1410
1411 1411 By default it does it in place, thus modifying the lists. Use inplace = 0
1412 1412 to avoid that (at the cost of temporary copy creation)."""
1413 1413 if not inplace:
1414 1414 lst1 = lst1[:]
1415 1415 lst2 = lst2[:]
1416 1416 lst1.sort(); lst2.sort()
1417 1417 return lst1 == lst2
1418 1418
1419 1419 #----------------------------------------------------------------------------
1420 1420 def mkdict(**kwargs):
1421 1421 """Return a dict from a keyword list.
1422 1422
1423 1423 It's just syntactic sugar for making ditcionary creation more convenient:
1424 1424 # the standard way
1425 1425 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1426 1426 # a cleaner way
1427 1427 >>>data = dict(red=1, green=2, blue=3)
1428 1428
1429 1429 If you need more than this, look at the Struct() class."""
1430 1430
1431 1431 return kwargs
1432 1432
1433 1433 #----------------------------------------------------------------------------
1434 1434 def list2dict(lst):
1435 1435 """Takes a list of (key,value) pairs and turns it into a dict."""
1436 1436
1437 1437 dic = {}
1438 1438 for k,v in lst: dic[k] = v
1439 1439 return dic
1440 1440
1441 1441 #----------------------------------------------------------------------------
1442 1442 def list2dict2(lst,default=''):
1443 1443 """Takes a list and turns it into a dict.
1444 1444 Much slower than list2dict, but more versatile. This version can take
1445 1445 lists with sublists of arbitrary length (including sclars)."""
1446 1446
1447 1447 dic = {}
1448 1448 for elem in lst:
1449 1449 if type(elem) in (types.ListType,types.TupleType):
1450 1450 size = len(elem)
1451 1451 if size == 0:
1452 1452 pass
1453 1453 elif size == 1:
1454 1454 dic[elem] = default
1455 1455 else:
1456 1456 k,v = elem[0], elem[1:]
1457 1457 if len(v) == 1: v = v[0]
1458 1458 dic[k] = v
1459 1459 else:
1460 1460 dic[elem] = default
1461 1461 return dic
1462 1462
1463 1463 #----------------------------------------------------------------------------
1464 1464 def flatten(seq):
1465 1465 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1466 1466
1467 1467 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1468 1468
1469 1469 # if the x=0 isn't made, a *global* variable x is left over after calling
1470 1470 # this function, with the value of the last element in the return
1471 1471 # list. This does seem like a bug big time to me.
1472 1472
1473 1473 # the problem is fixed with the x=0, which seems to force the creation of
1474 1474 # a local name
1475 1475
1476 1476 x = 0
1477 1477 return [x for subseq in seq for x in subseq]
1478 1478
1479 1479 #----------------------------------------------------------------------------
1480 1480 def get_slice(seq,start=0,stop=None,step=1):
1481 1481 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1482 1482 if stop == None:
1483 1483 stop = len(seq)
1484 1484 item = lambda i: seq[i]
1485 1485 return map(item,xrange(start,stop,step))
1486 1486
1487 1487 #----------------------------------------------------------------------------
1488 1488 def chop(seq,size):
1489 1489 """Chop a sequence into chunks of the given size."""
1490 1490 chunk = lambda i: seq[i:i+size]
1491 1491 return map(chunk,xrange(0,len(seq),size))
1492 1492
1493 1493 #----------------------------------------------------------------------------
1494 1494 def with(object, **args):
1495 1495 """Set multiple attributes for an object, similar to Pascal's with.
1496 1496
1497 1497 Example:
1498 1498 with(jim,
1499 1499 born = 1960,
1500 1500 haircolour = 'Brown',
1501 1501 eyecolour = 'Green')
1502 1502
1503 1503 Credit: Greg Ewing, in
1504 1504 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1505 1505
1506 1506 object.__dict__.update(args)
1507 1507
1508 1508 #----------------------------------------------------------------------------
1509 1509 def setattr_list(obj,alist,nspace = None):
1510 1510 """Set a list of attributes for an object taken from a namespace.
1511 1511
1512 1512 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1513 1513 alist with their values taken from nspace, which must be a dict (something
1514 1514 like locals() will often do) If nspace isn't given, locals() of the
1515 1515 *caller* is used, so in most cases you can omit it.
1516 1516
1517 1517 Note that alist can be given as a string, which will be automatically
1518 1518 split into a list on whitespace. If given as a list, it must be a list of
1519 1519 *strings* (the variable names themselves), not of variables."""
1520 1520
1521 1521 # this grabs the local variables from the *previous* call frame -- that is
1522 1522 # the locals from the function that called setattr_list().
1523 1523 # - snipped from weave.inline()
1524 1524 if nspace is None:
1525 1525 call_frame = sys._getframe().f_back
1526 1526 nspace = call_frame.f_locals
1527 1527
1528 1528 if type(alist) in StringTypes:
1529 1529 alist = alist.split()
1530 1530 for attr in alist:
1531 1531 val = eval(attr,nspace)
1532 1532 setattr(obj,attr,val)
1533 1533
1534 1534 #----------------------------------------------------------------------------
1535 1535 def getattr_list(obj,alist,*args):
1536 1536 """getattr_list(obj,alist[, default]) -> attribute list.
1537 1537
1538 1538 Get a list of named attributes for an object. When a default argument is
1539 1539 given, it is returned when the attribute doesn't exist; without it, an
1540 1540 exception is raised in that case.
1541 1541
1542 1542 Note that alist can be given as a string, which will be automatically
1543 1543 split into a list on whitespace. If given as a list, it must be a list of
1544 1544 *strings* (the variable names themselves), not of variables."""
1545 1545
1546 1546 if type(alist) in StringTypes:
1547 1547 alist = alist.split()
1548 1548 if args:
1549 1549 if len(args)==1:
1550 1550 default = args[0]
1551 1551 return map(lambda attr: getattr(obj,attr,default),alist)
1552 1552 else:
1553 1553 raise ValueError,'getattr_list() takes only one optional argument'
1554 1554 else:
1555 1555 return map(lambda attr: getattr(obj,attr),alist)
1556 1556
1557 1557 #----------------------------------------------------------------------------
1558 1558 def map_method(method,object_list,*argseq,**kw):
1559 1559 """map_method(method,object_list,*args,**kw) -> list
1560 1560
1561 1561 Return a list of the results of applying the methods to the items of the
1562 1562 argument sequence(s). If more than one sequence is given, the method is
1563 1563 called with an argument list consisting of the corresponding item of each
1564 1564 sequence. All sequences must be of the same length.
1565 1565
1566 1566 Keyword arguments are passed verbatim to all objects called.
1567 1567
1568 1568 This is Python code, so it's not nearly as fast as the builtin map()."""
1569 1569
1570 1570 out_list = []
1571 1571 idx = 0
1572 1572 for object in object_list:
1573 1573 try:
1574 1574 handler = getattr(object, method)
1575 1575 except AttributeError:
1576 1576 out_list.append(None)
1577 1577 else:
1578 1578 if argseq:
1579 1579 args = map(lambda lst:lst[idx],argseq)
1580 1580 #print 'ob',object,'hand',handler,'ar',args # dbg
1581 1581 out_list.append(handler(args,**kw))
1582 1582 else:
1583 1583 out_list.append(handler(**kw))
1584 1584 idx += 1
1585 1585 return out_list
1586 1586
1587 1587 #----------------------------------------------------------------------------
1588 1588 # Proposed popitem() extension, written as a method
1589 1589
1590 1590 class NotGiven: pass
1591 1591
1592 1592 def popkey(dct,key,default=NotGiven):
1593 1593 """Return dct[key] and delete dct[key].
1594 1594
1595 1595 If default is given, return it if dct[key] doesn't exist, otherwise raise
1596 1596 KeyError. """
1597 1597
1598 1598 try:
1599 1599 val = dct[key]
1600 1600 except KeyError:
1601 1601 if default is NotGiven:
1602 1602 raise
1603 1603 else:
1604 1604 return default
1605 1605 else:
1606 1606 del dct[key]
1607 1607 return val
1608 1608 #*************************** end of file <genutils.py> **********************
1609 1609
@@ -1,72 +1,95 b''
1 1 """hooks for IPython.
2 2
3 3 In Python, it is possible to overwrite any method of any object if you really
4 4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 5 be overwritten by users for customization purposes. This module defines the
6 6 default versions of all such hooks, which get used by IPython if not
7 7 overridden by the user.
8 8
9 9 hooks are simple functions, but they should be declared with 'self' as their
10 10 first argument, because when activated they are registered into IPython as
11 11 instance methods. The self argument will be the IPython running instance
12 12 itself, so hooks have full access to the entire IPython object.
13 13
14 14 If you wish to define a new hook and activate it, you need to put the
15 15 necessary code into a python file which can be either imported or execfile()'d
16 16 from within your ipythonrc configuration.
17 17
18 18 For example, suppose that you have a module called 'myiphooks' in your
19 19 PYTHONPATH, which contains the following definition:
20 20
21 21 import os
22 22 def calljed(self,filename, linenum):
23 23 "My editor hook calls the jed editor directly."
24 24 print "Calling my own editor, jed ..."
25 25 os.system('jed +%d %s' % (linenum,filename))
26 26
27 27 You can then execute the following line of code to make it the new IPython
28 28 editor hook, after having imported 'myiphooks':
29 29
30 30 ip_set_hook('editor',myiphooks.calljed)
31 31
32 32 The ip_set_hook function is put by IPython into the builtin namespace, so it
33 33 is always available from all running code.
34 34
35 $Id: hooks.py 535 2005-03-02 08:42:25Z fperez $"""
35 $Id: hooks.py 960 2005-12-28 06:51:01Z fperez $"""
36 36
37 37 #*****************************************************************************
38 38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 39 #
40 40 # Distributed under the terms of the BSD License. The full license is in
41 41 # the file COPYING, distributed as part of this software.
42 42 #*****************************************************************************
43 43
44 44 from IPython import Release
45 45 __author__ = '%s <%s>' % Release.authors['Fernando']
46 46 __license__ = Release.license
47 47 __version__ = Release.version
48 48
49 49 import os
50 50
51 # List here all the default hooks. For now it's just the editor, but over
52 # time we'll move here all the public API for user-accessible things.
53 __all__ = ['editor']
51 # List here all the default hooks. For now it's just the editor functions
52 # but over time we'll move here all the public API for user-accessible things.
53 __all__ = ['editor', 'fix_error_editor']
54 54
55 55 def editor(self,filename, linenum):
56 56 """Open the default editor at the given filename and linenumber.
57 57
58 58 This is IPython's default editor hook, you can use it as an example to
59 59 write your own modified one. To set your own editor function as the
60 60 new editor hook, call ip_set_hook('editor',yourfunc)."""
61 61
62 62 # IPython configures a default editor at startup by reading $EDITOR from
63 63 # the environment, and falling back on vi (unix) or notepad (win32).
64 64 editor = self.rc.editor
65 65
66 66 # marker for at which line to open the file (for existing objects)
67 67 if linenum is None or editor=='notepad':
68 68 linemark = ''
69 69 else:
70 70 linemark = '+%d' % linenum
71 71 # Call the actual editor
72 72 os.system('%s %s %s' % (editor,linemark,filename))
73
74 import tempfile
75 def fix_error_editor(self,filename,linenum,column,msg):
76 """Open the editor at the given filename, linenumber, column and
77 show an error message. This is used for correcting syntax errors.
78 The current implementation only has special support for the VIM editor,
79 and falls back on the 'editor' hook if VIM is not used.
80
81 Call ip_set_hook('fix_error_editor',youfunc) to use your own function,
82 """
83 def vim_quickfix_file():
84 t = tempfile.NamedTemporaryFile()
85 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
86 t.flush()
87 return t
88 if os.path.basename(self.rc.editor) != 'vim':
89 self.hooks.editor(filename,linenum)
90 return
91 t = vim_quickfix_file()
92 try:
93 os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name)
94 finally:
95 t.close()
@@ -1,1904 +1,1964 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 959 2005-12-28 02:04:41Z fperez $
9 $Id: iplib.py 960 2005-12-28 06:51:01Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from __future__ import generators # for 2.2 backwards-compatibility
32 32
33 33 from IPython import Release
34 34 __author__ = '%s <%s>\n%s <%s>' % \
35 35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 36 __license__ = Release.license
37 37 __version__ = Release.version
38 38
39 39 # Python standard modules
40 40 import __main__
41 41 import __builtin__
42 42 import StringIO
43 43 import bdb
44 44 import cPickle as pickle
45 45 import codeop
46 46 import exceptions
47 47 import glob
48 48 import inspect
49 49 import keyword
50 50 import new
51 51 import os
52 52 import pdb
53 53 import pydoc
54 54 import re
55 55 import shutil
56 56 import string
57 57 import sys
58 58 import traceback
59 59 import types
60 60
61 61 from pprint import pprint, pformat
62 62
63 63 # IPython's own modules
64 64 import IPython
65 65 from IPython import OInspect,PyColorize,ultraTB
66 66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 67 from IPython.FakeModule import FakeModule
68 68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 69 from IPython.Logger import Logger
70 70 from IPython.Magic import Magic,magic2python
71 71 from IPython.Struct import Struct
72 72 from IPython.background_jobs import BackgroundJobManager
73 73 from IPython.usage import cmd_line_usage,interactive_usage
74 74 from IPython.genutils import *
75 75
76 76 # store the builtin raw_input globally, and use this always, in case user code
77 77 # overwrites it (like wx.py.PyShell does)
78 78 raw_input_original = raw_input
79 79
80 80 #****************************************************************************
81 81 # Some utility function definitions
82 82
83 83 # This can be replaced with an isspace() call once we drop 2.2 compatibility
84 84 _isspace_match = re.compile(r'^\s+$').match
85 85 def isspace(s):
86 86 return bool(_isspace_match(s))
87 87
88 88 def esc_quotes(strng):
89 89 """Return the input string with single and double quotes escaped out"""
90 90
91 91 return strng.replace('"','\\"').replace("'","\\'")
92 92
93 93 def import_fail_info(mod_name,fns=None):
94 94 """Inform load failure for a module."""
95 95
96 96 if fns == None:
97 97 warn("Loading of %s failed.\n" % (mod_name,))
98 98 else:
99 99 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
100 100
101 101 def qw_lol(indata):
102 102 """qw_lol('a b') -> [['a','b']],
103 103 otherwise it's just a call to qw().
104 104
105 105 We need this to make sure the modules_some keys *always* end up as a
106 106 list of lists."""
107 107
108 108 if type(indata) in StringTypes:
109 109 return [qw(indata)]
110 110 else:
111 111 return qw(indata)
112 112
113 113 def ipmagic(arg_s):
114 114 """Call a magic function by name.
115 115
116 116 Input: a string containing the name of the magic function to call and any
117 117 additional arguments to be passed to the magic.
118 118
119 119 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
120 120 prompt:
121 121
122 122 In[1]: %name -opt foo bar
123 123
124 124 To call a magic without arguments, simply use ipmagic('name').
125 125
126 126 This provides a proper Python function to call IPython's magics in any
127 127 valid Python code you can type at the interpreter, including loops and
128 128 compound statements. It is added by IPython to the Python builtin
129 129 namespace upon initialization."""
130 130
131 131 args = arg_s.split(' ',1)
132 132 magic_name = args[0]
133 133 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
134 134 magic_name = magic_name[1:]
135 135 try:
136 136 magic_args = args[1]
137 137 except IndexError:
138 138 magic_args = ''
139 139 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
140 140 if fn is None:
141 141 error("Magic function `%s` not found." % magic_name)
142 142 else:
143 143 magic_args = __IPYTHON__.var_expand(magic_args)
144 144 return fn(magic_args)
145 145
146 146 def ipalias(arg_s):
147 147 """Call an alias by name.
148 148
149 149 Input: a string containing the name of the alias to call and any
150 150 additional arguments to be passed to the magic.
151 151
152 152 ipalias('name -opt foo bar') is equivalent to typing at the ipython
153 153 prompt:
154 154
155 155 In[1]: name -opt foo bar
156 156
157 157 To call an alias without arguments, simply use ipalias('name').
158 158
159 159 This provides a proper Python function to call IPython's aliases in any
160 160 valid Python code you can type at the interpreter, including loops and
161 161 compound statements. It is added by IPython to the Python builtin
162 162 namespace upon initialization."""
163 163
164 164 args = arg_s.split(' ',1)
165 165 alias_name = args[0]
166 166 try:
167 167 alias_args = args[1]
168 168 except IndexError:
169 169 alias_args = ''
170 170 if alias_name in __IPYTHON__.alias_table:
171 171 __IPYTHON__.call_alias(alias_name,alias_args)
172 172 else:
173 173 error("Alias `%s` not found." % alias_name)
174 174
175 175 def softspace(file, newvalue):
176 176 """Copied from code.py, to remove the dependency"""
177 177 oldvalue = 0
178 178 try:
179 179 oldvalue = file.softspace
180 180 except AttributeError:
181 181 pass
182 182 try:
183 183 file.softspace = newvalue
184 184 except (AttributeError, TypeError):
185 185 # "attribute-less object" or "read-only attributes"
186 186 pass
187 187 return oldvalue
188 188
189 189
190 190 #****************************************************************************
191 191 # Local use exceptions
192 192 class SpaceInInput(exceptions.Exception): pass
193 193
194 194 class IPythonExit(exceptions.Exception): pass
195 195
196 196 #****************************************************************************
197 197 # Local use classes
198 198 class Bunch: pass
199 199
200 200 class InputList(list):
201 201 """Class to store user input.
202 202
203 203 It's basically a list, but slices return a string instead of a list, thus
204 204 allowing things like (assuming 'In' is an instance):
205 205
206 206 exec In[4:7]
207 207
208 208 or
209 209
210 210 exec In[5:9] + In[14] + In[21:25]"""
211 211
212 212 def __getslice__(self,i,j):
213 213 return ''.join(list.__getslice__(self,i,j))
214 214
215 class SyntaxTB(ultraTB.ListTB):
216 """Extension which holds some state: the last exception value"""
217
218 def __init__(self,color_scheme = 'NoColor'):
219 ultraTB.ListTB.__init__(self,color_scheme)
220 self.last_syntax_error = None
221
222 def __call__(self, etype, value, elist):
223 self.last_syntax_error = value
224 ultraTB.ListTB.__call__(self,etype,value,elist)
225
226 def clear_err_state(self):
227 """Return the current error state and clear it"""
228 e = self.last_syntax_error
229 self.last_syntax_error = None
230 return e
231
215 232 #****************************************************************************
216 233 # Main IPython class
217 234 class InteractiveShell(Logger, Magic):
218 235 """An enhanced console for Python."""
219 236
220 237 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
221 238 user_ns = None,user_global_ns=None,banner2='',
222 239 custom_exceptions=((),None),embedded=False):
223 240
224 241 # Put a reference to self in builtins so that any form of embedded or
225 242 # imported code can test for being inside IPython.
226 243 __builtin__.__IPYTHON__ = self
227 244
228 245 # And load into builtins ipmagic/ipalias as well
229 246 __builtin__.ipmagic = ipmagic
230 247 __builtin__.ipalias = ipalias
231 248
232 249 # Add to __builtin__ other parts of IPython's public API
233 250 __builtin__.ip_set_hook = self.set_hook
234 251
235 252 # Keep in the builtins a flag for when IPython is active. We set it
236 253 # with setdefault so that multiple nested IPythons don't clobber one
237 254 # another. Each will increase its value by one upon being activated,
238 255 # which also gives us a way to determine the nesting level.
239 256 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
240 257
241 258 # Do the intuitively correct thing for quit/exit: we remove the
242 259 # builtins if they exist, and our own prefilter routine will handle
243 260 # these special cases
244 261 try:
245 262 del __builtin__.exit, __builtin__.quit
246 263 except AttributeError:
247 264 pass
248 265
249 266 # We need to know whether the instance is meant for embedding, since
250 267 # global/local namespaces need to be handled differently in that case
251 268 self.embedded = embedded
252 269
253 270 # command compiler
254 271 self.compile = codeop.CommandCompiler()
255 272
256 273 # User input buffer
257 274 self.buffer = []
258 275
259 276 # Default name given in compilation of code
260 277 self.filename = '<ipython console>'
261 278
262 279 # Create the namespace where the user will operate. user_ns is
263 280 # normally the only one used, and it is passed to the exec calls as
264 281 # the locals argument. But we do carry a user_global_ns namespace
265 282 # given as the exec 'globals' argument, This is useful in embedding
266 283 # situations where the ipython shell opens in a context where the
267 284 # distinction between locals and globals is meaningful.
268 285
269 286 # FIXME. For some strange reason, __builtins__ is showing up at user
270 287 # level as a dict instead of a module. This is a manual fix, but I
271 288 # should really track down where the problem is coming from. Alex
272 289 # Schmolck reported this problem first.
273 290
274 291 # A useful post by Alex Martelli on this topic:
275 292 # Re: inconsistent value from __builtins__
276 293 # Von: Alex Martelli <aleaxit@yahoo.com>
277 294 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
278 295 # Gruppen: comp.lang.python
279 296 # Referenzen: 1
280 297
281 298 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
282 299 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
283 300 # > <type 'dict'>
284 301 # > >>> print type(__builtins__)
285 302 # > <type 'module'>
286 303 # > Is this difference in return value intentional?
287 304
288 305 # Well, it's documented that '__builtins__' can be either a dictionary
289 306 # or a module, and it's been that way for a long time. Whether it's
290 307 # intentional (or sensible), I don't know. In any case, the idea is
291 308 # that if you need to access the built-in namespace directly, you
292 309 # should start with "import __builtin__" (note, no 's') which will
293 310 # definitely give you a module. Yeah, it's somewhat confusing:-(.
294 311
295 312 if user_ns is None:
296 313 # Set __name__ to __main__ to better match the behavior of the
297 314 # normal interpreter.
298 315 user_ns = {'__name__' :'__main__',
299 316 '__builtins__' : __builtin__,
300 317 }
301 318
302 319 if user_global_ns is None:
303 320 user_global_ns = {}
304 321
305 322 # Assign namespaces
306 323 # This is the namespace where all normal user variables live
307 324 self.user_ns = user_ns
308 325 # Embedded instances require a separate namespace for globals.
309 326 # Normally this one is unused by non-embedded instances.
310 327 self.user_global_ns = user_global_ns
311 328 # A namespace to keep track of internal data structures to prevent
312 329 # them from cluttering user-visible stuff. Will be updated later
313 330 self.internal_ns = {}
314 331
315 332 # Namespace of system aliases. Each entry in the alias
316 333 # table must be a 2-tuple of the form (N,name), where N is the number
317 334 # of positional arguments of the alias.
318 335 self.alias_table = {}
319 336
320 337 # A table holding all the namespaces IPython deals with, so that
321 338 # introspection facilities can search easily.
322 339 self.ns_table = {'user':user_ns,
323 340 'user_global':user_global_ns,
324 341 'alias':self.alias_table,
325 342 'internal':self.internal_ns,
326 343 'builtin':__builtin__.__dict__
327 344 }
328 345
329 346 # The user namespace MUST have a pointer to the shell itself.
330 347 self.user_ns[name] = self
331 348
332 349 # We need to insert into sys.modules something that looks like a
333 350 # module but which accesses the IPython namespace, for shelve and
334 351 # pickle to work interactively. Normally they rely on getting
335 352 # everything out of __main__, but for embedding purposes each IPython
336 353 # instance has its own private namespace, so we can't go shoving
337 354 # everything into __main__.
338 355
339 356 # note, however, that we should only do this for non-embedded
340 357 # ipythons, which really mimic the __main__.__dict__ with their own
341 358 # namespace. Embedded instances, on the other hand, should not do
342 359 # this because they need to manage the user local/global namespaces
343 360 # only, but they live within a 'normal' __main__ (meaning, they
344 361 # shouldn't overtake the execution environment of the script they're
345 362 # embedded in).
346 363
347 364 if not embedded:
348 365 try:
349 366 main_name = self.user_ns['__name__']
350 367 except KeyError:
351 368 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
352 369 else:
353 370 #print "pickle hack in place" # dbg
354 371 sys.modules[main_name] = FakeModule(self.user_ns)
355 372
356 373 # List of input with multi-line handling.
357 374 # Fill its zero entry, user counter starts at 1
358 375 self.input_hist = InputList(['\n'])
359 376
360 377 # list of visited directories
361 378 try:
362 379 self.dir_hist = [os.getcwd()]
363 380 except IOError, e:
364 381 self.dir_hist = []
365 382
366 383 # dict of output history
367 384 self.output_hist = {}
368 385
369 386 # dict of things NOT to alias (keywords, builtins and some magics)
370 387 no_alias = {}
371 388 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
372 389 for key in keyword.kwlist + no_alias_magics:
373 390 no_alias[key] = 1
374 391 no_alias.update(__builtin__.__dict__)
375 392 self.no_alias = no_alias
376 393
377 394 # make global variables for user access to these
378 395 self.user_ns['_ih'] = self.input_hist
379 396 self.user_ns['_oh'] = self.output_hist
380 397 self.user_ns['_dh'] = self.dir_hist
381 398
382 399 # user aliases to input and output histories
383 400 self.user_ns['In'] = self.input_hist
384 401 self.user_ns['Out'] = self.output_hist
385 402
386 403 # Store the actual shell's name
387 404 self.name = name
388 405
389 406 # Object variable to store code object waiting execution. This is
390 407 # used mainly by the multithreaded shells, but it can come in handy in
391 408 # other situations. No need to use a Queue here, since it's a single
392 409 # item which gets cleared once run.
393 410 self.code_to_run = None
394 411
395 412 # Job manager (for jobs run as background threads)
396 413 self.jobs = BackgroundJobManager()
397 414 # Put the job manager into builtins so it's always there.
398 415 __builtin__.jobs = self.jobs
399 416
400 417 # escapes for automatic behavior on the command line
401 418 self.ESC_SHELL = '!'
402 419 self.ESC_HELP = '?'
403 420 self.ESC_MAGIC = '%'
404 421 self.ESC_QUOTE = ','
405 422 self.ESC_QUOTE2 = ';'
406 423 self.ESC_PAREN = '/'
407 424
408 425 # And their associated handlers
409 426 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
410 427 self.ESC_QUOTE:self.handle_auto,
411 428 self.ESC_QUOTE2:self.handle_auto,
412 429 self.ESC_MAGIC:self.handle_magic,
413 430 self.ESC_HELP:self.handle_help,
414 431 self.ESC_SHELL:self.handle_shell_escape,
415 432 }
416 433
417 434 # class initializations
418 435 Logger.__init__(self,log_ns = self.user_ns)
419 436 Magic.__init__(self,self)
420 437
421 438 # an ugly hack to get a pointer to the shell, so I can start writing
422 439 # magic code via this pointer instead of the current mixin salad.
423 440 Magic.set_shell(self,self)
424 441
425 442 # Python source parser/formatter for syntax highlighting
426 443 pyformat = PyColorize.Parser().format
427 444 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
428 445
429 446 # hooks holds pointers used for user-side customizations
430 447 self.hooks = Struct()
431 448
432 449 # Set all default hooks, defined in the IPython.hooks module.
433 450 hooks = IPython.hooks
434 451 for hook_name in hooks.__all__:
435 452 self.set_hook(hook_name,getattr(hooks,hook_name))
436 453
437 454 # Flag to mark unconditional exit
438 455 self.exit_now = False
439 456
440 457 self.usage_min = """\
441 458 An enhanced console for Python.
442 459 Some of its features are:
443 460 - Readline support if the readline library is present.
444 461 - Tab completion in the local namespace.
445 462 - Logging of input, see command-line options.
446 463 - System shell escape via ! , eg !ls.
447 464 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
448 465 - Keeps track of locally defined variables via %who, %whos.
449 466 - Show object information with a ? eg ?x or x? (use ?? for more info).
450 467 """
451 468 if usage: self.usage = usage
452 469 else: self.usage = self.usage_min
453 470
454 471 # Storage
455 472 self.rc = rc # This will hold all configuration information
456 473 self.inputcache = []
457 474 self._boundcache = []
458 475 self.pager = 'less'
459 476 # temporary files used for various purposes. Deleted at exit.
460 477 self.tempfiles = []
461 478
462 479 # Keep track of readline usage (later set by init_readline)
463 480 self.has_readline = False
464 481
465 482 # for pushd/popd management
466 483 try:
467 484 self.home_dir = get_home_dir()
468 485 except HomeDirError,msg:
469 486 fatal(msg)
470 487
471 488 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
472 489
473 490 # Functions to call the underlying shell.
474 491
475 492 # utility to expand user variables via Itpl
476 493 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
477 494 self.user_ns))
478 495 # The first is similar to os.system, but it doesn't return a value,
479 496 # and it allows interpolation of variables in the user's namespace.
480 497 self.system = lambda cmd: shell(self.var_expand(cmd),
481 498 header='IPython system call: ',
482 499 verbose=self.rc.system_verbose)
483 500 # These are for getoutput and getoutputerror:
484 501 self.getoutput = lambda cmd: \
485 502 getoutput(self.var_expand(cmd),
486 503 header='IPython system call: ',
487 504 verbose=self.rc.system_verbose)
488 505 self.getoutputerror = lambda cmd: \
489 506 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
490 507 self.user_ns)),
491 508 header='IPython system call: ',
492 509 verbose=self.rc.system_verbose)
493 510
494 511 # RegExp for splitting line contents into pre-char//first
495 512 # word-method//rest. For clarity, each group in on one line.
496 513
497 514 # WARNING: update the regexp if the above escapes are changed, as they
498 515 # are hardwired in.
499 516
500 517 # Don't get carried away with trying to make the autocalling catch too
501 518 # much: it's better to be conservative rather than to trigger hidden
502 519 # evals() somewhere and end up causing side effects.
503 520
504 521 self.line_split = re.compile(r'^([\s*,;/])'
505 522 r'([\?\w\.]+\w*\s*)'
506 523 r'(\(?.*$)')
507 524
508 525 # Original re, keep around for a while in case changes break something
509 526 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
510 527 # r'(\s*[\?\w\.]+\w*\s*)'
511 528 # r'(\(?.*$)')
512 529
513 530 # RegExp to identify potential function names
514 531 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
515 532 # RegExp to exclude strings with this start from autocalling
516 533 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
517 534
518 535 # try to catch also methods for stuff in lists/tuples/dicts: off
519 536 # (experimental). For this to work, the line_split regexp would need
520 537 # to be modified so it wouldn't break things at '['. That line is
521 538 # nasty enough that I shouldn't change it until I can test it _well_.
522 539 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
523 540
524 541 # keep track of where we started running (mainly for crash post-mortem)
525 542 self.starting_dir = os.getcwd()
526 543
527 544 # Attributes for Logger mixin class, make defaults here
528 545 self._dolog = False
529 546 self.LOG = ''
530 547 self.LOGDEF = '.InteractiveShell.log'
531 548 self.LOGMODE = 'over'
532 549 self.LOGHEAD = Itpl(
533 550 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
534 551 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
535 552 #log# opts = $self.rc.opts
536 553 #log# args = $self.rc.args
537 554 #log# It is safe to make manual edits below here.
538 555 #log#-----------------------------------------------------------------------
539 556 """)
540 557 # Various switches which can be set
541 558 self.CACHELENGTH = 5000 # this is cheap, it's just text
542 559 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
543 560 self.banner2 = banner2
544 561
545 562 # TraceBack handlers:
546 563 # Need two, one for syntax errors and one for other exceptions.
547 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
548 # This one is initialized with an offset, meaning we always want to
549 # remove the topmost item in the traceback, which is our own internal
550 # code. Valid modes: ['Plain','Context','Verbose']
564 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
565 # The interactive one is initialized with an offset, meaning we always
566 # want to remove the topmost item in the traceback, which is our own
567 # internal code. Valid modes: ['Plain','Context','Verbose']
551 568 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
552 569 color_scheme='NoColor',
553 570 tb_offset = 1)
554 571 # and add any custom exception handlers the user may have specified
555 572 self.set_custom_exc(*custom_exceptions)
556 573
557 574 # Object inspector
558 575 self.inspector = OInspect.Inspector(OInspect.InspectColors,
559 576 PyColorize.ANSICodeColors,
560 577 'NoColor')
561 578 # indentation management
562 579 self.autoindent = False
563 580 self.indent_current_nsp = 0
564 581 self.indent_current = '' # actual indent string
565 582
566 583 # Make some aliases automatically
567 584 # Prepare list of shell aliases to auto-define
568 585 if os.name == 'posix':
569 586 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
570 587 'mv mv -i','rm rm -i','cp cp -i',
571 588 'cat cat','less less','clear clear',
572 589 # a better ls
573 590 'ls ls -F',
574 591 # long ls
575 592 'll ls -lF',
576 593 # color ls
577 594 'lc ls -F -o --color',
578 595 # ls normal files only
579 596 'lf ls -F -o --color %l | grep ^-',
580 597 # ls symbolic links
581 598 'lk ls -F -o --color %l | grep ^l',
582 599 # directories or links to directories,
583 600 'ldir ls -F -o --color %l | grep /$',
584 601 # things which are executable
585 602 'lx ls -F -o --color %l | grep ^-..x',
586 603 )
587 604 elif os.name in ['nt','dos']:
588 605 auto_alias = ('dir dir /on', 'ls dir /on',
589 606 'ddir dir /ad /on', 'ldir dir /ad /on',
590 607 'mkdir mkdir','rmdir rmdir','echo echo',
591 608 'ren ren','cls cls','copy copy')
592 609 else:
593 610 auto_alias = ()
594 611 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
595 612 # Call the actual (public) initializer
596 613 self.init_auto_alias()
597 614 # end __init__
598 615
599 616 def set_hook(self,name,hook):
600 617 """set_hook(name,hook) -> sets an internal IPython hook.
601 618
602 619 IPython exposes some of its internal API as user-modifiable hooks. By
603 620 resetting one of these hooks, you can modify IPython's behavior to
604 621 call at runtime your own routines."""
605 622
606 623 # At some point in the future, this should validate the hook before it
607 624 # accepts it. Probably at least check that the hook takes the number
608 625 # of args it's supposed to.
609 626 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
610 627
611 628 def set_custom_exc(self,exc_tuple,handler):
612 629 """set_custom_exc(exc_tuple,handler)
613 630
614 631 Set a custom exception handler, which will be called if any of the
615 632 exceptions in exc_tuple occur in the mainloop (specifically, in the
616 633 runcode() method.
617 634
618 635 Inputs:
619 636
620 637 - exc_tuple: a *tuple* of valid exceptions to call the defined
621 638 handler for. It is very important that you use a tuple, and NOT A
622 639 LIST here, because of the way Python's except statement works. If
623 640 you only want to trap a single exception, use a singleton tuple:
624 641
625 642 exc_tuple == (MyCustomException,)
626 643
627 644 - handler: this must be defined as a function with the following
628 645 basic interface: def my_handler(self,etype,value,tb).
629 646
630 647 This will be made into an instance method (via new.instancemethod)
631 648 of IPython itself, and it will be called if any of the exceptions
632 649 listed in the exc_tuple are caught. If the handler is None, an
633 650 internal basic one is used, which just prints basic info.
634 651
635 652 WARNING: by putting in your own exception handler into IPython's main
636 653 execution loop, you run a very good chance of nasty crashes. This
637 654 facility should only be used if you really know what you are doing."""
638 655
639 656 assert type(exc_tuple)==type(()) , \
640 657 "The custom exceptions must be given AS A TUPLE."
641 658
642 659 def dummy_handler(self,etype,value,tb):
643 660 print '*** Simple custom exception handler ***'
644 661 print 'Exception type :',etype
645 662 print 'Exception value:',value
646 663 print 'Traceback :',tb
647 664 print 'Source code :','\n'.join(self.buffer)
648 665
649 666 if handler is None: handler = dummy_handler
650 667
651 668 self.CustomTB = new.instancemethod(handler,self,self.__class__)
652 669 self.custom_exceptions = exc_tuple
653 670
654 671 def set_custom_completer(self,completer,pos=0):
655 672 """set_custom_completer(completer,pos=0)
656 673
657 674 Adds a new custom completer function.
658 675
659 676 The position argument (defaults to 0) is the index in the completers
660 677 list where you want the completer to be inserted."""
661 678
662 679 newcomp = new.instancemethod(completer,self.Completer,
663 680 self.Completer.__class__)
664 681 self.Completer.matchers.insert(pos,newcomp)
665 682
666 683 def complete(self,text):
667 684 """Return a sorted list of all possible completions on text.
668 685
669 686 Inputs:
670 687
671 688 - text: a string of text to be completed on.
672 689
673 690 This is a wrapper around the completion mechanism, similar to what
674 691 readline does at the command line when the TAB key is hit. By
675 692 exposing it as a method, it can be used by other non-readline
676 693 environments (such as GUIs) for text completion.
677 694
678 695 Simple usage example:
679 696
680 697 In [1]: x = 'hello'
681 698
682 699 In [2]: __IP.complete('x.l')
683 700 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
684 701
685 702 complete = self.Completer.complete
686 703 state = 0
687 704 # use a dict so we get unique keys, since ipyhton's multiple
688 705 # completers can return duplicates.
689 706 comps = {}
690 707 while True:
691 708 newcomp = complete(text,state)
692 709 if newcomp is None:
693 710 break
694 711 comps[newcomp] = 1
695 712 state += 1
696 713 outcomps = comps.keys()
697 714 outcomps.sort()
698 715 return outcomps
699 716
700 717 def set_completer_frame(self, frame):
701 718 if frame:
702 719 self.Completer.namespace = frame.f_locals
703 720 self.Completer.global_namespace = frame.f_globals
704 721 else:
705 722 self.Completer.namespace = self.user_ns
706 723 self.Completer.global_namespace = self.user_global_ns
707 724
708 725 def post_config_initialization(self):
709 726 """Post configuration init method
710 727
711 728 This is called after the configuration files have been processed to
712 729 'finalize' the initialization."""
713 730
714 731 rc = self.rc
715 732
716 733 # Load readline proper
717 734 if rc.readline:
718 735 self.init_readline()
719 736
720 737 # Set user colors (don't do it in the constructor above so that it
721 738 # doesn't crash if colors option is invalid)
722 739 self.magic_colors(rc.colors)
723 740
724 741 # Load user aliases
725 742 for alias in rc.alias:
726 743 self.magic_alias(alias)
727 744
728 745 # dynamic data that survives through sessions
729 746 # XXX make the filename a config option?
730 747 persist_base = 'persist'
731 748 if rc.profile:
732 749 persist_base += '_%s' % rc.profile
733 750 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
734 751
735 752 try:
736 753 self.persist = pickle.load(file(self.persist_fname))
737 754 except:
738 755 self.persist = {}
739 756
740 757 def init_auto_alias(self):
741 758 """Define some aliases automatically.
742 759
743 760 These are ALL parameter-less aliases"""
744 761 for alias,cmd in self.auto_alias:
745 762 self.alias_table[alias] = (0,cmd)
746 763
747 764 def alias_table_validate(self,verbose=0):
748 765 """Update information about the alias table.
749 766
750 767 In particular, make sure no Python keywords/builtins are in it."""
751 768
752 769 no_alias = self.no_alias
753 770 for k in self.alias_table.keys():
754 771 if k in no_alias:
755 772 del self.alias_table[k]
756 773 if verbose:
757 774 print ("Deleting alias <%s>, it's a Python "
758 775 "keyword or builtin." % k)
759 776
760 777 def set_autoindent(self,value=None):
761 778 """Set the autoindent flag, checking for readline support.
762 779
763 780 If called with no arguments, it acts as a toggle."""
764 781
765 782 if not self.has_readline:
766 783 if os.name == 'posix':
767 784 warn("The auto-indent feature requires the readline library")
768 785 self.autoindent = 0
769 786 return
770 787 if value is None:
771 788 self.autoindent = not self.autoindent
772 789 else:
773 790 self.autoindent = value
774 791
775 792 def rc_set_toggle(self,rc_field,value=None):
776 793 """Set or toggle a field in IPython's rc config. structure.
777 794
778 795 If called with no arguments, it acts as a toggle.
779 796
780 797 If called with a non-existent field, the resulting AttributeError
781 798 exception will propagate out."""
782 799
783 800 rc_val = getattr(self.rc,rc_field)
784 801 if value is None:
785 802 value = not rc_val
786 803 setattr(self.rc,rc_field,value)
787 804
788 805 def user_setup(self,ipythondir,rc_suffix,mode='install'):
789 806 """Install the user configuration directory.
790 807
791 808 Can be called when running for the first time or to upgrade the user's
792 809 .ipython/ directory with the mode parameter. Valid modes are 'install'
793 810 and 'upgrade'."""
794 811
795 812 def wait():
796 813 try:
797 814 raw_input("Please press <RETURN> to start IPython.")
798 815 except EOFError:
799 816 print >> Term.cout
800 817 print '*'*70
801 818
802 819 cwd = os.getcwd() # remember where we started
803 820 glb = glob.glob
804 821 print '*'*70
805 822 if mode == 'install':
806 823 print \
807 824 """Welcome to IPython. I will try to create a personal configuration directory
808 825 where you can customize many aspects of IPython's functionality in:\n"""
809 826 else:
810 827 print 'I am going to upgrade your configuration in:'
811 828
812 829 print ipythondir
813 830
814 831 rcdirend = os.path.join('IPython','UserConfig')
815 832 cfg = lambda d: os.path.join(d,rcdirend)
816 833 try:
817 834 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
818 835 except IOError:
819 836 warning = """
820 837 Installation error. IPython's directory was not found.
821 838
822 839 Check the following:
823 840
824 841 The ipython/IPython directory should be in a directory belonging to your
825 842 PYTHONPATH environment variable (that is, it should be in a directory
826 843 belonging to sys.path). You can copy it explicitly there or just link to it.
827 844
828 845 IPython will proceed with builtin defaults.
829 846 """
830 847 warn(warning)
831 848 wait()
832 849 return
833 850
834 851 if mode == 'install':
835 852 try:
836 853 shutil.copytree(rcdir,ipythondir)
837 854 os.chdir(ipythondir)
838 855 rc_files = glb("ipythonrc*")
839 856 for rc_file in rc_files:
840 857 os.rename(rc_file,rc_file+rc_suffix)
841 858 except:
842 859 warning = """
843 860
844 861 There was a problem with the installation:
845 862 %s
846 863 Try to correct it or contact the developers if you think it's a bug.
847 864 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
848 865 warn(warning)
849 866 wait()
850 867 return
851 868
852 869 elif mode == 'upgrade':
853 870 try:
854 871 os.chdir(ipythondir)
855 872 except:
856 873 print """
857 874 Can not upgrade: changing to directory %s failed. Details:
858 875 %s
859 876 """ % (ipythondir,sys.exc_info()[1])
860 877 wait()
861 878 return
862 879 else:
863 880 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
864 881 for new_full_path in sources:
865 882 new_filename = os.path.basename(new_full_path)
866 883 if new_filename.startswith('ipythonrc'):
867 884 new_filename = new_filename + rc_suffix
868 885 # The config directory should only contain files, skip any
869 886 # directories which may be there (like CVS)
870 887 if os.path.isdir(new_full_path):
871 888 continue
872 889 if os.path.exists(new_filename):
873 890 old_file = new_filename+'.old'
874 891 if os.path.exists(old_file):
875 892 os.remove(old_file)
876 893 os.rename(new_filename,old_file)
877 894 shutil.copy(new_full_path,new_filename)
878 895 else:
879 896 raise ValueError,'unrecognized mode for install:',`mode`
880 897
881 898 # Fix line-endings to those native to each platform in the config
882 899 # directory.
883 900 try:
884 901 os.chdir(ipythondir)
885 902 except:
886 903 print """
887 904 Problem: changing to directory %s failed.
888 905 Details:
889 906 %s
890 907
891 908 Some configuration files may have incorrect line endings. This should not
892 909 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
893 910 wait()
894 911 else:
895 912 for fname in glb('ipythonrc*'):
896 913 try:
897 914 native_line_ends(fname,backup=0)
898 915 except IOError:
899 916 pass
900 917
901 918 if mode == 'install':
902 919 print """
903 920 Successful installation!
904 921
905 922 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
906 923 IPython manual (there are both HTML and PDF versions supplied with the
907 924 distribution) to make sure that your system environment is properly configured
908 925 to take advantage of IPython's features."""
909 926 else:
910 927 print """
911 928 Successful upgrade!
912 929
913 930 All files in your directory:
914 931 %(ipythondir)s
915 932 which would have been overwritten by the upgrade were backed up with a .old
916 933 extension. If you had made particular customizations in those files you may
917 934 want to merge them back into the new files.""" % locals()
918 935 wait()
919 936 os.chdir(cwd)
920 937 # end user_setup()
921 938
922 939 def atexit_operations(self):
923 940 """This will be executed at the time of exit.
924 941
925 942 Saving of persistent data should be performed here. """
926 943
927 944 # input history
928 945 self.savehist()
929 946
930 947 # Cleanup all tempfiles left around
931 948 for tfile in self.tempfiles:
932 949 try:
933 950 os.unlink(tfile)
934 951 except OSError:
935 952 pass
936 953
937 954 # save the "persistent data" catch-all dictionary
938 955 try:
939 956 pickle.dump(self.persist, open(self.persist_fname,"w"))
940 957 except:
941 958 print "*** ERROR *** persistent data saving failed."
942 959
943 960 def savehist(self):
944 961 """Save input history to a file (via readline library)."""
945 962 try:
946 963 self.readline.write_history_file(self.histfile)
947 964 except:
948 965 print 'Unable to save IPython command history to file: ' + \
949 966 `self.histfile`
950 967
951 968 def pre_readline(self):
952 969 """readline hook to be used at the start of each line.
953 970
954 971 Currently it handles auto-indent only."""
955 972
956 973 self.readline.insert_text(self.indent_current)
957 974
958 975 def init_readline(self):
959 976 """Command history completion/saving/reloading."""
960 977 try:
961 978 import readline
962 979 except ImportError:
963 980 self.has_readline = 0
964 981 self.readline = None
965 982 # no point in bugging windows users with this every time:
966 983 if os.name == 'posix':
967 984 warn('Readline services not available on this platform.')
968 985 else:
969 986 import atexit
970 987 from IPython.completer import IPCompleter
971 988 self.Completer = IPCompleter(self,
972 989 self.user_ns,
973 990 self.user_global_ns,
974 991 self.rc.readline_omit__names,
975 992 self.alias_table)
976 993
977 994 # Platform-specific configuration
978 995 if os.name == 'nt':
979 996 self.readline_startup_hook = readline.set_pre_input_hook
980 997 else:
981 998 self.readline_startup_hook = readline.set_startup_hook
982 999
983 1000 # Load user's initrc file (readline config)
984 1001 inputrc_name = os.environ.get('INPUTRC')
985 1002 if inputrc_name is None:
986 1003 home_dir = get_home_dir()
987 1004 if home_dir is not None:
988 1005 inputrc_name = os.path.join(home_dir,'.inputrc')
989 1006 if os.path.isfile(inputrc_name):
990 1007 try:
991 1008 readline.read_init_file(inputrc_name)
992 1009 except:
993 1010 warn('Problems reading readline initialization file <%s>'
994 1011 % inputrc_name)
995 1012
996 1013 self.has_readline = 1
997 1014 self.readline = readline
998 1015 # save this in sys so embedded copies can restore it properly
999 1016 sys.ipcompleter = self.Completer.complete
1000 1017 readline.set_completer(self.Completer.complete)
1001 1018
1002 1019 # Configure readline according to user's prefs
1003 1020 for rlcommand in self.rc.readline_parse_and_bind:
1004 1021 readline.parse_and_bind(rlcommand)
1005 1022
1006 1023 # remove some chars from the delimiters list
1007 1024 delims = readline.get_completer_delims()
1008 1025 delims = delims.translate(string._idmap,
1009 1026 self.rc.readline_remove_delims)
1010 1027 readline.set_completer_delims(delims)
1011 1028 # otherwise we end up with a monster history after a while:
1012 1029 readline.set_history_length(1000)
1013 1030 try:
1014 1031 #print '*** Reading readline history' # dbg
1015 1032 readline.read_history_file(self.histfile)
1016 1033 except IOError:
1017 1034 pass # It doesn't exist yet.
1018 1035
1019 1036 atexit.register(self.atexit_operations)
1020 1037 del atexit
1021 1038
1022 1039 # Configure auto-indent for all platforms
1023 1040 self.set_autoindent(self.rc.autoindent)
1024 1041
1042 def _should_recompile(self,e):
1043 """Utility routine for edit_syntax_error"""
1044
1045 if e.filename in ('<ipython console>','<input>','<string>',
1046 '<console>'):
1047 return False
1048 try:
1049 if not ask_yes_no('Return to editor to correct syntax error? '
1050 '[Y/n] ','y'):
1051 return False
1052 except EOFError:
1053 return False
1054 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1055 return True
1056
1057 def edit_syntax_error(self):
1058 """The bottom half of the syntax error handler called in the main loop.
1059
1060 Loop until syntax error is fixed or user cancels.
1061 """
1062
1063 while self.SyntaxTB.last_syntax_error:
1064 # copy and clear last_syntax_error
1065 err = self.SyntaxTB.clear_err_state()
1066 if not self._should_recompile(err):
1067 return
1068 try:
1069 # may set last_syntax_error again if a SyntaxError is raised
1070 self.safe_execfile(err.filename,self.shell.user_ns)
1071 except:
1072 self.showtraceback()
1073 else:
1074 f = file(err.filename)
1075 try:
1076 sys.displayhook(f.read())
1077 finally:
1078 f.close()
1079
1025 1080 def showsyntaxerror(self, filename=None):
1026 1081 """Display the syntax error that just occurred.
1027 1082
1028 1083 This doesn't display a stack trace because there isn't one.
1029 1084
1030 1085 If a filename is given, it is stuffed in the exception instead
1031 1086 of what was there before (because Python's parser always uses
1032 1087 "<string>" when reading from a string).
1033 1088 """
1034 1089 type, value, sys.last_traceback = sys.exc_info()
1035 1090 sys.last_type = type
1036 1091 sys.last_value = value
1037 1092 if filename and type is SyntaxError:
1038 1093 # Work hard to stuff the correct filename in the exception
1039 1094 try:
1040 1095 msg, (dummy_filename, lineno, offset, line) = value
1041 1096 except:
1042 1097 # Not the format we expect; leave it alone
1043 1098 pass
1044 1099 else:
1045 1100 # Stuff in the right filename
1046 1101 try:
1047 1102 # Assume SyntaxError is a class exception
1048 1103 value = SyntaxError(msg, (filename, lineno, offset, line))
1049 1104 except:
1050 1105 # If that failed, assume SyntaxError is a string
1051 1106 value = msg, (filename, lineno, offset, line)
1052 1107 self.SyntaxTB(type,value,[])
1053 1108
1054 1109 def debugger(self):
1055 1110 """Call the pdb debugger."""
1056 1111
1057 1112 if not self.rc.pdb:
1058 1113 return
1059 1114 pdb.pm()
1060 1115
1061 1116 def showtraceback(self,exc_tuple = None,filename=None):
1062 1117 """Display the exception that just occurred."""
1063 1118
1064 1119 # Though this won't be called by syntax errors in the input line,
1065 1120 # there may be SyntaxError cases whith imported code.
1066 1121 if exc_tuple is None:
1067 1122 type, value, tb = sys.exc_info()
1068 1123 else:
1069 1124 type, value, tb = exc_tuple
1070 1125 if type is SyntaxError:
1071 1126 self.showsyntaxerror(filename)
1072 1127 else:
1073 1128 sys.last_type = type
1074 1129 sys.last_value = value
1075 1130 sys.last_traceback = tb
1076 1131 self.InteractiveTB()
1077 1132 if self.InteractiveTB.call_pdb and self.has_readline:
1078 1133 # pdb mucks up readline, fix it back
1079 1134 self.readline.set_completer(self.Completer.complete)
1080 1135
1081 1136 def update_cache(self, line):
1082 1137 """puts line into cache"""
1083 1138 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1084 1139 if len(self.inputcache) >= self.CACHELENGTH:
1085 1140 self.inputcache.pop() # This doesn't :-)
1086 1141
1087 1142 def mainloop(self,banner=None):
1088 1143 """Creates the local namespace and starts the mainloop.
1089 1144
1090 1145 If an optional banner argument is given, it will override the
1091 1146 internally created default banner."""
1092 1147
1093 1148 if self.rc.c: # Emulate Python's -c option
1094 1149 self.exec_init_cmd()
1095 1150 if banner is None:
1096 1151 if self.rc.banner:
1097 1152 banner = self.BANNER+self.banner2
1098 1153 else:
1099 1154 banner = ''
1100 1155 self.interact(banner)
1101 1156
1102 1157 def exec_init_cmd(self):
1103 1158 """Execute a command given at the command line.
1104 1159
1105 1160 This emulates Python's -c option."""
1106 1161
1107 1162 sys.argv = ['-c']
1108 1163 self.push(self.rc.c)
1109 1164
1110 1165 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1111 1166 """Embeds IPython into a running python program.
1112 1167
1113 1168 Input:
1114 1169
1115 1170 - header: An optional header message can be specified.
1116 1171
1117 1172 - local_ns, global_ns: working namespaces. If given as None, the
1118 1173 IPython-initialized one is updated with __main__.__dict__, so that
1119 1174 program variables become visible but user-specific configuration
1120 1175 remains possible.
1121 1176
1122 1177 - stack_depth: specifies how many levels in the stack to go to
1123 1178 looking for namespaces (when local_ns and global_ns are None). This
1124 1179 allows an intermediate caller to make sure that this function gets
1125 1180 the namespace from the intended level in the stack. By default (0)
1126 1181 it will get its locals and globals from the immediate caller.
1127 1182
1128 1183 Warning: it's possible to use this in a program which is being run by
1129 1184 IPython itself (via %run), but some funny things will happen (a few
1130 1185 globals get overwritten). In the future this will be cleaned up, as
1131 1186 there is no fundamental reason why it can't work perfectly."""
1132 1187
1133 1188 # Get locals and globals from caller
1134 1189 if local_ns is None or global_ns is None:
1135 1190 call_frame = sys._getframe(stack_depth).f_back
1136 1191
1137 1192 if local_ns is None:
1138 1193 local_ns = call_frame.f_locals
1139 1194 if global_ns is None:
1140 1195 global_ns = call_frame.f_globals
1141 1196
1142 1197 # Update namespaces and fire up interpreter
1143 1198 self.user_ns = local_ns
1144 1199 self.user_global_ns = global_ns
1145 1200
1146 1201 # Patch for global embedding to make sure that things don't overwrite
1147 1202 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1148 1203 # FIXME. Test this a bit more carefully (the if.. is new)
1149 1204 if local_ns is None and global_ns is None:
1150 1205 self.user_global_ns.update(__main__.__dict__)
1151 1206
1152 1207 # make sure the tab-completer has the correct frame information, so it
1153 1208 # actually completes using the frame's locals/globals
1154 1209 self.set_completer_frame(call_frame)
1155 1210
1156 1211 self.interact(header)
1157 1212
1158 1213 def interact(self, banner=None):
1159 1214 """Closely emulate the interactive Python console.
1160 1215
1161 1216 The optional banner argument specify the banner to print
1162 1217 before the first interaction; by default it prints a banner
1163 1218 similar to the one printed by the real Python interpreter,
1164 1219 followed by the current class name in parentheses (so as not
1165 1220 to confuse this with the real interpreter -- since it's so
1166 1221 close!).
1167 1222
1168 1223 """
1169 1224 cprt = 'Type "copyright", "credits" or "license" for more information.'
1170 1225 if banner is None:
1171 1226 self.write("Python %s on %s\n%s\n(%s)\n" %
1172 1227 (sys.version, sys.platform, cprt,
1173 1228 self.__class__.__name__))
1174 1229 else:
1175 1230 self.write(banner)
1176 1231
1177 1232 more = 0
1178 1233
1179 1234 # Mark activity in the builtins
1180 1235 __builtin__.__dict__['__IPYTHON__active'] += 1
1181 1236
1182 1237 # compiled regexps for autoindent management
1183 1238 ini_spaces_re = re.compile(r'^(\s+)')
1184 1239 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
1185 1240
1186 1241 # exit_now is set by a call to %Exit or %Quit
1187 1242 while not self.exit_now:
1188 1243 try:
1189 1244 if more:
1190 1245 prompt = self.outputcache.prompt2
1191 1246 if self.autoindent:
1192 1247 self.readline_startup_hook(self.pre_readline)
1193 1248 else:
1194 1249 prompt = self.outputcache.prompt1
1195 1250 try:
1196 1251 line = self.raw_input(prompt,more)
1197 1252 if self.autoindent:
1198 1253 self.readline_startup_hook(None)
1199 1254 except EOFError:
1200 1255 if self.autoindent:
1201 1256 self.readline_startup_hook(None)
1202 1257 self.write("\n")
1203 1258 self.exit()
1204 1259 except IPythonExit:
1205 1260 self.exit()
1206 1261 else:
1207 1262 more = self.push(line)
1208 1263 # Auto-indent management
1209 1264 if self.autoindent:
1210 1265 if line:
1211 1266 ini_spaces = ini_spaces_re.match(line)
1212 1267 if ini_spaces:
1213 1268 nspaces = ini_spaces.end()
1214 1269 else:
1215 1270 nspaces = 0
1216 1271 self.indent_current_nsp = nspaces
1217 1272
1218 1273 if line[-1] == ':':
1219 1274 self.indent_current_nsp += 4
1220 1275 elif dedent_re.match(line):
1221 1276 self.indent_current_nsp -= 4
1222 1277 else:
1223 1278 self.indent_current_nsp = 0
1279
1224 1280 # indent_current is the actual string to be inserted
1225 1281 # by the readline hooks for indentation
1226 1282 self.indent_current = ' '* self.indent_current_nsp
1227 1283
1284 if (self.SyntaxTB.last_syntax_error and
1285 self.rc.autoedit_syntax):
1286 self.edit_syntax_error()
1287
1228 1288 except KeyboardInterrupt:
1229 1289 self.write("\nKeyboardInterrupt\n")
1230 1290 self.resetbuffer()
1231 1291 more = 0
1232 1292 # keep cache in sync with the prompt counter:
1233 1293 self.outputcache.prompt_count -= 1
1234 1294
1235 1295 if self.autoindent:
1236 1296 self.indent_current_nsp = 0
1237 1297 self.indent_current = ' '* self.indent_current_nsp
1238 1298
1239 1299 except bdb.BdbQuit:
1240 1300 warn("The Python debugger has exited with a BdbQuit exception.\n"
1241 1301 "Because of how pdb handles the stack, it is impossible\n"
1242 1302 "for IPython to properly format this particular exception.\n"
1243 1303 "IPython will resume normal operation.")
1244 1304
1245 1305 # We are off again...
1246 1306 __builtin__.__dict__['__IPYTHON__active'] -= 1
1247 1307
1248 1308 def excepthook(self, type, value, tb):
1249 1309 """One more defense for GUI apps that call sys.excepthook.
1250 1310
1251 1311 GUI frameworks like wxPython trap exceptions and call
1252 1312 sys.excepthook themselves. I guess this is a feature that
1253 1313 enables them to keep running after exceptions that would
1254 1314 otherwise kill their mainloop. This is a bother for IPython
1255 1315 which excepts to catch all of the program exceptions with a try:
1256 1316 except: statement.
1257 1317
1258 1318 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1259 1319 any app directly invokes sys.excepthook, it will look to the user like
1260 1320 IPython crashed. In order to work around this, we can disable the
1261 1321 CrashHandler and replace it with this excepthook instead, which prints a
1262 1322 regular traceback using our InteractiveTB. In this fashion, apps which
1263 1323 call sys.excepthook will generate a regular-looking exception from
1264 1324 IPython, and the CrashHandler will only be triggered by real IPython
1265 1325 crashes.
1266 1326
1267 1327 This hook should be used sparingly, only in places which are not likely
1268 1328 to be true IPython errors.
1269 1329 """
1270 1330
1271 1331 self.InteractiveTB(type, value, tb, tb_offset=0)
1272 1332 if self.InteractiveTB.call_pdb and self.has_readline:
1273 1333 self.readline.set_completer(self.Completer.complete)
1274 1334
1275 1335 def call_alias(self,alias,rest=''):
1276 1336 """Call an alias given its name and the rest of the line.
1277 1337
1278 1338 This function MUST be given a proper alias, because it doesn't make
1279 1339 any checks when looking up into the alias table. The caller is
1280 1340 responsible for invoking it only with a valid alias."""
1281 1341
1282 1342 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1283 1343 nargs,cmd = self.alias_table[alias]
1284 1344 # Expand the %l special to be the user's input line
1285 1345 if cmd.find('%l') >= 0:
1286 1346 cmd = cmd.replace('%l',rest)
1287 1347 rest = ''
1288 1348 if nargs==0:
1289 1349 # Simple, argument-less aliases
1290 1350 cmd = '%s %s' % (cmd,rest)
1291 1351 else:
1292 1352 # Handle aliases with positional arguments
1293 1353 args = rest.split(None,nargs)
1294 1354 if len(args)< nargs:
1295 1355 error('Alias <%s> requires %s arguments, %s given.' %
1296 1356 (alias,nargs,len(args)))
1297 1357 return
1298 1358 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1299 1359 # Now call the macro, evaluating in the user's namespace
1300 1360 try:
1301 1361 self.system(cmd)
1302 1362 except:
1303 1363 self.showtraceback()
1304 1364
1305 1365 def runlines(self,lines):
1306 1366 """Run a string of one or more lines of source.
1307 1367
1308 1368 This method is capable of running a string containing multiple source
1309 1369 lines, as if they had been entered at the IPython prompt. Since it
1310 1370 exposes IPython's processing machinery, the given strings can contain
1311 1371 magic calls (%magic), special shell access (!cmd), etc."""
1312 1372
1313 1373 # We must start with a clean buffer, in case this is run from an
1314 1374 # interactive IPython session (via a magic, for example).
1315 1375 self.resetbuffer()
1316 1376 lines = lines.split('\n')
1317 1377 more = 0
1318 1378 for line in lines:
1319 1379 # skip blank lines so we don't mess up the prompt counter, but do
1320 1380 # NOT skip even a blank line if we are in a code block (more is
1321 1381 # true)
1322 1382 if line or more:
1323 1383 more = self.push((self.prefilter(line,more)))
1324 1384 # IPython's runsource returns None if there was an error
1325 1385 # compiling the code. This allows us to stop processing right
1326 1386 # away, so the user gets the error message at the right place.
1327 1387 if more is None:
1328 1388 break
1329 1389 # final newline in case the input didn't have it, so that the code
1330 1390 # actually does get executed
1331 1391 if more:
1332 1392 self.push('\n')
1333 1393
1334 1394 def runsource(self, source, filename='<input>', symbol='single'):
1335 1395 """Compile and run some source in the interpreter.
1336 1396
1337 1397 Arguments are as for compile_command().
1338 1398
1339 1399 One several things can happen:
1340 1400
1341 1401 1) The input is incorrect; compile_command() raised an
1342 1402 exception (SyntaxError or OverflowError). A syntax traceback
1343 1403 will be printed by calling the showsyntaxerror() method.
1344 1404
1345 1405 2) The input is incomplete, and more input is required;
1346 1406 compile_command() returned None. Nothing happens.
1347 1407
1348 1408 3) The input is complete; compile_command() returned a code
1349 1409 object. The code is executed by calling self.runcode() (which
1350 1410 also handles run-time exceptions, except for SystemExit).
1351 1411
1352 1412 The return value is:
1353 1413
1354 1414 - True in case 2
1355 1415
1356 1416 - False in the other cases, unless an exception is raised, where
1357 1417 None is returned instead. This can be used by external callers to
1358 1418 know whether to continue feeding input or not.
1359 1419
1360 1420 The return value can be used to decide whether to use sys.ps1 or
1361 1421 sys.ps2 to prompt the next line."""
1362 1422
1363 1423 try:
1364 1424 code = self.compile(source,filename,symbol)
1365 1425 except (OverflowError, SyntaxError, ValueError):
1366 1426 # Case 1
1367 1427 self.showsyntaxerror(filename)
1368 1428 return None
1369 1429
1370 1430 if code is None:
1371 1431 # Case 2
1372 1432 return True
1373 1433
1374 1434 # Case 3
1375 1435 # We store the code object so that threaded shells and
1376 1436 # custom exception handlers can access all this info if needed.
1377 1437 # The source corresponding to this can be obtained from the
1378 1438 # buffer attribute as '\n'.join(self.buffer).
1379 1439 self.code_to_run = code
1380 1440 # now actually execute the code object
1381 1441 if self.runcode(code) == 0:
1382 1442 return False
1383 1443 else:
1384 1444 return None
1385 1445
1386 1446 def runcode(self,code_obj):
1387 1447 """Execute a code object.
1388 1448
1389 1449 When an exception occurs, self.showtraceback() is called to display a
1390 1450 traceback.
1391 1451
1392 1452 Return value: a flag indicating whether the code to be run completed
1393 1453 successfully:
1394 1454
1395 1455 - 0: successful execution.
1396 1456 - 1: an error occurred.
1397 1457 """
1398 1458
1399 1459 # Set our own excepthook in case the user code tries to call it
1400 1460 # directly, so that the IPython crash handler doesn't get triggered
1401 1461 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1402 1462 outflag = 1 # happens in more places, so it's easier as default
1403 1463 try:
1404 1464 try:
1405 1465 # Embedded instances require separate global/local namespaces
1406 1466 # so they can see both the surrounding (local) namespace and
1407 1467 # the module-level globals when called inside another function.
1408 1468 if self.embedded:
1409 1469 exec code_obj in self.user_global_ns, self.user_ns
1410 1470 # Normal (non-embedded) instances should only have a single
1411 1471 # namespace for user code execution, otherwise functions won't
1412 1472 # see interactive top-level globals.
1413 1473 else:
1414 1474 exec code_obj in self.user_ns
1415 1475 finally:
1416 1476 # Reset our crash handler in place
1417 1477 sys.excepthook = old_excepthook
1418 1478 except SystemExit:
1419 1479 self.resetbuffer()
1420 1480 self.showtraceback()
1421 1481 warn("Type exit or quit to exit IPython "
1422 1482 "(%Exit or %Quit do so unconditionally).",level=1)
1423 1483 except self.custom_exceptions:
1424 1484 etype,value,tb = sys.exc_info()
1425 1485 self.CustomTB(etype,value,tb)
1426 1486 except:
1427 1487 self.showtraceback()
1428 1488 else:
1429 1489 outflag = 0
1430 1490 if softspace(sys.stdout, 0):
1431 1491 print
1432 1492 # Flush out code object which has been run (and source)
1433 1493 self.code_to_run = None
1434 1494 return outflag
1435 1495
1436 1496 def push(self, line):
1437 1497 """Push a line to the interpreter.
1438 1498
1439 1499 The line should not have a trailing newline; it may have
1440 1500 internal newlines. The line is appended to a buffer and the
1441 1501 interpreter's runsource() method is called with the
1442 1502 concatenated contents of the buffer as source. If this
1443 1503 indicates that the command was executed or invalid, the buffer
1444 1504 is reset; otherwise, the command is incomplete, and the buffer
1445 1505 is left as it was after the line was appended. The return
1446 1506 value is 1 if more input is required, 0 if the line was dealt
1447 1507 with in some way (this is the same as runsource()).
1448 1508
1449 1509 """
1450 1510 self.buffer.append(line)
1451 1511 more = self.runsource('\n'.join(self.buffer), self.filename)
1452 1512 if not more:
1453 1513 self.resetbuffer()
1454 1514 return more
1455 1515
1456 1516 def resetbuffer(self):
1457 1517 """Reset the input buffer."""
1458 1518 self.buffer[:] = []
1459 1519
1460 1520 def raw_input(self,prompt='',continue_prompt=False):
1461 1521 """Write a prompt and read a line.
1462 1522
1463 1523 The returned line does not include the trailing newline.
1464 1524 When the user enters the EOF key sequence, EOFError is raised.
1465 1525
1466 1526 Optional inputs:
1467 1527
1468 1528 - prompt(''): a string to be printed to prompt the user.
1469 1529
1470 1530 - continue_prompt(False): whether this line is the first one or a
1471 1531 continuation in a sequence of inputs.
1472 1532 """
1473 1533
1474 1534 line = raw_input_original(prompt)
1475 1535 # Try to be reasonably smart about not re-indenting pasted input more
1476 1536 # than necessary. We do this by trimming out the auto-indent initial
1477 1537 # spaces, if the user's actual input started itself with whitespace.
1478 1538 if self.autoindent:
1479 1539 line2 = line[self.indent_current_nsp:]
1480 1540 if line2[0:1] in (' ','\t'):
1481 1541 line = line2
1482 1542 return self.prefilter(line,continue_prompt)
1483 1543
1484 1544 def split_user_input(self,line):
1485 1545 """Split user input into pre-char, function part and rest."""
1486 1546
1487 1547 lsplit = self.line_split.match(line)
1488 1548 if lsplit is None: # no regexp match returns None
1489 1549 try:
1490 1550 iFun,theRest = line.split(None,1)
1491 1551 except ValueError:
1492 1552 iFun,theRest = line,''
1493 1553 pre = re.match('^(\s*)(.*)',line).groups()[0]
1494 1554 else:
1495 1555 pre,iFun,theRest = lsplit.groups()
1496 1556
1497 1557 #print 'line:<%s>' % line # dbg
1498 1558 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1499 1559 return pre,iFun.strip(),theRest
1500 1560
1501 1561 def _prefilter(self, line, continue_prompt):
1502 1562 """Calls different preprocessors, depending on the form of line."""
1503 1563
1504 1564 # All handlers *must* return a value, even if it's blank ('').
1505 1565
1506 1566 # Lines are NOT logged here. Handlers should process the line as
1507 1567 # needed, update the cache AND log it (so that the input cache array
1508 1568 # stays synced).
1509 1569
1510 1570 # This function is _very_ delicate, and since it's also the one which
1511 1571 # determines IPython's response to user input, it must be as efficient
1512 1572 # as possible. For this reason it has _many_ returns in it, trying
1513 1573 # always to exit as quickly as it can figure out what it needs to do.
1514 1574
1515 1575 # This function is the main responsible for maintaining IPython's
1516 1576 # behavior respectful of Python's semantics. So be _very_ careful if
1517 1577 # making changes to anything here.
1518 1578
1519 1579 #.....................................................................
1520 1580 # Code begins
1521 1581
1522 1582 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1523 1583
1524 1584 # save the line away in case we crash, so the post-mortem handler can
1525 1585 # record it
1526 1586 self._last_input_line = line
1527 1587
1528 1588 #print '***line: <%s>' % line # dbg
1529 1589
1530 1590 # the input history needs to track even empty lines
1531 1591 if not line.strip():
1532 1592 if not continue_prompt:
1533 1593 self.outputcache.prompt_count -= 1
1534 1594 return self.handle_normal(line,continue_prompt)
1535 1595 #return self.handle_normal('',continue_prompt)
1536 1596
1537 1597 # print '***cont',continue_prompt # dbg
1538 1598 # special handlers are only allowed for single line statements
1539 1599 if continue_prompt and not self.rc.multi_line_specials:
1540 1600 return self.handle_normal(line,continue_prompt)
1541 1601
1542 1602 # For the rest, we need the structure of the input
1543 1603 pre,iFun,theRest = self.split_user_input(line)
1544 1604 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1545 1605
1546 1606 # First check for explicit escapes in the last/first character
1547 1607 handler = None
1548 1608 if line[-1] == self.ESC_HELP:
1549 1609 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1550 1610 if handler is None:
1551 1611 # look at the first character of iFun, NOT of line, so we skip
1552 1612 # leading whitespace in multiline input
1553 1613 handler = self.esc_handlers.get(iFun[0:1])
1554 1614 if handler is not None:
1555 1615 return handler(line,continue_prompt,pre,iFun,theRest)
1556 1616 # Emacs ipython-mode tags certain input lines
1557 1617 if line.endswith('# PYTHON-MODE'):
1558 1618 return self.handle_emacs(line,continue_prompt)
1559 1619
1560 1620 # Next, check if we can automatically execute this thing
1561 1621
1562 1622 # Allow ! in multi-line statements if multi_line_specials is on:
1563 1623 if continue_prompt and self.rc.multi_line_specials and \
1564 1624 iFun.startswith(self.ESC_SHELL):
1565 1625 return self.handle_shell_escape(line,continue_prompt,
1566 1626 pre=pre,iFun=iFun,
1567 1627 theRest=theRest)
1568 1628
1569 1629 # Let's try to find if the input line is a magic fn
1570 1630 oinfo = None
1571 1631 if hasattr(self,'magic_'+iFun):
1572 1632 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1573 1633 if oinfo['ismagic']:
1574 1634 # Be careful not to call magics when a variable assignment is
1575 1635 # being made (ls='hi', for example)
1576 1636 if self.rc.automagic and \
1577 1637 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1578 1638 (self.rc.multi_line_specials or not continue_prompt):
1579 1639 return self.handle_magic(line,continue_prompt,
1580 1640 pre,iFun,theRest)
1581 1641 else:
1582 1642 return self.handle_normal(line,continue_prompt)
1583 1643
1584 1644 # If the rest of the line begins with an (in)equality, assginment or
1585 1645 # function call, we should not call _ofind but simply execute it.
1586 1646 # This avoids spurious geattr() accesses on objects upon assignment.
1587 1647 #
1588 1648 # It also allows users to assign to either alias or magic names true
1589 1649 # python variables (the magic/alias systems always take second seat to
1590 1650 # true python code).
1591 1651 if theRest and theRest[0] in '!=()':
1592 1652 return self.handle_normal(line,continue_prompt)
1593 1653
1594 1654 if oinfo is None:
1595 1655 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1596 1656
1597 1657 if not oinfo['found']:
1598 1658 if iFun in ('quit','exit'):
1599 1659 raise IPythonExit
1600 1660 return self.handle_normal(line,continue_prompt)
1601 1661 else:
1602 1662 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1603 1663 if oinfo['isalias']:
1604 1664 return self.handle_alias(line,continue_prompt,
1605 1665 pre,iFun,theRest)
1606 1666
1607 1667 if self.rc.autocall and \
1608 1668 not self.re_exclude_auto.match(theRest) and \
1609 1669 self.re_fun_name.match(iFun) and \
1610 1670 callable(oinfo['obj']) :
1611 1671 #print 'going auto' # dbg
1612 1672 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1613 1673 else:
1614 1674 #print 'was callable?', callable(oinfo['obj']) # dbg
1615 1675 return self.handle_normal(line,continue_prompt)
1616 1676
1617 1677 # If we get here, we have a normal Python line. Log and return.
1618 1678 return self.handle_normal(line,continue_prompt)
1619 1679
1620 1680 def _prefilter_dumb(self, line, continue_prompt):
1621 1681 """simple prefilter function, for debugging"""
1622 1682 return self.handle_normal(line,continue_prompt)
1623 1683
1624 1684 # Set the default prefilter() function (this can be user-overridden)
1625 1685 prefilter = _prefilter
1626 1686
1627 1687 def handle_normal(self,line,continue_prompt=None,
1628 1688 pre=None,iFun=None,theRest=None):
1629 1689 """Handle normal input lines. Use as a template for handlers."""
1630 1690
1631 1691 # With autoindent on, we need some way to exit the input loop, and I
1632 1692 # don't want to force the user to have to backspace all the way to
1633 1693 # clear the line. The rule will be in this case, that either two
1634 1694 # lines of pure whitespace in a row, or a line of pure whitespace but
1635 1695 # of a size different to the indent level, will exit the input loop.
1636 1696 if (continue_prompt and self.autoindent and isspace(line) and
1637 1697 (line != self.indent_current or isspace(self.buffer[-1]))):
1638 1698 line = ''
1639 1699
1640 1700 self.log(line,continue_prompt)
1641 1701 self.update_cache(line)
1642 1702 return line
1643 1703
1644 1704 def handle_alias(self,line,continue_prompt=None,
1645 1705 pre=None,iFun=None,theRest=None):
1646 1706 """Handle alias input lines. """
1647 1707
1648 1708 theRest = esc_quotes(theRest)
1649 1709 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1650 1710 self.log(line_out,continue_prompt)
1651 1711 self.update_cache(line_out)
1652 1712 return line_out
1653 1713
1654 1714 def handle_shell_escape(self, line, continue_prompt=None,
1655 1715 pre=None,iFun=None,theRest=None):
1656 1716 """Execute the line in a shell, empty return value"""
1657 1717
1658 1718 #print 'line in :', `line` # dbg
1659 1719 # Example of a special handler. Others follow a similar pattern.
1660 1720 if continue_prompt: # multi-line statements
1661 1721 if iFun.startswith('!!'):
1662 1722 print 'SyntaxError: !! is not allowed in multiline statements'
1663 1723 return pre
1664 1724 else:
1665 1725 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1666 1726 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1667 1727 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1668 1728 else: # single-line input
1669 1729 if line.startswith('!!'):
1670 1730 # rewrite iFun/theRest to properly hold the call to %sx and
1671 1731 # the actual command to be executed, so handle_magic can work
1672 1732 # correctly
1673 1733 theRest = '%s %s' % (iFun[2:],theRest)
1674 1734 iFun = 'sx'
1675 1735 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1676 1736 continue_prompt,pre,iFun,theRest)
1677 1737 else:
1678 1738 cmd = esc_quotes(line[1:])
1679 1739 line_out = '%s.system("%s")' % (self.name,cmd)
1680 1740 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1681 1741 # update cache/log and return
1682 1742 self.log(line_out,continue_prompt)
1683 1743 self.update_cache(line_out) # readline cache gets normal line
1684 1744 #print 'line out r:', `line_out` # dbg
1685 1745 #print 'line out s:', line_out # dbg
1686 1746 return line_out
1687 1747
1688 1748 def handle_magic(self, line, continue_prompt=None,
1689 1749 pre=None,iFun=None,theRest=None):
1690 1750 """Execute magic functions.
1691 1751
1692 1752 Also log them with a prepended # so the log is clean Python."""
1693 1753
1694 1754 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1695 1755 self.log(cmd,continue_prompt)
1696 1756 self.update_cache(line)
1697 1757 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1698 1758 return cmd
1699 1759
1700 1760 def handle_auto(self, line, continue_prompt=None,
1701 1761 pre=None,iFun=None,theRest=None):
1702 1762 """Hande lines which can be auto-executed, quoting if requested."""
1703 1763
1704 1764 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1705 1765
1706 1766 # This should only be active for single-line input!
1707 1767 if continue_prompt:
1708 1768 return line
1709 1769
1710 1770 if pre == self.ESC_QUOTE:
1711 1771 # Auto-quote splitting on whitespace
1712 1772 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1713 1773 elif pre == self.ESC_QUOTE2:
1714 1774 # Auto-quote whole string
1715 1775 newcmd = '%s("%s")' % (iFun,theRest)
1716 1776 else:
1717 1777 # Auto-paren
1718 1778 if theRest[0:1] in ('=','['):
1719 1779 # Don't autocall in these cases. They can be either
1720 1780 # rebindings of an existing callable's name, or item access
1721 1781 # for an object which is BOTH callable and implements
1722 1782 # __getitem__.
1723 1783 return '%s %s' % (iFun,theRest)
1724 1784 if theRest.endswith(';'):
1725 1785 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1726 1786 else:
1727 1787 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1728 1788
1729 1789 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1730 1790 # log what is now valid Python, not the actual user input (without the
1731 1791 # final newline)
1732 1792 self.log(newcmd,continue_prompt)
1733 1793 return newcmd
1734 1794
1735 1795 def handle_help(self, line, continue_prompt=None,
1736 1796 pre=None,iFun=None,theRest=None):
1737 1797 """Try to get some help for the object.
1738 1798
1739 1799 obj? or ?obj -> basic information.
1740 1800 obj?? or ??obj -> more details.
1741 1801 """
1742 1802
1743 1803 # We need to make sure that we don't process lines which would be
1744 1804 # otherwise valid python, such as "x=1 # what?"
1745 1805 try:
1746 1806 codeop.compile_command(line)
1747 1807 except SyntaxError:
1748 1808 # We should only handle as help stuff which is NOT valid syntax
1749 1809 if line[0]==self.ESC_HELP:
1750 1810 line = line[1:]
1751 1811 elif line[-1]==self.ESC_HELP:
1752 1812 line = line[:-1]
1753 1813 self.log('#?'+line)
1754 1814 self.update_cache(line)
1755 1815 if line:
1756 1816 self.magic_pinfo(line)
1757 1817 else:
1758 1818 page(self.usage,screen_lines=self.rc.screen_length)
1759 1819 return '' # Empty string is needed here!
1760 1820 except:
1761 1821 # Pass any other exceptions through to the normal handler
1762 1822 return self.handle_normal(line,continue_prompt)
1763 1823 else:
1764 1824 # If the code compiles ok, we should handle it normally
1765 1825 return self.handle_normal(line,continue_prompt)
1766 1826
1767 1827 def handle_emacs(self,line,continue_prompt=None,
1768 1828 pre=None,iFun=None,theRest=None):
1769 1829 """Handle input lines marked by python-mode."""
1770 1830
1771 1831 # Currently, nothing is done. Later more functionality can be added
1772 1832 # here if needed.
1773 1833
1774 1834 # The input cache shouldn't be updated
1775 1835
1776 1836 return line
1777 1837
1778 1838 def write(self,data):
1779 1839 """Write a string to the default output"""
1780 1840 Term.cout.write(data)
1781 1841
1782 1842 def write_err(self,data):
1783 1843 """Write a string to the default error output"""
1784 1844 Term.cerr.write(data)
1785 1845
1786 1846 def exit(self):
1787 1847 """Handle interactive exit.
1788 1848
1789 1849 This method sets the exit_now attribute."""
1790 1850
1791 1851 if self.rc.confirm_exit:
1792 1852 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1793 1853 self.exit_now = True
1794 1854 else:
1795 1855 self.exit_now = True
1796 1856 return self.exit_now
1797 1857
1798 1858 def safe_execfile(self,fname,*where,**kw):
1799 1859 fname = os.path.expanduser(fname)
1800 1860
1801 1861 # find things also in current directory
1802 1862 dname = os.path.dirname(fname)
1803 1863 if not sys.path.count(dname):
1804 1864 sys.path.append(dname)
1805 1865
1806 1866 try:
1807 1867 xfile = open(fname)
1808 1868 except:
1809 1869 print >> Term.cerr, \
1810 1870 'Could not open file <%s> for safe execution.' % fname
1811 1871 return None
1812 1872
1813 1873 kw.setdefault('islog',0)
1814 1874 kw.setdefault('quiet',1)
1815 1875 kw.setdefault('exit_ignore',0)
1816 1876 first = xfile.readline()
1817 1877 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1818 1878 xfile.close()
1819 1879 # line by line execution
1820 1880 if first.startswith(_LOGHEAD) or kw['islog']:
1821 1881 print 'Loading log file <%s> one line at a time...' % fname
1822 1882 if kw['quiet']:
1823 1883 stdout_save = sys.stdout
1824 1884 sys.stdout = StringIO.StringIO()
1825 1885 try:
1826 1886 globs,locs = where[0:2]
1827 1887 except:
1828 1888 try:
1829 1889 globs = locs = where[0]
1830 1890 except:
1831 1891 globs = locs = globals()
1832 1892 badblocks = []
1833 1893
1834 1894 # we also need to identify indented blocks of code when replaying
1835 1895 # logs and put them together before passing them to an exec
1836 1896 # statement. This takes a bit of regexp and look-ahead work in the
1837 1897 # file. It's easiest if we swallow the whole thing in memory
1838 1898 # first, and manually walk through the lines list moving the
1839 1899 # counter ourselves.
1840 1900 indent_re = re.compile('\s+\S')
1841 1901 xfile = open(fname)
1842 1902 filelines = xfile.readlines()
1843 1903 xfile.close()
1844 1904 nlines = len(filelines)
1845 1905 lnum = 0
1846 1906 while lnum < nlines:
1847 1907 line = filelines[lnum]
1848 1908 lnum += 1
1849 1909 # don't re-insert logger status info into cache
1850 1910 if line.startswith('#log#'):
1851 1911 continue
1852 1912 elif line.startswith('#%s'% self.ESC_MAGIC):
1853 1913 self.update_cache(line[1:])
1854 1914 line = magic2python(line)
1855 1915 elif line.startswith('#!'):
1856 1916 self.update_cache(line[1:])
1857 1917 else:
1858 1918 # build a block of code (maybe a single line) for execution
1859 1919 block = line
1860 1920 try:
1861 1921 next = filelines[lnum] # lnum has already incremented
1862 1922 except:
1863 1923 next = None
1864 1924 while next and indent_re.match(next):
1865 1925 block += next
1866 1926 lnum += 1
1867 1927 try:
1868 1928 next = filelines[lnum]
1869 1929 except:
1870 1930 next = None
1871 1931 # now execute the block of one or more lines
1872 1932 try:
1873 1933 exec block in globs,locs
1874 1934 self.update_cache(block.rstrip())
1875 1935 except SystemExit:
1876 1936 pass
1877 1937 except:
1878 1938 badblocks.append(block.rstrip())
1879 1939 if kw['quiet']: # restore stdout
1880 1940 sys.stdout.close()
1881 1941 sys.stdout = stdout_save
1882 1942 print 'Finished replaying log file <%s>' % fname
1883 1943 if badblocks:
1884 1944 print >> sys.stderr, ('\nThe following lines/blocks in file '
1885 1945 '<%s> reported errors:' % fname)
1886 1946
1887 1947 for badline in badblocks:
1888 1948 print >> sys.stderr, badline
1889 1949 else: # regular file execution
1890 1950 try:
1891 1951 execfile(fname,*where)
1892 1952 except SyntaxError:
1893 1953 etype, evalue = sys.exc_info()[0:2]
1894 1954 self.SyntaxTB(etype,evalue,[])
1895 1955 warn('Failure executing file: <%s>' % fname)
1896 1956 except SystemExit,status:
1897 1957 if not kw['exit_ignore']:
1898 1958 self.InteractiveTB()
1899 1959 warn('Failure executing file: <%s>' % fname)
1900 1960 except:
1901 1961 self.InteractiveTB()
1902 1962 warn('Failure executing file: <%s>' % fname)
1903 1963
1904 1964 #************************* end of file <iplib.py> *****************************
@@ -1,735 +1,737 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 958 2005-12-27 23:17:51Z fperez $"""
9 $Id: ipmaker.py 960 2005-12-28 06:51:01Z fperez $"""
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #*****************************************************************************
17 17
18 18 from IPython import Release
19 19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 20 __license__ = Release.license
21 21 __version__ = Release.version
22 22
23 23 credits._Printer__data = """
24 24 Python: %s
25 25
26 26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 27 See http://ipython.scipy.org for more information.""" \
28 28 % credits._Printer__data
29 29
30 30 copyright._Printer__data += """
31 31
32 32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 33 All Rights Reserved."""
34 34
35 35 #****************************************************************************
36 36 # Required modules
37 37
38 38 # From the standard library
39 39 import __main__
40 40 import __builtin__
41 41 import os
42 42 import re
43 43 import sys
44 44 import types
45 45 from pprint import pprint,pformat
46 46
47 47 # Our own
48 48 from IPython import DPyGetOpt
49 49 from IPython.Struct import Struct
50 50 from IPython.OutputTrap import OutputTrap
51 51 from IPython.ConfigLoader import ConfigLoader
52 52 from IPython.iplib import InteractiveShell,qw_lol,import_fail_info
53 53 from IPython.usage import cmd_line_usage,interactive_usage
54 54 from IPython.Prompts import CachedOutput
55 55 from IPython.genutils import *
56 56
57 57 #-----------------------------------------------------------------------------
58 58 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
59 59 shell_class=InteractiveShell,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,embedded=embedded,**kw)
90 90
91 91 # Put 'help' in the user namespace
92 92 from site import _Helper
93 93 IP.user_ns['help'] = _Helper()
94 94
95 95 if DEVDEBUG:
96 96 # For developer debugging only (global flag)
97 97 from IPython import ultraTB
98 98 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
99 99 else:
100 100 # IPython itself shouldn't crash. This will produce a detailed
101 101 # post-mortem if it does
102 102 from IPython import CrashHandler
103 103 sys.excepthook = CrashHandler.CrashHandler(IP)
104 104
105 105 IP.BANNER_PARTS = ['Python %s\n'
106 106 'Type "copyright", "credits" or "license" '
107 107 'for more information.\n'
108 108 % (sys.version.split('\n')[0],),
109 109 "IPython %s -- An enhanced Interactive Python."
110 110 % (__version__,),
111 111 """? -> Introduction to IPython's features.
112 112 %magic -> Information about IPython's 'magic' % functions.
113 113 help -> Python's own help system.
114 114 object? -> Details about 'object'. ?object also works, ?? prints more.
115 115 """ ]
116 116
117 117 IP.usage = interactive_usage
118 118
119 119 # Platform-dependent suffix and directory names. We use _ipython instead
120 120 # of .ipython under win32 b/c there's software that breaks with .named
121 121 # directories on that platform.
122 122 if os.name == 'posix':
123 123 rc_suffix = ''
124 124 ipdir_def = '.ipython'
125 125 else:
126 126 rc_suffix = '.ini'
127 127 ipdir_def = '_ipython'
128 128
129 129 # default directory for configuration
130 130 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
131 131 os.path.join(IP.home_dir,ipdir_def)))
132 132
133 133 # we need the directory where IPython itself is installed
134 134 import IPython
135 135 IPython_dir = os.path.dirname(IPython.__file__)
136 136 del IPython
137 137
138 138 #-------------------------------------------------------------------------
139 139 # Command line handling
140 140
141 141 # Valid command line options (uses DPyGetOpt syntax, like Perl's
142 142 # GetOpt::Long)
143 143
144 144 # Any key not listed here gets deleted even if in the file (like session
145 145 # or profile). That's deliberate, to maintain the rc namespace clean.
146 146
147 147 # Each set of options appears twice: under _conv only the names are
148 148 # listed, indicating which type they must be converted to when reading the
149 149 # ipythonrc file. And under DPyGetOpt they are listed with the regular
150 150 # DPyGetOpt syntax (=s,=i,:f,etc).
151 151
152 152 # Make sure there's a space before each end of line (they get auto-joined!)
153 153 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
154 154 'c=s classic|cl color_info! colors=s confirm_exit! '
155 155 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
156 156 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
157 157 'quick screen_length|sl=i prompts_pad_left=i '
158 158 'logfile|lf=s logplay|lp=s profile|p=s '
159 159 'readline! readline_merge_completions! '
160 160 'readline_omit__names! '
161 161 'rcfile=s separate_in|si=s separate_out|so=s '
162 162 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
163 163 'magic_docstrings system_verbose! '
164 'multi_line_specials!')
164 'multi_line_specials! '
165 'autoedit_syntax!')
165 166
166 167 # Options that can *only* appear at the cmd line (not in rcfiles).
167 168
168 169 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
169 170 # the 'C-c !' command in emacs automatically appends a -i option at the end.
170 171 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
171 172 'gthread! qthread! wthread! pylab! tk!')
172 173
173 174 # Build the actual name list to be used by DPyGetOpt
174 175 opts_names = qw(cmdline_opts) + qw(cmdline_only)
175 176
176 177 # Set sensible command line defaults.
177 178 # This should have everything from cmdline_opts and cmdline_only
178 179 opts_def = Struct(autocall = 1,
179 180 autoindent=0,
180 181 automagic = 1,
181 182 banner = 1,
182 183 cache_size = 1000,
183 184 c = '',
184 185 classic = 0,
185 186 colors = 'NoColor',
186 187 color_info = 0,
187 188 confirm_exit = 1,
188 189 debug = 0,
189 190 deep_reload = 0,
190 191 editor = '0',
191 192 help = 0,
192 193 ignore = 0,
193 194 ipythondir = ipythondir,
194 195 log = 0,
195 196 logfile = '',
196 197 logplay = '',
197 198 multi_line_specials = 1,
198 199 messages = 1,
199 200 nosep = 0,
200 201 pdb = 0,
201 202 pprint = 0,
202 203 profile = '',
203 204 prompt_in1 = 'In [\\#]: ',
204 205 prompt_in2 = ' .\\D.: ',
205 206 prompt_out = 'Out[\\#]: ',
206 207 prompts_pad_left = 1,
207 208 quick = 0,
208 209 readline = 1,
209 210 readline_merge_completions = 1,
210 211 readline_omit__names = 0,
211 212 rcfile = 'ipythonrc' + rc_suffix,
212 213 screen_length = 0,
213 214 separate_in = '\n',
214 215 separate_out = '\n',
215 216 separate_out2 = '',
216 217 system_verbose = 0,
217 218 gthread = 0,
218 219 qthread = 0,
219 220 wthread = 0,
220 221 pylab = 0,
221 222 tk = 0,
222 223 upgrade = 0,
223 224 Version = 0,
224 225 xmode = 'Verbose',
225 226 wildcards_case_sensitive = 1,
226 227 magic_docstrings = 0, # undocumented, for doc generation
228 autoedit_syntax = 0,
227 229 )
228 230
229 231 # Things that will *only* appear in rcfiles (not at the command line).
230 232 # Make sure there's a space before each end of line (they get auto-joined!)
231 233 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
232 234 qw_lol: 'import_some ',
233 235 # for things with embedded whitespace:
234 236 list_strings:'execute alias readline_parse_and_bind ',
235 237 # Regular strings need no conversion:
236 238 None:'readline_remove_delims ',
237 239 }
238 240 # Default values for these
239 241 rc_def = Struct(include = [],
240 242 import_mod = [],
241 243 import_all = [],
242 244 import_some = [[]],
243 245 execute = [],
244 246 execfile = [],
245 247 alias = [],
246 248 readline_parse_and_bind = [],
247 249 readline_remove_delims = '',
248 250 )
249 251
250 252 # Build the type conversion dictionary from the above tables:
251 253 typeconv = rcfile_opts.copy()
252 254 typeconv.update(optstr2types(cmdline_opts))
253 255
254 256 # FIXME: the None key appears in both, put that back together by hand. Ugly!
255 257 typeconv[None] += ' ' + rcfile_opts[None]
256 258
257 259 # Remove quotes at ends of all strings (used to protect spaces)
258 260 typeconv[unquote_ends] = typeconv[None]
259 261 del typeconv[None]
260 262
261 263 # Build the list we'll use to make all config decisions with defaults:
262 264 opts_all = opts_def.copy()
263 265 opts_all.update(rc_def)
264 266
265 267 # Build conflict resolver for recursive loading of config files:
266 268 # - preserve means the outermost file maintains the value, it is not
267 269 # overwritten if an included file has the same key.
268 270 # - add_flip applies + to the two values, so it better make sense to add
269 271 # those types of keys. But it flips them first so that things loaded
270 272 # deeper in the inclusion chain have lower precedence.
271 273 conflict = {'preserve': ' '.join([ typeconv[int],
272 274 typeconv[unquote_ends] ]),
273 275 'add_flip': ' '.join([ typeconv[qwflat],
274 276 typeconv[qw_lol],
275 277 typeconv[list_strings] ])
276 278 }
277 279
278 280 # Now actually process the command line
279 281 getopt = DPyGetOpt.DPyGetOpt()
280 282 getopt.setIgnoreCase(0)
281 283
282 284 getopt.parseConfiguration(opts_names)
283 285
284 286 try:
285 287 getopt.processArguments(argv)
286 288 except:
287 289 print cmd_line_usage
288 290 warn('\nError in Arguments: ' + `sys.exc_value`)
289 291 sys.exit(1)
290 292
291 293 # convert the options dict to a struct for much lighter syntax later
292 294 opts = Struct(getopt.optionValues)
293 295 args = getopt.freeValues
294 296
295 297 # this is the struct (which has default values at this point) with which
296 298 # we make all decisions:
297 299 opts_all.update(opts)
298 300
299 301 # Options that force an immediate exit
300 302 if opts_all.help:
301 303 page(cmd_line_usage)
302 304 sys.exit()
303 305
304 306 if opts_all.Version:
305 307 print __version__
306 308 sys.exit()
307 309
308 310 if opts_all.magic_docstrings:
309 311 IP.magic_magic('-latex')
310 312 sys.exit()
311 313
312 314 # Create user config directory if it doesn't exist. This must be done
313 315 # *after* getting the cmd line options.
314 316 if not os.path.isdir(opts_all.ipythondir):
315 317 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
316 318
317 319 # upgrade user config files while preserving a copy of the originals
318 320 if opts_all.upgrade:
319 321 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
320 322
321 323 # check mutually exclusive options in the *original* command line
322 324 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
323 325 qw('classic profile'),qw('classic rcfile')])
324 326
325 327 # default logfilename used when -log is called.
326 328 IP.LOGDEF = 'ipython.log'
327 329
328 330 #---------------------------------------------------------------------------
329 331 # Log replay
330 332
331 333 # if -logplay, we need to 'become' the other session. That basically means
332 334 # replacing the current command line environment with that of the old
333 335 # session and moving on.
334 336
335 337 # this is needed so that later we know we're in session reload mode, as
336 338 # opts_all will get overwritten:
337 339 load_logplay = 0
338 340
339 341 if opts_all.logplay:
340 342 load_logplay = opts_all.logplay
341 343 opts_debug_save = opts_all.debug
342 344 try:
343 345 logplay = open(opts_all.logplay)
344 346 except IOError:
345 347 if opts_all.debug: IP.InteractiveTB()
346 348 warn('Could not open logplay file '+`opts_all.logplay`)
347 349 # restore state as if nothing had happened and move on, but make
348 350 # sure that later we don't try to actually load the session file
349 351 logplay = None
350 352 load_logplay = 0
351 353 del opts_all.logplay
352 354 else:
353 355 try:
354 356 logplay.readline()
355 357 logplay.readline();
356 358 # this reloads that session's command line
357 359 cmd = logplay.readline()[6:]
358 360 exec cmd
359 361 # restore the true debug flag given so that the process of
360 362 # session loading itself can be monitored.
361 363 opts.debug = opts_debug_save
362 364 # save the logplay flag so later we don't overwrite the log
363 365 opts.logplay = load_logplay
364 366 # now we must update our own structure with defaults
365 367 opts_all.update(opts)
366 368 # now load args
367 369 cmd = logplay.readline()[6:]
368 370 exec cmd
369 371 logplay.close()
370 372 except:
371 373 logplay.close()
372 374 if opts_all.debug: IP.InteractiveTB()
373 375 warn("Logplay file lacking full configuration information.\n"
374 376 "I'll try to read it, but some things may not work.")
375 377
376 378 #-------------------------------------------------------------------------
377 379 # set up output traps: catch all output from files, being run, modules
378 380 # loaded, etc. Then give it to the user in a clean form at the end.
379 381
380 382 msg_out = 'Output messages. '
381 383 msg_err = 'Error messages. '
382 384 msg_sep = '\n'
383 385 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
384 386 msg_err,msg_sep,debug,
385 387 quiet_out=1),
386 388 user_exec = OutputTrap('User File Execution',msg_out,
387 389 msg_err,msg_sep,debug),
388 390 logplay = OutputTrap('Log Loader',msg_out,
389 391 msg_err,msg_sep,debug),
390 392 summary = ''
391 393 )
392 394
393 395 #-------------------------------------------------------------------------
394 396 # Process user ipythonrc-type configuration files
395 397
396 398 # turn on output trapping and log to msg.config
397 399 # remember that with debug on, trapping is actually disabled
398 400 msg.config.trap_all()
399 401
400 402 # look for rcfile in current or default directory
401 403 try:
402 404 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
403 405 except IOError:
404 406 if opts_all.debug: IP.InteractiveTB()
405 407 warn('Configuration file %s not found. Ignoring request.'
406 408 % (opts_all.rcfile) )
407 409
408 410 # 'profiles' are a shorthand notation for config filenames
409 411 if opts_all.profile:
410 412 try:
411 413 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
412 414 + rc_suffix,
413 415 opts_all.ipythondir)
414 416 except IOError:
415 417 if opts_all.debug: IP.InteractiveTB()
416 418 opts.profile = '' # remove profile from options if invalid
417 419 warn('Profile configuration file %s not found. Ignoring request.'
418 420 % (opts_all.profile) )
419 421
420 422 # load the config file
421 423 rcfiledata = None
422 424 if opts_all.quick:
423 425 print 'Launching IPython in quick mode. No config file read.'
424 426 elif opts_all.classic:
425 427 print 'Launching IPython in classic mode. No config file read.'
426 428 elif opts_all.rcfile:
427 429 try:
428 430 cfg_loader = ConfigLoader(conflict)
429 431 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
430 432 'include',opts_all.ipythondir,
431 433 purge = 1,
432 434 unique = conflict['preserve'])
433 435 except:
434 436 IP.InteractiveTB()
435 437 warn('Problems loading configuration file '+
436 438 `opts_all.rcfile`+
437 439 '\nStarting with default -bare bones- configuration.')
438 440 else:
439 441 warn('No valid configuration file found in either currrent directory\n'+
440 442 'or in the IPython config. directory: '+`opts_all.ipythondir`+
441 443 '\nProceeding with internal defaults.')
442 444
443 445 #------------------------------------------------------------------------
444 446 # Set exception handlers in mode requested by user.
445 447 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
446 448 IP.magic_xmode(opts_all.xmode)
447 449 otrap.release_out()
448 450
449 451 #------------------------------------------------------------------------
450 452 # Execute user config
451 453
452 454 # Create a valid config structure with the right precedence order:
453 455 # defaults < rcfile < command line. This needs to be in the instance, so
454 456 # that method calls below that rely on it find it.
455 457 IP.rc = rc_def.copy()
456 458
457 459 # Work with a local alias inside this routine to avoid unnecessary
458 460 # attribute lookups.
459 461 IP_rc = IP.rc
460 462
461 463 IP_rc.update(opts_def)
462 464 if rcfiledata:
463 465 # now we can update
464 466 IP_rc.update(rcfiledata)
465 467 IP_rc.update(opts)
466 468 IP_rc.update(rc_override)
467 469
468 470 # Store the original cmd line for reference:
469 471 IP_rc.opts = opts
470 472 IP_rc.args = args
471 473
472 474 # create a *runtime* Struct like rc for holding parameters which may be
473 475 # created and/or modified by runtime user extensions.
474 476 IP.runtime_rc = Struct()
475 477
476 478 # from this point on, all config should be handled through IP_rc,
477 479 # opts* shouldn't be used anymore.
478 480
479 481 # add personal .ipython dir to sys.path so that users can put things in
480 482 # there for customization
481 483 sys.path.append(IP_rc.ipythondir)
482 484 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
483 485
484 486 # update IP_rc with some special things that need manual
485 487 # tweaks. Basically options which affect other options. I guess this
486 488 # should just be written so that options are fully orthogonal and we
487 489 # wouldn't worry about this stuff!
488 490
489 491 if IP_rc.classic:
490 492 IP_rc.quick = 1
491 493 IP_rc.cache_size = 0
492 494 IP_rc.pprint = 0
493 495 IP_rc.prompt_in1 = '>>> '
494 496 IP_rc.prompt_in2 = '... '
495 497 IP_rc.prompt_out = ''
496 498 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
497 499 IP_rc.colors = 'NoColor'
498 500 IP_rc.xmode = 'Plain'
499 501
500 502 # configure readline
501 503 # Define the history file for saving commands in between sessions
502 504 if IP_rc.profile:
503 505 histfname = 'history-%s' % IP_rc.profile
504 506 else:
505 507 histfname = 'history'
506 508 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
507 509
508 510 # update exception handlers with rc file status
509 511 otrap.trap_out() # I don't want these messages ever.
510 512 IP.magic_xmode(IP_rc.xmode)
511 513 otrap.release_out()
512 514
513 515 # activate logging if requested and not reloading a log
514 516 if IP_rc.logplay:
515 517 IP.magic_logstart(IP_rc.logplay + ' append')
516 518 elif IP_rc.logfile:
517 519 IP.magic_logstart(IP_rc.logfile)
518 520 elif IP_rc.log:
519 521 IP.magic_logstart()
520 522
521 523 # find user editor so that it we don't have to look it up constantly
522 524 if IP_rc.editor.strip()=='0':
523 525 try:
524 526 ed = os.environ['EDITOR']
525 527 except KeyError:
526 528 if os.name == 'posix':
527 529 ed = 'vi' # the only one guaranteed to be there!
528 530 else:
529 531 ed = 'notepad' # same in Windows!
530 532 IP_rc.editor = ed
531 533
532 534 # Keep track of whether this is an embedded instance or not (useful for
533 535 # post-mortems).
534 536 IP_rc.embedded = IP.embedded
535 537
536 538 # Recursive reload
537 539 try:
538 540 from IPython import deep_reload
539 541 if IP_rc.deep_reload:
540 542 __builtin__.reload = deep_reload.reload
541 543 else:
542 544 __builtin__.dreload = deep_reload.reload
543 545 del deep_reload
544 546 except ImportError:
545 547 pass
546 548
547 549 # Save the current state of our namespace so that the interactive shell
548 550 # can later know which variables have been created by us from config files
549 551 # and loading. This way, loading a file (in any way) is treated just like
550 552 # defining things on the command line, and %who works as expected.
551 553
552 554 # DON'T do anything that affects the namespace beyond this point!
553 555 IP.internal_ns.update(__main__.__dict__)
554 556
555 557 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
556 558
557 559 # Now run through the different sections of the users's config
558 560 if IP_rc.debug:
559 561 print 'Trying to execute the following configuration structure:'
560 562 print '(Things listed first are deeper in the inclusion tree and get'
561 563 print 'loaded first).\n'
562 564 pprint(IP_rc.__dict__)
563 565
564 566 for mod in IP_rc.import_mod:
565 567 try:
566 568 exec 'import '+mod in IP.user_ns
567 569 except :
568 570 IP.InteractiveTB()
569 571 import_fail_info(mod)
570 572
571 573 for mod_fn in IP_rc.import_some:
572 574 if mod_fn == []: break
573 575 mod,fn = mod_fn[0],','.join(mod_fn[1:])
574 576 try:
575 577 exec 'from '+mod+' import '+fn in IP.user_ns
576 578 except :
577 579 IP.InteractiveTB()
578 580 import_fail_info(mod,fn)
579 581
580 582 for mod in IP_rc.import_all:
581 583 try:
582 584 exec 'from '+mod+' import *' in IP.user_ns
583 585 except :
584 586 IP.InteractiveTB()
585 587 import_fail_info(mod)
586 588
587 589 for code in IP_rc.execute:
588 590 try:
589 591 exec code in IP.user_ns
590 592 except:
591 593 IP.InteractiveTB()
592 594 warn('Failure executing code: ' + `code`)
593 595
594 596 # Execute the files the user wants in ipythonrc
595 597 for file in IP_rc.execfile:
596 598 try:
597 599 file = filefind(file,sys.path+[IPython_dir])
598 600 except IOError:
599 601 warn(itpl('File $file not found. Skipping it.'))
600 602 else:
601 603 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
602 604
603 605 # release stdout and stderr and save config log into a global summary
604 606 msg.config.release_all()
605 607 if IP_rc.messages:
606 608 msg.summary += msg.config.summary_all()
607 609
608 610 #------------------------------------------------------------------------
609 611 # Setup interactive session
610 612
611 613 # Now we should be fully configured. We can then execute files or load
612 614 # things only needed for interactive use. Then we'll open the shell.
613 615
614 616 # Take a snapshot of the user namespace before opening the shell. That way
615 617 # we'll be able to identify which things were interactively defined and
616 618 # which were defined through config files.
617 619 IP.user_config_ns = IP.user_ns.copy()
618 620
619 621 # Force reading a file as if it were a session log. Slower but safer.
620 622 if load_logplay:
621 623 print 'Replaying log...'
622 624 try:
623 625 if IP_rc.debug:
624 626 logplay_quiet = 0
625 627 else:
626 628 logplay_quiet = 1
627 629
628 630 msg.logplay.trap_all()
629 631 IP.safe_execfile(load_logplay,IP.user_ns,
630 632 islog = 1, quiet = logplay_quiet)
631 633 msg.logplay.release_all()
632 634 if IP_rc.messages:
633 635 msg.summary += msg.logplay.summary_all()
634 636 except:
635 637 warn('Problems replaying logfile %s.' % load_logplay)
636 638 IP.InteractiveTB()
637 639
638 640 # Load remaining files in command line
639 641 msg.user_exec.trap_all()
640 642
641 643 # Do NOT execute files named in the command line as scripts to be loaded
642 644 # by embedded instances. Doing so has the potential for an infinite
643 645 # recursion if there are exceptions thrown in the process.
644 646
645 647 # XXX FIXME: the execution of user files should be moved out to after
646 648 # ipython is fully initialized, just as if they were run via %run at the
647 649 # ipython prompt. This would also give them the benefit of ipython's
648 650 # nice tracebacks.
649 651
650 652 if not embedded and IP_rc.args:
651 653 name_save = IP.user_ns['__name__']
652 654 IP.user_ns['__name__'] = '__main__'
653 655 try:
654 656 # Set our own excepthook in case the user code tries to call it
655 657 # directly. This prevents triggering the IPython crash handler.
656 658 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
657 659 for run in args:
658 660 IP.safe_execfile(run,IP.user_ns)
659 661 finally:
660 662 # Reset our crash handler in place
661 663 sys.excepthook = old_excepthook
662 664
663 665 IP.user_ns['__name__'] = name_save
664 666
665 667 msg.user_exec.release_all()
666 668 if IP_rc.messages:
667 669 msg.summary += msg.user_exec.summary_all()
668 670
669 671 # since we can't specify a null string on the cmd line, 0 is the equivalent:
670 672 if IP_rc.nosep:
671 673 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
672 674 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
673 675 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
674 676 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
675 677 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
676 678 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
677 679 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
678 680
679 681 # Determine how many lines at the bottom of the screen are needed for
680 682 # showing prompts, so we can know wheter long strings are to be printed or
681 683 # paged:
682 684 num_lines_bot = IP_rc.separate_in.count('\n')+1
683 685 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
684 686 # Initialize cache, set in/out prompts and printing system
685 687 IP.outputcache = CachedOutput(IP_rc.cache_size,
686 688 IP_rc.pprint,
687 689 input_sep = IP_rc.separate_in,
688 690 output_sep = IP_rc.separate_out,
689 691 output_sep2 = IP_rc.separate_out2,
690 692 ps1 = IP_rc.prompt_in1,
691 693 ps2 = IP_rc.prompt_in2,
692 694 ps_out = IP_rc.prompt_out,
693 695 user_ns = IP.user_ns,
694 696 input_hist = IP.input_hist,
695 697 pad_left = IP_rc.prompts_pad_left)
696 698
697 699 # user may have over-ridden the default print hook:
698 700 try:
699 701 IP.outputcache.__class__.display = IP.hooks.display
700 702 except AttributeError:
701 703 pass
702 704
703 705 # Set calling of pdb on exceptions
704 706 IP.InteractiveTB.call_pdb = IP_rc.pdb
705 707
706 708 # I don't like assigning globally to sys, because it means when embedding
707 709 # instances, each embedded instance overrides the previous choice. But
708 710 # sys.displayhook seems to be called internally by exec, so I don't see a
709 711 # way around it.
710 712 sys.displayhook = IP.outputcache
711 713
712 714 # we need to know globally if we're caching i/o or not
713 715 IP.do_full_cache = IP.outputcache.do_full_cache
714 716
715 717 # configure startup banner
716 718 if IP_rc.c: # regular python doesn't print the banner with -c
717 719 IP_rc.banner = 0
718 720 if IP_rc.banner:
719 721 BANN_P = IP.BANNER_PARTS
720 722 else:
721 723 BANN_P = []
722 724
723 725 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
724 726
725 727 # add message log (possibly empty)
726 728 if msg.summary: BANN_P.append(msg.summary)
727 729 # Final banner is a string
728 730 IP.BANNER = '\n'.join(BANN_P)
729 731
730 732 # Finalize the IPython instance. This assumes the rc structure is fully
731 733 # in place.
732 734 IP.post_config_initialization()
733 735
734 736 return IP
735 737 #************************ end of file <ipmaker.py> **************************
@@ -1,586 +1,585 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 926 2005-12-01 18:14:21Z fperez $
9 # $Id: usage.py 960 2005-12-28 06:51:01Z 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 147 -[no]autocall
148 148 Make IPython automatically call any callable object even if you
149 149 didn’t type explicit parentheses. For example, ’str 43’ becomes
150 150 ’str(43)’ automatically.
151 151
152 152 -[no]autoindent
153 153 Turn automatic indentation on/off.
154 154
155 155 -[no]automagic
156 156 Make magic commands automatic (without needing their first char-
157 acter to be @). Type @magic at the IPython prompt for more
157 acter to be %). Type %magic at the IPython prompt for more
158 158 information.
159 159
160 -[no]autoparens
161 Make IPython automatically call any callable object even if you
162 didn’t type explicit parentheses. For example, ’str 43’ becomes
163 ’str(43)’ automatically.
160 -[no]autoedit_syntax
161 When a syntax error occurs after editing a file, automatically
162 open the file to the trouble causing line for convenient fixing.
164 163
165 164 -[no]banner
166 165 Print the intial information banner (default on).
167 166
168 167 -c <command>
169 168 Execute the given command string, and set sys.argv to [’c’].
170 169 This is similar to the -c option in the normal Python inter-
171 170 preter.
172 171
173 172 -cache_size|cs <n>
174 173 Size of the output cache (maximum number of entries to hold in
175 174 memory). The default is 1000, you can change it permanently in
176 175 your config file. Setting it to 0 completely disables the
177 176 caching system, and the minimum value accepted is 20 (if you
178 177 provide a value less than 20, it is reset to 0 and a warning is
179 178 issued). This limit is defined because otherwise you’ll spend
180 179 more time re-flushing a too small cache than working.
181 180
182 181 -classic|cl
183 182 Gives IPython a similar feel to the classic Python prompt.
184 183
185 184 -colors <scheme>
186 185 Color scheme for prompts and exception reporting. Currently
187 186 implemented: NoColor, Linux, and LightBG.
188 187
189 188 -[no]color_info
190 189 IPython can display information about objects via a set of func-
191 190 tions, and optionally can use colors for this, syntax highlight-
192 191 ing source code and various other elements. However, because
193 192 this information is passed through a pager (like ’less’) and
194 193 many pagers get confused with color codes, this option is off by
195 194 default. You can test it and turn it on permanently in your
196 195 ipythonrc file if it works for you. As a reference, the ’less’
197 196 pager supplied with Mandrake 8.2 works ok, but that in RedHat
198 197 7.2 doesn’t.
199 198
200 199 Test it and turn it on permanently if it works with your system.
201 200 The magic function @color_info allows you to toggle this inter-
202 201 actively for testing.
203 202
204 203 -[no]confirm_exit
205 204 Set to confirm when you try to exit IPython with an EOF (Con-
206 205 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
207 206 magic functions @Exit or @Quit you can force a direct exit,
208 207 bypassing any confirmation.
209 208
210 209 -[no]debug
211 210 Show information about the loading process. Very useful to pin
212 211 down problems with your configuration files or to get details
213 212 about session restores.
214 213
215 214 -[no]deep_reload
216 215 IPython can use the deep_reload module which reloads changes in
217 216 modules recursively (it replaces the reload() function, so you
218 217 don’t need to change anything to use it). deep_reload() forces a
219 218 full reload of modules whose code may have changed, which the
220 219 default reload() function does not.
221 220
222 221 When deep_reload is off, IPython will use the normal reload(),
223 222 but deep_reload will still be available as dreload(). This fea-
224 223 ture is off by default [which means that you have both normal
225 224 reload() and dreload()].
226 225
227 226 -editor <name>
228 227 Which editor to use with the @edit command. By default, IPython
229 228 will honor your EDITOR environment variable (if not set, vi is
230 229 the Unix default and notepad the Windows one). Since this editor
231 230 is invoked on the fly by IPython and is meant for editing small
232 231 code snippets, you may want to use a small, lightweight editor
233 232 here (in case your default EDITOR is something like Emacs).
234 233
235 234 -ipythondir <name>
236 235 The name of your IPython configuration directory IPYTHONDIR.
237 236 This can also be specified through the environment variable
238 237 IPYTHONDIR.
239 238
240 239 -log|l Generate a log file of all input. The file is named ipython.log
241 240 in your current directory (which prevents logs from multiple
242 241 IPython sessions from trampling each other). You can use this to
243 242 later restore a session by loading your logfile as a file to be
244 243 executed with option -logplay (see below).
245 244
246 245 -logfile|lf
247 246 Specifu the name of your logfile.
248 247
249 248 -logplay|lp
250 249 Replay a previous log. For restoring a session as close as pos-
251 250 sible to the state you left it in, use this option (don’t just
252 251 run the logfile). With -logplay, IPython will try to reconstruct
253 252 the previous working environment in full, not just execute the
254 253 commands in the logfile.
255 254 When a session is restored, logging is automatically turned on
256 255 again with the name of the logfile it was invoked with (it is
257 256 read from the log header). So once you’ve turned logging on for
258 257 a session, you can quit IPython and reload it as many times as
259 258 you want and it will continue to log its history and restore
260 259 from the beginning every time.
261 260
262 261 Caveats: there are limitations in this option. The history vari-
263 262 ables _i*,_* and _dh don’t get restored properly. In the future
264 263 we will try to implement full session saving by writing and
265 264 retrieving a failed because of inherent limitations of Python’s
266 265 Pickle module, so this may have to wait.
267 266
268 267 -[no]messages
269 268 Print messages which IPython collects about its startup process
270 269 (default on).
271 270
272 271 -[no]pdb
273 272 Automatically call the pdb debugger after every uncaught excep-
274 273 tion. If you are used to debugging using pdb, this puts you
275 274 automatically inside of it after any call (either in IPython or
276 275 in code called by it) which triggers an exception which goes
277 276 uncaught.
278 277
279 278 -[no]pprint
280 279 IPython can optionally use the pprint (pretty printer) module
281 280 for displaying results. pprint tends to give a nicer display of
282 281 nested data structures. If you like it, you can turn it on per-
283 282 manently in your config file (default off).
284 283
285 284 -profile|p <name>
286 285 Assume that your config file is ipythonrc-<name> (looks in cur-
287 286 rent dir first, then in IPYTHONDIR). This is a quick way to keep
288 287 and load multiple config files for different tasks, especially
289 288 if you use the include option of config files. You can keep a
290 289 basic IPYTHONDIR/ipythonrc file and then have other ’profiles’
291 290 which include this one and load extra things for particular
292 291 tasks. For example:
293 292
294 293 1) $HOME/.ipython/ipythonrc : load basic things you always want.
295 294 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
296 295 related modules.
297 296 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
298 297 plotting modules.
299 298
300 299 Since it is possible to create an endless loop by having circu-
301 300 lar file inclusions, IPython will stop if it reaches 15 recur-
302 301 sive inclusions.
303 302
304 303 -prompt_in1|pi1 <string>
305 304 Specify the string used for input prompts. Note that if you are
306 305 using numbered prompts, the number is represented with a ’\#’ in
307 306 the string. Don’t forget to quote strings with spaces embedded
308 307 in them. Default: ’In [\#]:’.
309 308
310 309 Most bash-like escapes can be used to customize IPython’s
311 310 prompts, as well as a few additional ones which are IPython-spe-
312 311 cific. All valid prompt escapes are described in detail in the
313 312 Customization section of the IPython HTML/PDF manual.
314 313
315 314 -prompt_in2|pi2 <string>
316 315 Similar to the previous option, but used for the continuation
317 316 prompts. The special sequence ’\D’ is similar to ’\#’, but with
318 317 all digits replaced dots (so you can have your continuation
319 318 prompt aligned with your input prompt). Default: ’ .\D.:’
320 319 (note three spaces at the start for alignment with ’In [\#]’).
321 320
322 321 -prompt_out|po <string>
323 322 String used for output prompts, also uses numbers like
324 323 prompt_in1. Default: ’Out[\#]:’.
325 324
326 325 -quick Start in bare bones mode (no config file loaded).
327 326
328 327 -rcfile <name>
329 328 Name of your IPython resource configuration file. normally
330 329 IPython loads ipythonrc (from current directory) or
331 330 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
332 331 IPython starts with a bare bones configuration (no modules
333 332 loaded at all).
334 333
335 334 -[no]readline
336 335 Use the readline library, which is needed to support name com-
337 336 pletion and command history, among other things. It is enabled
338 337 by default, but may cause problems for users of X/Emacs in
339 338 Python comint or shell buffers.
340 339
341 340 Note that emacs ’eterm’ buffers (opened with M-x term) support
342 341 IPython’s readline and syntax coloring fine, only ’emacs’ (M-x
343 342 shell and C-c !) buffers do not.
344 343
345 344 -screen_length|sl <n>
346 345 Number of lines of your screen. This is used to control print-
347 346 ing of very long strings. Strings longer than this number of
348 347 lines will be sent through a pager instead of directly printed.
349 348
350 349 The default value for this is 0, which means IPython will auto-
351 350 detect your screen size every time it needs to print certain
352 351 potentially long strings (this doesn’t change the behavior of
353 352 the ’print’ keyword, it’s only triggered internally). If for
354 353 some reason this isn’t working well (it needs curses support),
355 354 specify it yourself. Otherwise don’t change the default.
356 355
357 356 -separate_in|si <string>
358 357 Separator before input prompts. Default ’0.
359 358
360 359 -separate_out|so <string>
361 360 Separator before output prompts. Default: 0 (nothing).
362 361
363 362 -separate_out2|so2 <string>
364 363 Separator after output prompts. Default: 0 (nothing).
365 364
366 365 -nosep Shorthand for ’-separate_in 0 -separate_out 0 -separate_out2 0’.
367 366 Simply removes all input/output separators.
368 367
369 368 -upgrade
370 369 Allows you to upgrade your IPYTHONDIR configuration when you
371 370 install a new version of IPython. Since new versions may
372 371 include new command lines options or example files, this copies
373 372 updated ipythonrc-type files. However, it backs up (with a .old
374 373 extension) all files which it overwrites so that you can merge
375 374 back any custimizations you might have in your personal files.
376 375
377 376 -Version
378 377 Print version information and exit.
379 378
380 379 -xmode <modename>
381 380 Mode for exception reporting. The valid modes are Plain, Con-
382 381 text, and Verbose.
383 382
384 383 - Plain: similar to python’s normal traceback printing.
385 384
386 385 - Context: prints 5 lines of context source code around each
387 386 line in the traceback.
388 387
389 388 - Verbose: similar to Context, but additionally prints the vari-
390 389 ables currently visible where the exception happened (shortening
391 390 their strings if too long). This can potentially be very slow,
392 391 if you happen to have a huge data structure whose string repre-
393 392 sentation is complex to compute. Your computer may appear to
394 393 freeze for a while with cpu usage at 100%. If this occurs, you
395 394 can cancel the traceback with Ctrl-C (maybe hitting it more than
396 395 once).
397 396
398 397
399 398 EMBEDDING
400 399 It is possible to start an IPython instance inside your own Python pro-
401 400 grams. In the documentation example files there are some illustrations
402 401 on how to do this.
403 402
404 403 This feature allows you to evalutate dynamically the state of your
405 404 code, operate with your variables, analyze them, etc. Note however
406 405 that any changes you make to values while in the shell do NOT propagate
407 406 back to the running code, so it is safe to modify your values because
408 407 you won’t break your code in bizarre ways by doing so.
409 408 """
410 409
411 410 cmd_line_usage = __doc__
412 411
413 412 #---------------------------------------------------------------------------
414 413 interactive_usage = """
415 414 IPython -- An enhanced Interactive Python
416 415 =========================================
417 416
418 417 IPython offers a combination of convenient shell features, special commands
419 418 and a history mechanism for both input (command history) and output (results
420 419 caching, similar to Mathematica). It is intended to be a fully compatible
421 420 replacement for the standard Python interpreter, while offering vastly
422 421 improved functionality and flexibility.
423 422
424 423 At your system command line, type 'ipython -help' to see the command line
425 424 options available. This document only describes interactive features.
426 425
427 426 Warning: IPython relies on the existence of a global variable called __IP which
428 427 controls the shell itself. If you redefine __IP to anything, bizarre behavior
429 428 will quickly occur.
430 429
431 430 MAIN FEATURES
432 431
433 432 * Access to the standard Python help. As of Python 2.1, a help system is
434 433 available with access to object docstrings and the Python manuals. Simply
435 434 type 'help' (no quotes) to access it.
436 435
437 436 * Magic commands: type %magic for information on the magic subsystem.
438 437
439 438 * System command aliases, via the %alias command or the ipythonrc config file.
440 439
441 440 * Dynamic object information:
442 441
443 442 Typing ?word or word? prints detailed information about an object. If
444 443 certain strings in the object are too long (docstrings, code, etc.) they get
445 444 snipped in the center for brevity.
446 445
447 446 Typing ??word or word?? gives access to the full information without
448 447 snipping long strings. Long strings are sent to the screen through the less
449 448 pager if longer than the screen, printed otherwise.
450 449
451 450 The ?/?? system gives access to the full source code for any object (if
452 451 available), shows function prototypes and other useful information.
453 452
454 453 If you just want to see an object's docstring, type '%pdoc object' (without
455 454 quotes, and without % if you have automagic on).
456 455
457 456 Both %pdoc and ?/?? give you access to documentation even on things which are
458 457 not explicitely defined. Try for example typing {}.get? or after import os,
459 458 type os.path.abspath??. The magic functions %pdef, %source and %file operate
460 459 similarly.
461 460
462 461 * Completion in the local namespace, by typing TAB at the prompt.
463 462
464 463 At any time, hitting tab will complete any available python commands or
465 464 variable names, and show you a list of the possible completions if there's
466 465 no unambiguous one. It will also complete filenames in the current directory.
467 466
468 467 This feature requires the readline and rlcomplete modules, so it won't work
469 468 if your Python lacks readline support (such as under Windows).
470 469
471 470 * Search previous command history in two ways (also requires readline):
472 471
473 472 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
474 473 search through only the history items that match what you've typed so
475 474 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
476 475 normal arrow keys.
477 476
478 477 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
479 478 your history for lines that match what you've typed so far, completing as
480 479 much as it can.
481 480
482 481 * Persistent command history across sessions (readline required).
483 482
484 483 * Logging of input with the ability to save and restore a working session.
485 484
486 485 * System escape with !. Typing !ls will run 'ls' in the current directory.
487 486
488 487 * The reload command does a 'deep' reload of a module: changes made to the
489 488 module since you imported will actually be available without having to exit.
490 489
491 490 * Verbose and colored exception traceback printouts. See the magic xmode and
492 491 xcolor functions for details (just type %magic).
493 492
494 493 * Input caching system:
495 494
496 495 IPython offers numbered prompts (In/Out) with input and output caching. All
497 496 input is saved and can be retrieved as variables (besides the usual arrow
498 497 key recall).
499 498
500 499 The following GLOBAL variables always exist (so don't overwrite them!):
501 500 _i: stores previous input.
502 501 _ii: next previous.
503 502 _iii: next-next previous.
504 503 _ih : a list of all input _ih[n] is the input from line n.
505 504
506 505 Additionally, global variables named _i<n> are dynamically created (<n>
507 506 being the prompt counter), such that _i<n> == _ih[<n>]
508 507
509 508 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
510 509
511 510 You can create macros which contain multiple input lines from this history,
512 511 for later re-execution, with the %macro function.
513 512
514 513 The history function %hist allows you to see any part of your input history
515 514 by printing a range of the _i variables. Note that inputs which contain
516 515 magic functions (%) appear in the history with a prepended comment. This is
517 516 because they aren't really valid Python code, so you can't exec them.
518 517
519 518 * Output caching system:
520 519
521 520 For output that is returned from actions, a system similar to the input
522 521 cache exists but using _ instead of _i. Only actions that produce a result
523 522 (NOT assignments, for example) are cached. If you are familiar with
524 523 Mathematica, IPython's _ variables behave exactly like Mathematica's %
525 524 variables.
526 525
527 526 The following GLOBAL variables always exist (so don't overwrite them!):
528 527 _ (one underscore): previous output.
529 528 __ (two underscores): next previous.
530 529 ___ (three underscores): next-next previous.
531 530
532 531 Global variables named _<n> are dynamically created (<n> being the prompt
533 532 counter), such that the result of output <n> is always available as _<n>.
534 533
535 534 Finally, a global dictionary named _oh exists with entries for all lines
536 535 which generated output.
537 536
538 537 * Directory history:
539 538
540 539 Your history of visited directories is kept in the global list _dh, and the
541 540 magic %cd command can be used to go to any entry in that list.
542 541
543 542 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
544 543
545 544 1. Auto-parentheses
546 545 Callable objects (i.e. functions, methods, etc) can be invoked like
547 546 this (notice the commas between the arguments):
548 547 >>> callable_ob arg1, arg2, arg3
549 548 and the input will be translated to this:
550 549 --> callable_ob(arg1, arg2, arg3)
551 550 You can force auto-parentheses by using '/' as the first character
552 551 of a line. For example:
553 552 >>> /globals # becomes 'globals()'
554 553 Note that the '/' MUST be the first character on the line! This
555 554 won't work:
556 555 >>> print /globals # syntax error
557 556
558 557 In most cases the automatic algorithm should work, so you should
559 558 rarely need to explicitly invoke /. One notable exception is if you
560 559 are trying to call a function with a list of tuples as arguments (the
561 560 parenthesis will confuse IPython):
562 561 In [1]: zip (1,2,3),(4,5,6) # won't work
563 562 but this will work:
564 563 In [2]: /zip (1,2,3),(4,5,6)
565 564 ------> zip ((1,2,3),(4,5,6))
566 565 Out[2]= [(1, 4), (2, 5), (3, 6)]
567 566
568 567 IPython tells you that it has altered your command line by
569 568 displaying the new command line preceded by -->. e.g.:
570 569 In [18]: callable list
571 570 -------> callable (list)
572 571
573 572 2. Auto-Quoting
574 573 You can force auto-quoting of a function's arguments by using ',' as
575 574 the first character of a line. For example:
576 575 >>> ,my_function /home/me # becomes my_function("/home/me")
577 576
578 577 If you use ';' instead, the whole argument is quoted as a single
579 578 string (while ',' splits on whitespace):
580 579 >>> ,my_function a b c # becomes my_function("a","b","c")
581 580 >>> ;my_function a b c # becomes my_function("a b c")
582 581
583 582 Note that the ',' MUST be the first character on the line! This
584 583 won't work:
585 584 >>> x = ,my_function /home/me # syntax error
586 585 """
@@ -1,4562 +1,4567 b''
1 1 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
2 2
3 3 * IPython/iplib.py (handle_normal): add suport for multi-line
4 4 input with emtpy lines. This fixes
5 5 http://www.scipy.net/roundup/ipython/issue43 and a similar
6 6 discussion on the user list.
7 (edit_syntax_error): added support for automatically reopening the
8 editor if the file had a syntax error in it. Thanks to scottt who
9 provided the patch at:
10 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
11 version committed).
7 12
8 13 WARNING: a behavior change is necessarily introduced to support
9 14 blank lines: now a single blank line with whitespace does NOT
10 15 break the input loop, which means that when autoindent is on, by
11 16 default hitting return on the next (indented) line does NOT exit.
12 17
13 18 Instead, to exit a multiline input you can either have:
14 19
15 20 - TWO whitespace lines (just hit return again), or
16 21 - a single whitespace line of a different length than provided
17 22 by the autoindent (add or remove a space).
18 23
19 24 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
20 25 module to better organize all readline-related functionality.
21 26 I've deleted FlexCompleter and put all completion clases here.
22 27
23 28 * IPython/iplib.py (raw_input): improve indentation management.
24 29 It is now possible to paste indented code with autoindent on, and
25 30 the code is interpreted correctly (though it still looks bad on
26 31 screen, due to the line-oriented nature of ipython).
27 32 (MagicCompleter.complete): change behavior so that a TAB key on an
28 33 otherwise empty line actually inserts a tab, instead of completing
29 34 on the entire global namespace. This makes it easier to use the
30 35 TAB key for indentation. After a request by Hans Meine
31 36 <hans_meine-AT-gmx.net>
32 37 (_prefilter): add support so that typing plain 'exit' or 'quit'
33 38 does a sensible thing. Originally I tried to deviate as little as
34 39 possible from the default python behavior, but even that one may
35 40 change in this direction (thread on python-dev to that effect).
36 41 Regardless, ipython should do the right thing even if CPython's
37 42 '>>>' prompt doesn't.
38 43 (InteractiveShell): removed subclassing code.InteractiveConsole
39 44 class. By now we'd overridden just about all of its methods: I've
40 45 copied the remaining two over, and now ipython is a standalone
41 46 class. This will provide a clearer picture for the chainsaw
42 47 branch refactoring.
43 48
44 49 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
45 50
46 51 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
47 52 failures for objects which break when dir() is called on them.
48 53
49 54 * IPython/FlexCompleter.py (Completer.__init__): Added support for
50 55 distinct local and global namespaces in the completer API. This
51 56 change allows us top properly handle completion with distinct
52 57 scopes, including in embedded instances (this had never really
53 58 worked correctly).
54 59
55 60 Note: this introduces a change in the constructor for
56 61 MagicCompleter, as a new global_namespace parameter is now the
57 62 second argument (the others were bumped one position).
58 63
59 64 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
60 65
61 66 * IPython/iplib.py (embed_mainloop): fix tab-completion in
62 67 embedded instances (which can be done now thanks to Vivian's
63 68 frame-handling fixes for pdb).
64 69 (InteractiveShell.__init__): Fix namespace handling problem in
65 70 embedded instances. We were overwriting __main__ unconditionally,
66 71 and this should only be done for 'full' (non-embedded) IPython;
67 72 embedded instances must respect the caller's __main__. Thanks to
68 73 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
69 74
70 75 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
71 76
72 77 * setup.py: added download_url to setup(). This registers the
73 78 download address at PyPI, which is not only useful to humans
74 79 browsing the site, but is also picked up by setuptools (the Eggs
75 80 machinery). Thanks to Ville and R. Kern for the info/discussion
76 81 on this.
77 82
78 83 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
79 84
80 85 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
81 86 This brings a lot of nice functionality to the pdb mode, which now
82 87 has tab-completion, syntax highlighting, and better stack handling
83 88 than before. Many thanks to Vivian De Smedt
84 89 <vivian-AT-vdesmedt.com> for the original patches.
85 90
86 91 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
87 92
88 93 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
89 94 sequence to consistently accept the banner argument. The
90 95 inconsistency was tripping SAGE, thanks to Gary Zablackis
91 96 <gzabl-AT-yahoo.com> for the report.
92 97
93 98 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
94 99
95 100 * IPython/iplib.py (InteractiveShell.post_config_initialization):
96 101 Fix bug where a naked 'alias' call in the ipythonrc file would
97 102 cause a crash. Bug reported by Jorgen Stenarson.
98 103
99 104 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
100 105
101 106 * IPython/ipmaker.py (make_IPython): cleanups which should improve
102 107 startup time.
103 108
104 109 * IPython/iplib.py (runcode): my globals 'fix' for embedded
105 110 instances had introduced a bug with globals in normal code. Now
106 111 it's working in all cases.
107 112
108 113 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
109 114 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
110 115 has been introduced to set the default case sensitivity of the
111 116 searches. Users can still select either mode at runtime on a
112 117 per-search basis.
113 118
114 119 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
115 120
116 121 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
117 122 attributes in wildcard searches for subclasses. Modified version
118 123 of a patch by Jorgen.
119 124
120 125 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
121 126
122 127 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
123 128 embedded instances. I added a user_global_ns attribute to the
124 129 InteractiveShell class to handle this.
125 130
126 131 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
127 132
128 133 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
129 134 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
130 135 (reported under win32, but may happen also in other platforms).
131 136 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
132 137
133 138 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
134 139
135 140 * IPython/Magic.py (magic_psearch): new support for wildcard
136 141 patterns. Now, typing ?a*b will list all names which begin with a
137 142 and end in b, for example. The %psearch magic has full
138 143 docstrings. Many thanks to Jörgen Stenarson
139 144 <jorgen.stenarson-AT-bostream.nu>, author of the patches
140 145 implementing this functionality.
141 146
142 147 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
143 148
144 149 * Manual: fixed long-standing annoyance of double-dashes (as in
145 150 --prefix=~, for example) being stripped in the HTML version. This
146 151 is a latex2html bug, but a workaround was provided. Many thanks
147 152 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
148 153 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
149 154 rolling. This seemingly small issue had tripped a number of users
150 155 when first installing, so I'm glad to see it gone.
151 156
152 157 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
153 158
154 159 * IPython/Extensions/numeric_formats.py: fix missing import,
155 160 reported by Stephen Walton.
156 161
157 162 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
158 163
159 164 * IPython/demo.py: finish demo module, fully documented now.
160 165
161 166 * IPython/genutils.py (file_read): simple little utility to read a
162 167 file and ensure it's closed afterwards.
163 168
164 169 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
165 170
166 171 * IPython/demo.py (Demo.__init__): added support for individually
167 172 tagging blocks for automatic execution.
168 173
169 174 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
170 175 syntax-highlighted python sources, requested by John.
171 176
172 177 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
173 178
174 179 * IPython/demo.py (Demo.again): fix bug where again() blocks after
175 180 finishing.
176 181
177 182 * IPython/genutils.py (shlex_split): moved from Magic to here,
178 183 where all 2.2 compatibility stuff lives. I needed it for demo.py.
179 184
180 185 * IPython/demo.py (Demo.__init__): added support for silent
181 186 blocks, improved marks as regexps, docstrings written.
182 187 (Demo.__init__): better docstring, added support for sys.argv.
183 188
184 189 * IPython/genutils.py (marquee): little utility used by the demo
185 190 code, handy in general.
186 191
187 192 * IPython/demo.py (Demo.__init__): new class for interactive
188 193 demos. Not documented yet, I just wrote it in a hurry for
189 194 scipy'05. Will docstring later.
190 195
191 196 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
192 197
193 198 * IPython/Shell.py (sigint_handler): Drastic simplification which
194 199 also seems to make Ctrl-C work correctly across threads! This is
195 200 so simple, that I can't beleive I'd missed it before. Needs more
196 201 testing, though.
197 202 (KBINT): Never mind, revert changes. I'm sure I'd tried something
198 203 like this before...
199 204
200 205 * IPython/genutils.py (get_home_dir): add protection against
201 206 non-dirs in win32 registry.
202 207
203 208 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
204 209 bug where dict was mutated while iterating (pysh crash).
205 210
206 211 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
207 212
208 213 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
209 214 spurious newlines added by this routine. After a report by
210 215 F. Mantegazza.
211 216
212 217 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
213 218
214 219 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
215 220 calls. These were a leftover from the GTK 1.x days, and can cause
216 221 problems in certain cases (after a report by John Hunter).
217 222
218 223 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
219 224 os.getcwd() fails at init time. Thanks to patch from David Remahl
220 225 <chmod007-AT-mac.com>.
221 226 (InteractiveShell.__init__): prevent certain special magics from
222 227 being shadowed by aliases. Closes
223 228 http://www.scipy.net/roundup/ipython/issue41.
224 229
225 230 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
226 231
227 232 * IPython/iplib.py (InteractiveShell.complete): Added new
228 233 top-level completion method to expose the completion mechanism
229 234 beyond readline-based environments.
230 235
231 236 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
232 237
233 238 * tools/ipsvnc (svnversion): fix svnversion capture.
234 239
235 240 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
236 241 attribute to self, which was missing. Before, it was set by a
237 242 routine which in certain cases wasn't being called, so the
238 243 instance could end up missing the attribute. This caused a crash.
239 244 Closes http://www.scipy.net/roundup/ipython/issue40.
240 245
241 246 2005-08-16 Fernando Perez <fperez@colorado.edu>
242 247
243 248 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
244 249 contains non-string attribute. Closes
245 250 http://www.scipy.net/roundup/ipython/issue38.
246 251
247 252 2005-08-14 Fernando Perez <fperez@colorado.edu>
248 253
249 254 * tools/ipsvnc: Minor improvements, to add changeset info.
250 255
251 256 2005-08-12 Fernando Perez <fperez@colorado.edu>
252 257
253 258 * IPython/iplib.py (runsource): remove self.code_to_run_src
254 259 attribute. I realized this is nothing more than
255 260 '\n'.join(self.buffer), and having the same data in two different
256 261 places is just asking for synchronization bugs. This may impact
257 262 people who have custom exception handlers, so I need to warn
258 263 ipython-dev about it (F. Mantegazza may use them).
259 264
260 265 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
261 266
262 267 * IPython/genutils.py: fix 2.2 compatibility (generators)
263 268
264 269 2005-07-18 Fernando Perez <fperez@colorado.edu>
265 270
266 271 * IPython/genutils.py (get_home_dir): fix to help users with
267 272 invalid $HOME under win32.
268 273
269 274 2005-07-17 Fernando Perez <fperez@colorado.edu>
270 275
271 276 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
272 277 some old hacks and clean up a bit other routines; code should be
273 278 simpler and a bit faster.
274 279
275 280 * IPython/iplib.py (interact): removed some last-resort attempts
276 281 to survive broken stdout/stderr. That code was only making it
277 282 harder to abstract out the i/o (necessary for gui integration),
278 283 and the crashes it could prevent were extremely rare in practice
279 284 (besides being fully user-induced in a pretty violent manner).
280 285
281 286 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
282 287 Nothing major yet, but the code is simpler to read; this should
283 288 make it easier to do more serious modifications in the future.
284 289
285 290 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
286 291 which broke in .15 (thanks to a report by Ville).
287 292
288 293 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
289 294 be quite correct, I know next to nothing about unicode). This
290 295 will allow unicode strings to be used in prompts, amongst other
291 296 cases. It also will prevent ipython from crashing when unicode
292 297 shows up unexpectedly in many places. If ascii encoding fails, we
293 298 assume utf_8. Currently the encoding is not a user-visible
294 299 setting, though it could be made so if there is demand for it.
295 300
296 301 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
297 302
298 303 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
299 304
300 305 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
301 306
302 307 * IPython/genutils.py: Add 2.2 compatibility here, so all other
303 308 code can work transparently for 2.2/2.3.
304 309
305 310 2005-07-16 Fernando Perez <fperez@colorado.edu>
306 311
307 312 * IPython/ultraTB.py (ExceptionColors): Make a global variable
308 313 out of the color scheme table used for coloring exception
309 314 tracebacks. This allows user code to add new schemes at runtime.
310 315 This is a minimally modified version of the patch at
311 316 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
312 317 for the contribution.
313 318
314 319 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
315 320 slightly modified version of the patch in
316 321 http://www.scipy.net/roundup/ipython/issue34, which also allows me
317 322 to remove the previous try/except solution (which was costlier).
318 323 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
319 324
320 325 2005-06-08 Fernando Perez <fperez@colorado.edu>
321 326
322 327 * IPython/iplib.py (write/write_err): Add methods to abstract all
323 328 I/O a bit more.
324 329
325 330 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
326 331 warning, reported by Aric Hagberg, fix by JD Hunter.
327 332
328 333 2005-06-02 *** Released version 0.6.15
329 334
330 335 2005-06-01 Fernando Perez <fperez@colorado.edu>
331 336
332 337 * IPython/iplib.py (MagicCompleter.file_matches): Fix
333 338 tab-completion of filenames within open-quoted strings. Note that
334 339 this requires that in ~/.ipython/ipythonrc, users change the
335 340 readline delimiters configuration to read:
336 341
337 342 readline_remove_delims -/~
338 343
339 344
340 345 2005-05-31 *** Released version 0.6.14
341 346
342 347 2005-05-29 Fernando Perez <fperez@colorado.edu>
343 348
344 349 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
345 350 with files not on the filesystem. Reported by Eliyahu Sandler
346 351 <eli@gondolin.net>
347 352
348 353 2005-05-22 Fernando Perez <fperez@colorado.edu>
349 354
350 355 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
351 356 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
352 357
353 358 2005-05-19 Fernando Perez <fperez@colorado.edu>
354 359
355 360 * IPython/iplib.py (safe_execfile): close a file which could be
356 361 left open (causing problems in win32, which locks open files).
357 362 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
358 363
359 364 2005-05-18 Fernando Perez <fperez@colorado.edu>
360 365
361 366 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
362 367 keyword arguments correctly to safe_execfile().
363 368
364 369 2005-05-13 Fernando Perez <fperez@colorado.edu>
365 370
366 371 * ipython.1: Added info about Qt to manpage, and threads warning
367 372 to usage page (invoked with --help).
368 373
369 374 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
370 375 new matcher (it goes at the end of the priority list) to do
371 376 tab-completion on named function arguments. Submitted by George
372 377 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
373 378 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
374 379 for more details.
375 380
376 381 * IPython/Magic.py (magic_run): Added new -e flag to ignore
377 382 SystemExit exceptions in the script being run. Thanks to a report
378 383 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
379 384 producing very annoying behavior when running unit tests.
380 385
381 386 2005-05-12 Fernando Perez <fperez@colorado.edu>
382 387
383 388 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
384 389 which I'd broken (again) due to a changed regexp. In the process,
385 390 added ';' as an escape to auto-quote the whole line without
386 391 splitting its arguments. Thanks to a report by Jerry McRae
387 392 <qrs0xyc02-AT-sneakemail.com>.
388 393
389 394 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
390 395 possible crashes caused by a TokenError. Reported by Ed Schofield
391 396 <schofield-AT-ftw.at>.
392 397
393 398 2005-05-06 Fernando Perez <fperez@colorado.edu>
394 399
395 400 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
396 401
397 402 2005-04-29 Fernando Perez <fperez@colorado.edu>
398 403
399 404 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
400 405 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
401 406 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
402 407 which provides support for Qt interactive usage (similar to the
403 408 existing one for WX and GTK). This had been often requested.
404 409
405 410 2005-04-14 *** Released version 0.6.13
406 411
407 412 2005-04-08 Fernando Perez <fperez@colorado.edu>
408 413
409 414 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
410 415 from _ofind, which gets called on almost every input line. Now,
411 416 we only try to get docstrings if they are actually going to be
412 417 used (the overhead of fetching unnecessary docstrings can be
413 418 noticeable for certain objects, such as Pyro proxies).
414 419
415 420 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
416 421 for completers. For some reason I had been passing them the state
417 422 variable, which completers never actually need, and was in
418 423 conflict with the rlcompleter API. Custom completers ONLY need to
419 424 take the text parameter.
420 425
421 426 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
422 427 work correctly in pysh. I've also moved all the logic which used
423 428 to be in pysh.py here, which will prevent problems with future
424 429 upgrades. However, this time I must warn users to update their
425 430 pysh profile to include the line
426 431
427 432 import_all IPython.Extensions.InterpreterExec
428 433
429 434 because otherwise things won't work for them. They MUST also
430 435 delete pysh.py and the line
431 436
432 437 execfile pysh.py
433 438
434 439 from their ipythonrc-pysh.
435 440
436 441 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
437 442 robust in the face of objects whose dir() returns non-strings
438 443 (which it shouldn't, but some broken libs like ITK do). Thanks to
439 444 a patch by John Hunter (implemented differently, though). Also
440 445 minor improvements by using .extend instead of + on lists.
441 446
442 447 * pysh.py:
443 448
444 449 2005-04-06 Fernando Perez <fperez@colorado.edu>
445 450
446 451 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
447 452 by default, so that all users benefit from it. Those who don't
448 453 want it can still turn it off.
449 454
450 455 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
451 456 config file, I'd forgotten about this, so users were getting it
452 457 off by default.
453 458
454 459 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
455 460 consistency. Now magics can be called in multiline statements,
456 461 and python variables can be expanded in magic calls via $var.
457 462 This makes the magic system behave just like aliases or !system
458 463 calls.
459 464
460 465 2005-03-28 Fernando Perez <fperez@colorado.edu>
461 466
462 467 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
463 468 expensive string additions for building command. Add support for
464 469 trailing ';' when autocall is used.
465 470
466 471 2005-03-26 Fernando Perez <fperez@colorado.edu>
467 472
468 473 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
469 474 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
470 475 ipython.el robust against prompts with any number of spaces
471 476 (including 0) after the ':' character.
472 477
473 478 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
474 479 continuation prompt, which misled users to think the line was
475 480 already indented. Closes debian Bug#300847, reported to me by
476 481 Norbert Tretkowski <tretkowski-AT-inittab.de>.
477 482
478 483 2005-03-23 Fernando Perez <fperez@colorado.edu>
479 484
480 485 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
481 486 properly aligned if they have embedded newlines.
482 487
483 488 * IPython/iplib.py (runlines): Add a public method to expose
484 489 IPython's code execution machinery, so that users can run strings
485 490 as if they had been typed at the prompt interactively.
486 491 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
487 492 methods which can call the system shell, but with python variable
488 493 expansion. The three such methods are: __IPYTHON__.system,
489 494 .getoutput and .getoutputerror. These need to be documented in a
490 495 'public API' section (to be written) of the manual.
491 496
492 497 2005-03-20 Fernando Perez <fperez@colorado.edu>
493 498
494 499 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
495 500 for custom exception handling. This is quite powerful, and it
496 501 allows for user-installable exception handlers which can trap
497 502 custom exceptions at runtime and treat them separately from
498 503 IPython's default mechanisms. At the request of Frédéric
499 504 Mantegazza <mantegazza-AT-ill.fr>.
500 505 (InteractiveShell.set_custom_completer): public API function to
501 506 add new completers at runtime.
502 507
503 508 2005-03-19 Fernando Perez <fperez@colorado.edu>
504 509
505 510 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
506 511 allow objects which provide their docstrings via non-standard
507 512 mechanisms (like Pyro proxies) to still be inspected by ipython's
508 513 ? system.
509 514
510 515 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
511 516 automatic capture system. I tried quite hard to make it work
512 517 reliably, and simply failed. I tried many combinations with the
513 518 subprocess module, but eventually nothing worked in all needed
514 519 cases (not blocking stdin for the child, duplicating stdout
515 520 without blocking, etc). The new %sc/%sx still do capture to these
516 521 magical list/string objects which make shell use much more
517 522 conveninent, so not all is lost.
518 523
519 524 XXX - FIX MANUAL for the change above!
520 525
521 526 (runsource): I copied code.py's runsource() into ipython to modify
522 527 it a bit. Now the code object and source to be executed are
523 528 stored in ipython. This makes this info accessible to third-party
524 529 tools, like custom exception handlers. After a request by Frédéric
525 530 Mantegazza <mantegazza-AT-ill.fr>.
526 531
527 532 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
528 533 history-search via readline (like C-p/C-n). I'd wanted this for a
529 534 long time, but only recently found out how to do it. For users
530 535 who already have their ipythonrc files made and want this, just
531 536 add:
532 537
533 538 readline_parse_and_bind "\e[A": history-search-backward
534 539 readline_parse_and_bind "\e[B": history-search-forward
535 540
536 541 2005-03-18 Fernando Perez <fperez@colorado.edu>
537 542
538 543 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
539 544 LSString and SList classes which allow transparent conversions
540 545 between list mode and whitespace-separated string.
541 546 (magic_r): Fix recursion problem in %r.
542 547
543 548 * IPython/genutils.py (LSString): New class to be used for
544 549 automatic storage of the results of all alias/system calls in _o
545 550 and _e (stdout/err). These provide a .l/.list attribute which
546 551 does automatic splitting on newlines. This means that for most
547 552 uses, you'll never need to do capturing of output with %sc/%sx
548 553 anymore, since ipython keeps this always done for you. Note that
549 554 only the LAST results are stored, the _o/e variables are
550 555 overwritten on each call. If you need to save their contents
551 556 further, simply bind them to any other name.
552 557
553 558 2005-03-17 Fernando Perez <fperez@colorado.edu>
554 559
555 560 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
556 561 prompt namespace handling.
557 562
558 563 2005-03-16 Fernando Perez <fperez@colorado.edu>
559 564
560 565 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
561 566 classic prompts to be '>>> ' (final space was missing, and it
562 567 trips the emacs python mode).
563 568 (BasePrompt.__str__): Added safe support for dynamic prompt
564 569 strings. Now you can set your prompt string to be '$x', and the
565 570 value of x will be printed from your interactive namespace. The
566 571 interpolation syntax includes the full Itpl support, so
567 572 ${foo()+x+bar()} is a valid prompt string now, and the function
568 573 calls will be made at runtime.
569 574
570 575 2005-03-15 Fernando Perez <fperez@colorado.edu>
571 576
572 577 * IPython/Magic.py (magic_history): renamed %hist to %history, to
573 578 avoid name clashes in pylab. %hist still works, it just forwards
574 579 the call to %history.
575 580
576 581 2005-03-02 *** Released version 0.6.12
577 582
578 583 2005-03-02 Fernando Perez <fperez@colorado.edu>
579 584
580 585 * IPython/iplib.py (handle_magic): log magic calls properly as
581 586 ipmagic() function calls.
582 587
583 588 * IPython/Magic.py (magic_time): Improved %time to support
584 589 statements and provide wall-clock as well as CPU time.
585 590
586 591 2005-02-27 Fernando Perez <fperez@colorado.edu>
587 592
588 593 * IPython/hooks.py: New hooks module, to expose user-modifiable
589 594 IPython functionality in a clean manner. For now only the editor
590 595 hook is actually written, and other thigns which I intend to turn
591 596 into proper hooks aren't yet there. The display and prefilter
592 597 stuff, for example, should be hooks. But at least now the
593 598 framework is in place, and the rest can be moved here with more
594 599 time later. IPython had had a .hooks variable for a long time for
595 600 this purpose, but I'd never actually used it for anything.
596 601
597 602 2005-02-26 Fernando Perez <fperez@colorado.edu>
598 603
599 604 * IPython/ipmaker.py (make_IPython): make the default ipython
600 605 directory be called _ipython under win32, to follow more the
601 606 naming peculiarities of that platform (where buggy software like
602 607 Visual Sourcesafe breaks with .named directories). Reported by
603 608 Ville Vainio.
604 609
605 610 2005-02-23 Fernando Perez <fperez@colorado.edu>
606 611
607 612 * IPython/iplib.py (InteractiveShell.__init__): removed a few
608 613 auto_aliases for win32 which were causing problems. Users can
609 614 define the ones they personally like.
610 615
611 616 2005-02-21 Fernando Perez <fperez@colorado.edu>
612 617
613 618 * IPython/Magic.py (magic_time): new magic to time execution of
614 619 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
615 620
616 621 2005-02-19 Fernando Perez <fperez@colorado.edu>
617 622
618 623 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
619 624 into keys (for prompts, for example).
620 625
621 626 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
622 627 prompts in case users want them. This introduces a small behavior
623 628 change: ipython does not automatically add a space to all prompts
624 629 anymore. To get the old prompts with a space, users should add it
625 630 manually to their ipythonrc file, so for example prompt_in1 should
626 631 now read 'In [\#]: ' instead of 'In [\#]:'.
627 632 (BasePrompt.__init__): New option prompts_pad_left (only in rc
628 633 file) to control left-padding of secondary prompts.
629 634
630 635 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
631 636 the profiler can't be imported. Fix for Debian, which removed
632 637 profile.py because of License issues. I applied a slightly
633 638 modified version of the original Debian patch at
634 639 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
635 640
636 641 2005-02-17 Fernando Perez <fperez@colorado.edu>
637 642
638 643 * IPython/genutils.py (native_line_ends): Fix bug which would
639 644 cause improper line-ends under win32 b/c I was not opening files
640 645 in binary mode. Bug report and fix thanks to Ville.
641 646
642 647 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
643 648 trying to catch spurious foo[1] autocalls. My fix actually broke
644 649 ',/' autoquote/call with explicit escape (bad regexp).
645 650
646 651 2005-02-15 *** Released version 0.6.11
647 652
648 653 2005-02-14 Fernando Perez <fperez@colorado.edu>
649 654
650 655 * IPython/background_jobs.py: New background job management
651 656 subsystem. This is implemented via a new set of classes, and
652 657 IPython now provides a builtin 'jobs' object for background job
653 658 execution. A convenience %bg magic serves as a lightweight
654 659 frontend for starting the more common type of calls. This was
655 660 inspired by discussions with B. Granger and the BackgroundCommand
656 661 class described in the book Python Scripting for Computational
657 662 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
658 663 (although ultimately no code from this text was used, as IPython's
659 664 system is a separate implementation).
660 665
661 666 * IPython/iplib.py (MagicCompleter.python_matches): add new option
662 667 to control the completion of single/double underscore names
663 668 separately. As documented in the example ipytonrc file, the
664 669 readline_omit__names variable can now be set to 2, to omit even
665 670 single underscore names. Thanks to a patch by Brian Wong
666 671 <BrianWong-AT-AirgoNetworks.Com>.
667 672 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
668 673 be autocalled as foo([1]) if foo were callable. A problem for
669 674 things which are both callable and implement __getitem__.
670 675 (init_readline): Fix autoindentation for win32. Thanks to a patch
671 676 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
672 677
673 678 2005-02-12 Fernando Perez <fperez@colorado.edu>
674 679
675 680 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
676 681 which I had written long ago to sort out user error messages which
677 682 may occur during startup. This seemed like a good idea initially,
678 683 but it has proven a disaster in retrospect. I don't want to
679 684 change much code for now, so my fix is to set the internal 'debug'
680 685 flag to true everywhere, whose only job was precisely to control
681 686 this subsystem. This closes issue 28 (as well as avoiding all
682 687 sorts of strange hangups which occur from time to time).
683 688
684 689 2005-02-07 Fernando Perez <fperez@colorado.edu>
685 690
686 691 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
687 692 previous call produced a syntax error.
688 693
689 694 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
690 695 classes without constructor.
691 696
692 697 2005-02-06 Fernando Perez <fperez@colorado.edu>
693 698
694 699 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
695 700 completions with the results of each matcher, so we return results
696 701 to the user from all namespaces. This breaks with ipython
697 702 tradition, but I think it's a nicer behavior. Now you get all
698 703 possible completions listed, from all possible namespaces (python,
699 704 filesystem, magics...) After a request by John Hunter
700 705 <jdhunter-AT-nitace.bsd.uchicago.edu>.
701 706
702 707 2005-02-05 Fernando Perez <fperez@colorado.edu>
703 708
704 709 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
705 710 the call had quote characters in it (the quotes were stripped).
706 711
707 712 2005-01-31 Fernando Perez <fperez@colorado.edu>
708 713
709 714 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
710 715 Itpl.itpl() to make the code more robust against psyco
711 716 optimizations.
712 717
713 718 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
714 719 of causing an exception. Quicker, cleaner.
715 720
716 721 2005-01-28 Fernando Perez <fperez@colorado.edu>
717 722
718 723 * scripts/ipython_win_post_install.py (install): hardcode
719 724 sys.prefix+'python.exe' as the executable path. It turns out that
720 725 during the post-installation run, sys.executable resolves to the
721 726 name of the binary installer! I should report this as a distutils
722 727 bug, I think. I updated the .10 release with this tiny fix, to
723 728 avoid annoying the lists further.
724 729
725 730 2005-01-27 *** Released version 0.6.10
726 731
727 732 2005-01-27 Fernando Perez <fperez@colorado.edu>
728 733
729 734 * IPython/numutils.py (norm): Added 'inf' as optional name for
730 735 L-infinity norm, included references to mathworld.com for vector
731 736 norm definitions.
732 737 (amin/amax): added amin/amax for array min/max. Similar to what
733 738 pylab ships with after the recent reorganization of names.
734 739 (spike/spike_odd): removed deprecated spike/spike_odd functions.
735 740
736 741 * ipython.el: committed Alex's recent fixes and improvements.
737 742 Tested with python-mode from CVS, and it looks excellent. Since
738 743 python-mode hasn't released anything in a while, I'm temporarily
739 744 putting a copy of today's CVS (v 4.70) of python-mode in:
740 745 http://ipython.scipy.org/tmp/python-mode.el
741 746
742 747 * scripts/ipython_win_post_install.py (install): Win32 fix to use
743 748 sys.executable for the executable name, instead of assuming it's
744 749 called 'python.exe' (the post-installer would have produced broken
745 750 setups on systems with a differently named python binary).
746 751
747 752 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
748 753 references to os.linesep, to make the code more
749 754 platform-independent. This is also part of the win32 coloring
750 755 fixes.
751 756
752 757 * IPython/genutils.py (page_dumb): Remove attempts to chop long
753 758 lines, which actually cause coloring bugs because the length of
754 759 the line is very difficult to correctly compute with embedded
755 760 escapes. This was the source of all the coloring problems under
756 761 Win32. I think that _finally_, Win32 users have a properly
757 762 working ipython in all respects. This would never have happened
758 763 if not for Gary Bishop and Viktor Ransmayr's great help and work.
759 764
760 765 2005-01-26 *** Released version 0.6.9
761 766
762 767 2005-01-25 Fernando Perez <fperez@colorado.edu>
763 768
764 769 * setup.py: finally, we have a true Windows installer, thanks to
765 770 the excellent work of Viktor Ransmayr
766 771 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
767 772 Windows users. The setup routine is quite a bit cleaner thanks to
768 773 this, and the post-install script uses the proper functions to
769 774 allow a clean de-installation using the standard Windows Control
770 775 Panel.
771 776
772 777 * IPython/genutils.py (get_home_dir): changed to use the $HOME
773 778 environment variable under all OSes (including win32) if
774 779 available. This will give consistency to win32 users who have set
775 780 this variable for any reason. If os.environ['HOME'] fails, the
776 781 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
777 782
778 783 2005-01-24 Fernando Perez <fperez@colorado.edu>
779 784
780 785 * IPython/numutils.py (empty_like): add empty_like(), similar to
781 786 zeros_like() but taking advantage of the new empty() Numeric routine.
782 787
783 788 2005-01-23 *** Released version 0.6.8
784 789
785 790 2005-01-22 Fernando Perez <fperez@colorado.edu>
786 791
787 792 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
788 793 automatic show() calls. After discussing things with JDH, it
789 794 turns out there are too many corner cases where this can go wrong.
790 795 It's best not to try to be 'too smart', and simply have ipython
791 796 reproduce as much as possible the default behavior of a normal
792 797 python shell.
793 798
794 799 * IPython/iplib.py (InteractiveShell.__init__): Modified the
795 800 line-splitting regexp and _prefilter() to avoid calling getattr()
796 801 on assignments. This closes
797 802 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
798 803 readline uses getattr(), so a simple <TAB> keypress is still
799 804 enough to trigger getattr() calls on an object.
800 805
801 806 2005-01-21 Fernando Perez <fperez@colorado.edu>
802 807
803 808 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
804 809 docstring under pylab so it doesn't mask the original.
805 810
806 811 2005-01-21 *** Released version 0.6.7
807 812
808 813 2005-01-21 Fernando Perez <fperez@colorado.edu>
809 814
810 815 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
811 816 signal handling for win32 users in multithreaded mode.
812 817
813 818 2005-01-17 Fernando Perez <fperez@colorado.edu>
814 819
815 820 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
816 821 instances with no __init__. After a crash report by Norbert Nemec
817 822 <Norbert-AT-nemec-online.de>.
818 823
819 824 2005-01-14 Fernando Perez <fperez@colorado.edu>
820 825
821 826 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
822 827 names for verbose exceptions, when multiple dotted names and the
823 828 'parent' object were present on the same line.
824 829
825 830 2005-01-11 Fernando Perez <fperez@colorado.edu>
826 831
827 832 * IPython/genutils.py (flag_calls): new utility to trap and flag
828 833 calls in functions. I need it to clean up matplotlib support.
829 834 Also removed some deprecated code in genutils.
830 835
831 836 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
832 837 that matplotlib scripts called with %run, which don't call show()
833 838 themselves, still have their plotting windows open.
834 839
835 840 2005-01-05 Fernando Perez <fperez@colorado.edu>
836 841
837 842 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
838 843 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
839 844
840 845 2004-12-19 Fernando Perez <fperez@colorado.edu>
841 846
842 847 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
843 848 parent_runcode, which was an eyesore. The same result can be
844 849 obtained with Python's regular superclass mechanisms.
845 850
846 851 2004-12-17 Fernando Perez <fperez@colorado.edu>
847 852
848 853 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
849 854 reported by Prabhu.
850 855 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
851 856 sys.stderr) instead of explicitly calling sys.stderr. This helps
852 857 maintain our I/O abstractions clean, for future GUI embeddings.
853 858
854 859 * IPython/genutils.py (info): added new utility for sys.stderr
855 860 unified info message handling (thin wrapper around warn()).
856 861
857 862 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
858 863 composite (dotted) names on verbose exceptions.
859 864 (VerboseTB.nullrepr): harden against another kind of errors which
860 865 Python's inspect module can trigger, and which were crashing
861 866 IPython. Thanks to a report by Marco Lombardi
862 867 <mlombard-AT-ma010192.hq.eso.org>.
863 868
864 869 2004-12-13 *** Released version 0.6.6
865 870
866 871 2004-12-12 Fernando Perez <fperez@colorado.edu>
867 872
868 873 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
869 874 generated by pygtk upon initialization if it was built without
870 875 threads (for matplotlib users). After a crash reported by
871 876 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
872 877
873 878 * IPython/ipmaker.py (make_IPython): fix small bug in the
874 879 import_some parameter for multiple imports.
875 880
876 881 * IPython/iplib.py (ipmagic): simplified the interface of
877 882 ipmagic() to take a single string argument, just as it would be
878 883 typed at the IPython cmd line.
879 884 (ipalias): Added new ipalias() with an interface identical to
880 885 ipmagic(). This completes exposing a pure python interface to the
881 886 alias and magic system, which can be used in loops or more complex
882 887 code where IPython's automatic line mangling is not active.
883 888
884 889 * IPython/genutils.py (timing): changed interface of timing to
885 890 simply run code once, which is the most common case. timings()
886 891 remains unchanged, for the cases where you want multiple runs.
887 892
888 893 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
889 894 bug where Python2.2 crashes with exec'ing code which does not end
890 895 in a single newline. Python 2.3 is OK, so I hadn't noticed this
891 896 before.
892 897
893 898 2004-12-10 Fernando Perez <fperez@colorado.edu>
894 899
895 900 * IPython/Magic.py (Magic.magic_prun): changed name of option from
896 901 -t to -T, to accomodate the new -t flag in %run (the %run and
897 902 %prun options are kind of intermixed, and it's not easy to change
898 903 this with the limitations of python's getopt).
899 904
900 905 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
901 906 the execution of scripts. It's not as fine-tuned as timeit.py,
902 907 but it works from inside ipython (and under 2.2, which lacks
903 908 timeit.py). Optionally a number of runs > 1 can be given for
904 909 timing very short-running code.
905 910
906 911 * IPython/genutils.py (uniq_stable): new routine which returns a
907 912 list of unique elements in any iterable, but in stable order of
908 913 appearance. I needed this for the ultraTB fixes, and it's a handy
909 914 utility.
910 915
911 916 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
912 917 dotted names in Verbose exceptions. This had been broken since
913 918 the very start, now x.y will properly be printed in a Verbose
914 919 traceback, instead of x being shown and y appearing always as an
915 920 'undefined global'. Getting this to work was a bit tricky,
916 921 because by default python tokenizers are stateless. Saved by
917 922 python's ability to easily add a bit of state to an arbitrary
918 923 function (without needing to build a full-blown callable object).
919 924
920 925 Also big cleanup of this code, which had horrendous runtime
921 926 lookups of zillions of attributes for colorization. Moved all
922 927 this code into a few templates, which make it cleaner and quicker.
923 928
924 929 Printout quality was also improved for Verbose exceptions: one
925 930 variable per line, and memory addresses are printed (this can be
926 931 quite handy in nasty debugging situations, which is what Verbose
927 932 is for).
928 933
929 934 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
930 935 the command line as scripts to be loaded by embedded instances.
931 936 Doing so has the potential for an infinite recursion if there are
932 937 exceptions thrown in the process. This fixes a strange crash
933 938 reported by Philippe MULLER <muller-AT-irit.fr>.
934 939
935 940 2004-12-09 Fernando Perez <fperez@colorado.edu>
936 941
937 942 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
938 943 to reflect new names in matplotlib, which now expose the
939 944 matlab-compatible interface via a pylab module instead of the
940 945 'matlab' name. The new code is backwards compatible, so users of
941 946 all matplotlib versions are OK. Patch by J. Hunter.
942 947
943 948 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
944 949 of __init__ docstrings for instances (class docstrings are already
945 950 automatically printed). Instances with customized docstrings
946 951 (indep. of the class) are also recognized and all 3 separate
947 952 docstrings are printed (instance, class, constructor). After some
948 953 comments/suggestions by J. Hunter.
949 954
950 955 2004-12-05 Fernando Perez <fperez@colorado.edu>
951 956
952 957 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
953 958 warnings when tab-completion fails and triggers an exception.
954 959
955 960 2004-12-03 Fernando Perez <fperez@colorado.edu>
956 961
957 962 * IPython/Magic.py (magic_prun): Fix bug where an exception would
958 963 be triggered when using 'run -p'. An incorrect option flag was
959 964 being set ('d' instead of 'D').
960 965 (manpage): fix missing escaped \- sign.
961 966
962 967 2004-11-30 *** Released version 0.6.5
963 968
964 969 2004-11-30 Fernando Perez <fperez@colorado.edu>
965 970
966 971 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
967 972 setting with -d option.
968 973
969 974 * setup.py (docfiles): Fix problem where the doc glob I was using
970 975 was COMPLETELY BROKEN. It was giving the right files by pure
971 976 accident, but failed once I tried to include ipython.el. Note:
972 977 glob() does NOT allow you to do exclusion on multiple endings!
973 978
974 979 2004-11-29 Fernando Perez <fperez@colorado.edu>
975 980
976 981 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
977 982 the manpage as the source. Better formatting & consistency.
978 983
979 984 * IPython/Magic.py (magic_run): Added new -d option, to run
980 985 scripts under the control of the python pdb debugger. Note that
981 986 this required changing the %prun option -d to -D, to avoid a clash
982 987 (since %run must pass options to %prun, and getopt is too dumb to
983 988 handle options with string values with embedded spaces). Thanks
984 989 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
985 990 (magic_who_ls): added type matching to %who and %whos, so that one
986 991 can filter their output to only include variables of certain
987 992 types. Another suggestion by Matthew.
988 993 (magic_whos): Added memory summaries in kb and Mb for arrays.
989 994 (magic_who): Improve formatting (break lines every 9 vars).
990 995
991 996 2004-11-28 Fernando Perez <fperez@colorado.edu>
992 997
993 998 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
994 999 cache when empty lines were present.
995 1000
996 1001 2004-11-24 Fernando Perez <fperez@colorado.edu>
997 1002
998 1003 * IPython/usage.py (__doc__): document the re-activated threading
999 1004 options for WX and GTK.
1000 1005
1001 1006 2004-11-23 Fernando Perez <fperez@colorado.edu>
1002 1007
1003 1008 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1004 1009 the -wthread and -gthread options, along with a new -tk one to try
1005 1010 and coordinate Tk threading with wx/gtk. The tk support is very
1006 1011 platform dependent, since it seems to require Tcl and Tk to be
1007 1012 built with threads (Fedora1/2 appears NOT to have it, but in
1008 1013 Prabhu's Debian boxes it works OK). But even with some Tk
1009 1014 limitations, this is a great improvement.
1010 1015
1011 1016 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1012 1017 info in user prompts. Patch by Prabhu.
1013 1018
1014 1019 2004-11-18 Fernando Perez <fperez@colorado.edu>
1015 1020
1016 1021 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1017 1022 EOFErrors and bail, to avoid infinite loops if a non-terminating
1018 1023 file is fed into ipython. Patch submitted in issue 19 by user,
1019 1024 many thanks.
1020 1025
1021 1026 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1022 1027 autoquote/parens in continuation prompts, which can cause lots of
1023 1028 problems. Closes roundup issue 20.
1024 1029
1025 1030 2004-11-17 Fernando Perez <fperez@colorado.edu>
1026 1031
1027 1032 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1028 1033 reported as debian bug #280505. I'm not sure my local changelog
1029 1034 entry has the proper debian format (Jack?).
1030 1035
1031 1036 2004-11-08 *** Released version 0.6.4
1032 1037
1033 1038 2004-11-08 Fernando Perez <fperez@colorado.edu>
1034 1039
1035 1040 * IPython/iplib.py (init_readline): Fix exit message for Windows
1036 1041 when readline is active. Thanks to a report by Eric Jones
1037 1042 <eric-AT-enthought.com>.
1038 1043
1039 1044 2004-11-07 Fernando Perez <fperez@colorado.edu>
1040 1045
1041 1046 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1042 1047 sometimes seen by win2k/cygwin users.
1043 1048
1044 1049 2004-11-06 Fernando Perez <fperez@colorado.edu>
1045 1050
1046 1051 * IPython/iplib.py (interact): Change the handling of %Exit from
1047 1052 trying to propagate a SystemExit to an internal ipython flag.
1048 1053 This is less elegant than using Python's exception mechanism, but
1049 1054 I can't get that to work reliably with threads, so under -pylab
1050 1055 %Exit was hanging IPython. Cross-thread exception handling is
1051 1056 really a bitch. Thaks to a bug report by Stephen Walton
1052 1057 <stephen.walton-AT-csun.edu>.
1053 1058
1054 1059 2004-11-04 Fernando Perez <fperez@colorado.edu>
1055 1060
1056 1061 * IPython/iplib.py (raw_input_original): store a pointer to the
1057 1062 true raw_input to harden against code which can modify it
1058 1063 (wx.py.PyShell does this and would otherwise crash ipython).
1059 1064 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1060 1065
1061 1066 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1062 1067 Ctrl-C problem, which does not mess up the input line.
1063 1068
1064 1069 2004-11-03 Fernando Perez <fperez@colorado.edu>
1065 1070
1066 1071 * IPython/Release.py: Changed licensing to BSD, in all files.
1067 1072 (name): lowercase name for tarball/RPM release.
1068 1073
1069 1074 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1070 1075 use throughout ipython.
1071 1076
1072 1077 * IPython/Magic.py (Magic._ofind): Switch to using the new
1073 1078 OInspect.getdoc() function.
1074 1079
1075 1080 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1076 1081 of the line currently being canceled via Ctrl-C. It's extremely
1077 1082 ugly, but I don't know how to do it better (the problem is one of
1078 1083 handling cross-thread exceptions).
1079 1084
1080 1085 2004-10-28 Fernando Perez <fperez@colorado.edu>
1081 1086
1082 1087 * IPython/Shell.py (signal_handler): add signal handlers to trap
1083 1088 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1084 1089 report by Francesc Alted.
1085 1090
1086 1091 2004-10-21 Fernando Perez <fperez@colorado.edu>
1087 1092
1088 1093 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1089 1094 to % for pysh syntax extensions.
1090 1095
1091 1096 2004-10-09 Fernando Perez <fperez@colorado.edu>
1092 1097
1093 1098 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1094 1099 arrays to print a more useful summary, without calling str(arr).
1095 1100 This avoids the problem of extremely lengthy computations which
1096 1101 occur if arr is large, and appear to the user as a system lockup
1097 1102 with 100% cpu activity. After a suggestion by Kristian Sandberg
1098 1103 <Kristian.Sandberg@colorado.edu>.
1099 1104 (Magic.__init__): fix bug in global magic escapes not being
1100 1105 correctly set.
1101 1106
1102 1107 2004-10-08 Fernando Perez <fperez@colorado.edu>
1103 1108
1104 1109 * IPython/Magic.py (__license__): change to absolute imports of
1105 1110 ipython's own internal packages, to start adapting to the absolute
1106 1111 import requirement of PEP-328.
1107 1112
1108 1113 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1109 1114 files, and standardize author/license marks through the Release
1110 1115 module instead of having per/file stuff (except for files with
1111 1116 particular licenses, like the MIT/PSF-licensed codes).
1112 1117
1113 1118 * IPython/Debugger.py: remove dead code for python 2.1
1114 1119
1115 1120 2004-10-04 Fernando Perez <fperez@colorado.edu>
1116 1121
1117 1122 * IPython/iplib.py (ipmagic): New function for accessing magics
1118 1123 via a normal python function call.
1119 1124
1120 1125 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1121 1126 from '@' to '%', to accomodate the new @decorator syntax of python
1122 1127 2.4.
1123 1128
1124 1129 2004-09-29 Fernando Perez <fperez@colorado.edu>
1125 1130
1126 1131 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1127 1132 matplotlib.use to prevent running scripts which try to switch
1128 1133 interactive backends from within ipython. This will just crash
1129 1134 the python interpreter, so we can't allow it (but a detailed error
1130 1135 is given to the user).
1131 1136
1132 1137 2004-09-28 Fernando Perez <fperez@colorado.edu>
1133 1138
1134 1139 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1135 1140 matplotlib-related fixes so that using @run with non-matplotlib
1136 1141 scripts doesn't pop up spurious plot windows. This requires
1137 1142 matplotlib >= 0.63, where I had to make some changes as well.
1138 1143
1139 1144 * IPython/ipmaker.py (make_IPython): update version requirement to
1140 1145 python 2.2.
1141 1146
1142 1147 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1143 1148 banner arg for embedded customization.
1144 1149
1145 1150 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1146 1151 explicit uses of __IP as the IPython's instance name. Now things
1147 1152 are properly handled via the shell.name value. The actual code
1148 1153 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1149 1154 is much better than before. I'll clean things completely when the
1150 1155 magic stuff gets a real overhaul.
1151 1156
1152 1157 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1153 1158 minor changes to debian dir.
1154 1159
1155 1160 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1156 1161 pointer to the shell itself in the interactive namespace even when
1157 1162 a user-supplied dict is provided. This is needed for embedding
1158 1163 purposes (found by tests with Michel Sanner).
1159 1164
1160 1165 2004-09-27 Fernando Perez <fperez@colorado.edu>
1161 1166
1162 1167 * IPython/UserConfig/ipythonrc: remove []{} from
1163 1168 readline_remove_delims, so that things like [modname.<TAB> do
1164 1169 proper completion. This disables [].TAB, but that's a less common
1165 1170 case than module names in list comprehensions, for example.
1166 1171 Thanks to a report by Andrea Riciputi.
1167 1172
1168 1173 2004-09-09 Fernando Perez <fperez@colorado.edu>
1169 1174
1170 1175 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1171 1176 blocking problems in win32 and osx. Fix by John.
1172 1177
1173 1178 2004-09-08 Fernando Perez <fperez@colorado.edu>
1174 1179
1175 1180 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1176 1181 for Win32 and OSX. Fix by John Hunter.
1177 1182
1178 1183 2004-08-30 *** Released version 0.6.3
1179 1184
1180 1185 2004-08-30 Fernando Perez <fperez@colorado.edu>
1181 1186
1182 1187 * setup.py (isfile): Add manpages to list of dependent files to be
1183 1188 updated.
1184 1189
1185 1190 2004-08-27 Fernando Perez <fperez@colorado.edu>
1186 1191
1187 1192 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1188 1193 for now. They don't really work with standalone WX/GTK code
1189 1194 (though matplotlib IS working fine with both of those backends).
1190 1195 This will neeed much more testing. I disabled most things with
1191 1196 comments, so turning it back on later should be pretty easy.
1192 1197
1193 1198 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1194 1199 autocalling of expressions like r'foo', by modifying the line
1195 1200 split regexp. Closes
1196 1201 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1197 1202 Riley <ipythonbugs-AT-sabi.net>.
1198 1203 (InteractiveShell.mainloop): honor --nobanner with banner
1199 1204 extensions.
1200 1205
1201 1206 * IPython/Shell.py: Significant refactoring of all classes, so
1202 1207 that we can really support ALL matplotlib backends and threading
1203 1208 models (John spotted a bug with Tk which required this). Now we
1204 1209 should support single-threaded, WX-threads and GTK-threads, both
1205 1210 for generic code and for matplotlib.
1206 1211
1207 1212 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1208 1213 -pylab, to simplify things for users. Will also remove the pylab
1209 1214 profile, since now all of matplotlib configuration is directly
1210 1215 handled here. This also reduces startup time.
1211 1216
1212 1217 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1213 1218 shell wasn't being correctly called. Also in IPShellWX.
1214 1219
1215 1220 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1216 1221 fine-tune banner.
1217 1222
1218 1223 * IPython/numutils.py (spike): Deprecate these spike functions,
1219 1224 delete (long deprecated) gnuplot_exec handler.
1220 1225
1221 1226 2004-08-26 Fernando Perez <fperez@colorado.edu>
1222 1227
1223 1228 * ipython.1: Update for threading options, plus some others which
1224 1229 were missing.
1225 1230
1226 1231 * IPython/ipmaker.py (__call__): Added -wthread option for
1227 1232 wxpython thread handling. Make sure threading options are only
1228 1233 valid at the command line.
1229 1234
1230 1235 * scripts/ipython: moved shell selection into a factory function
1231 1236 in Shell.py, to keep the starter script to a minimum.
1232 1237
1233 1238 2004-08-25 Fernando Perez <fperez@colorado.edu>
1234 1239
1235 1240 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1236 1241 John. Along with some recent changes he made to matplotlib, the
1237 1242 next versions of both systems should work very well together.
1238 1243
1239 1244 2004-08-24 Fernando Perez <fperez@colorado.edu>
1240 1245
1241 1246 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1242 1247 tried to switch the profiling to using hotshot, but I'm getting
1243 1248 strange errors from prof.runctx() there. I may be misreading the
1244 1249 docs, but it looks weird. For now the profiling code will
1245 1250 continue to use the standard profiler.
1246 1251
1247 1252 2004-08-23 Fernando Perez <fperez@colorado.edu>
1248 1253
1249 1254 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1250 1255 threaded shell, by John Hunter. It's not quite ready yet, but
1251 1256 close.
1252 1257
1253 1258 2004-08-22 Fernando Perez <fperez@colorado.edu>
1254 1259
1255 1260 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1256 1261 in Magic and ultraTB.
1257 1262
1258 1263 * ipython.1: document threading options in manpage.
1259 1264
1260 1265 * scripts/ipython: Changed name of -thread option to -gthread,
1261 1266 since this is GTK specific. I want to leave the door open for a
1262 1267 -wthread option for WX, which will most likely be necessary. This
1263 1268 change affects usage and ipmaker as well.
1264 1269
1265 1270 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1266 1271 handle the matplotlib shell issues. Code by John Hunter
1267 1272 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1268 1273 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1269 1274 broken (and disabled for end users) for now, but it puts the
1270 1275 infrastructure in place.
1271 1276
1272 1277 2004-08-21 Fernando Perez <fperez@colorado.edu>
1273 1278
1274 1279 * ipythonrc-pylab: Add matplotlib support.
1275 1280
1276 1281 * matplotlib_config.py: new files for matplotlib support, part of
1277 1282 the pylab profile.
1278 1283
1279 1284 * IPython/usage.py (__doc__): documented the threading options.
1280 1285
1281 1286 2004-08-20 Fernando Perez <fperez@colorado.edu>
1282 1287
1283 1288 * ipython: Modified the main calling routine to handle the -thread
1284 1289 and -mpthread options. This needs to be done as a top-level hack,
1285 1290 because it determines which class to instantiate for IPython
1286 1291 itself.
1287 1292
1288 1293 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1289 1294 classes to support multithreaded GTK operation without blocking,
1290 1295 and matplotlib with all backends. This is a lot of still very
1291 1296 experimental code, and threads are tricky. So it may still have a
1292 1297 few rough edges... This code owes a lot to
1293 1298 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1294 1299 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1295 1300 to John Hunter for all the matplotlib work.
1296 1301
1297 1302 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1298 1303 options for gtk thread and matplotlib support.
1299 1304
1300 1305 2004-08-16 Fernando Perez <fperez@colorado.edu>
1301 1306
1302 1307 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1303 1308 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1304 1309 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1305 1310
1306 1311 2004-08-11 Fernando Perez <fperez@colorado.edu>
1307 1312
1308 1313 * setup.py (isfile): Fix build so documentation gets updated for
1309 1314 rpms (it was only done for .tgz builds).
1310 1315
1311 1316 2004-08-10 Fernando Perez <fperez@colorado.edu>
1312 1317
1313 1318 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1314 1319
1315 1320 * iplib.py : Silence syntax error exceptions in tab-completion.
1316 1321
1317 1322 2004-08-05 Fernando Perez <fperez@colorado.edu>
1318 1323
1319 1324 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1320 1325 'color off' mark for continuation prompts. This was causing long
1321 1326 continuation lines to mis-wrap.
1322 1327
1323 1328 2004-08-01 Fernando Perez <fperez@colorado.edu>
1324 1329
1325 1330 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1326 1331 for building ipython to be a parameter. All this is necessary
1327 1332 right now to have a multithreaded version, but this insane
1328 1333 non-design will be cleaned up soon. For now, it's a hack that
1329 1334 works.
1330 1335
1331 1336 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1332 1337 args in various places. No bugs so far, but it's a dangerous
1333 1338 practice.
1334 1339
1335 1340 2004-07-31 Fernando Perez <fperez@colorado.edu>
1336 1341
1337 1342 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1338 1343 fix completion of files with dots in their names under most
1339 1344 profiles (pysh was OK because the completion order is different).
1340 1345
1341 1346 2004-07-27 Fernando Perez <fperez@colorado.edu>
1342 1347
1343 1348 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1344 1349 keywords manually, b/c the one in keyword.py was removed in python
1345 1350 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1346 1351 This is NOT a bug under python 2.3 and earlier.
1347 1352
1348 1353 2004-07-26 Fernando Perez <fperez@colorado.edu>
1349 1354
1350 1355 * IPython/ultraTB.py (VerboseTB.text): Add another
1351 1356 linecache.checkcache() call to try to prevent inspect.py from
1352 1357 crashing under python 2.3. I think this fixes
1353 1358 http://www.scipy.net/roundup/ipython/issue17.
1354 1359
1355 1360 2004-07-26 *** Released version 0.6.2
1356 1361
1357 1362 2004-07-26 Fernando Perez <fperez@colorado.edu>
1358 1363
1359 1364 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1360 1365 fail for any number.
1361 1366 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1362 1367 empty bookmarks.
1363 1368
1364 1369 2004-07-26 *** Released version 0.6.1
1365 1370
1366 1371 2004-07-26 Fernando Perez <fperez@colorado.edu>
1367 1372
1368 1373 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1369 1374
1370 1375 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1371 1376 escaping '()[]{}' in filenames.
1372 1377
1373 1378 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1374 1379 Python 2.2 users who lack a proper shlex.split.
1375 1380
1376 1381 2004-07-19 Fernando Perez <fperez@colorado.edu>
1377 1382
1378 1383 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1379 1384 for reading readline's init file. I follow the normal chain:
1380 1385 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1381 1386 report by Mike Heeter. This closes
1382 1387 http://www.scipy.net/roundup/ipython/issue16.
1383 1388
1384 1389 2004-07-18 Fernando Perez <fperez@colorado.edu>
1385 1390
1386 1391 * IPython/iplib.py (__init__): Add better handling of '\' under
1387 1392 Win32 for filenames. After a patch by Ville.
1388 1393
1389 1394 2004-07-17 Fernando Perez <fperez@colorado.edu>
1390 1395
1391 1396 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1392 1397 autocalling would be triggered for 'foo is bar' if foo is
1393 1398 callable. I also cleaned up the autocall detection code to use a
1394 1399 regexp, which is faster. Bug reported by Alexander Schmolck.
1395 1400
1396 1401 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1397 1402 '?' in them would confuse the help system. Reported by Alex
1398 1403 Schmolck.
1399 1404
1400 1405 2004-07-16 Fernando Perez <fperez@colorado.edu>
1401 1406
1402 1407 * IPython/GnuplotInteractive.py (__all__): added plot2.
1403 1408
1404 1409 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1405 1410 plotting dictionaries, lists or tuples of 1d arrays.
1406 1411
1407 1412 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1408 1413 optimizations.
1409 1414
1410 1415 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1411 1416 the information which was there from Janko's original IPP code:
1412 1417
1413 1418 03.05.99 20:53 porto.ifm.uni-kiel.de
1414 1419 --Started changelog.
1415 1420 --make clear do what it say it does
1416 1421 --added pretty output of lines from inputcache
1417 1422 --Made Logger a mixin class, simplifies handling of switches
1418 1423 --Added own completer class. .string<TAB> expands to last history
1419 1424 line which starts with string. The new expansion is also present
1420 1425 with Ctrl-r from the readline library. But this shows, who this
1421 1426 can be done for other cases.
1422 1427 --Added convention that all shell functions should accept a
1423 1428 parameter_string This opens the door for different behaviour for
1424 1429 each function. @cd is a good example of this.
1425 1430
1426 1431 04.05.99 12:12 porto.ifm.uni-kiel.de
1427 1432 --added logfile rotation
1428 1433 --added new mainloop method which freezes first the namespace
1429 1434
1430 1435 07.05.99 21:24 porto.ifm.uni-kiel.de
1431 1436 --added the docreader classes. Now there is a help system.
1432 1437 -This is only a first try. Currently it's not easy to put new
1433 1438 stuff in the indices. But this is the way to go. Info would be
1434 1439 better, but HTML is every where and not everybody has an info
1435 1440 system installed and it's not so easy to change html-docs to info.
1436 1441 --added global logfile option
1437 1442 --there is now a hook for object inspection method pinfo needs to
1438 1443 be provided for this. Can be reached by two '??'.
1439 1444
1440 1445 08.05.99 20:51 porto.ifm.uni-kiel.de
1441 1446 --added a README
1442 1447 --bug in rc file. Something has changed so functions in the rc
1443 1448 file need to reference the shell and not self. Not clear if it's a
1444 1449 bug or feature.
1445 1450 --changed rc file for new behavior
1446 1451
1447 1452 2004-07-15 Fernando Perez <fperez@colorado.edu>
1448 1453
1449 1454 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1450 1455 cache was falling out of sync in bizarre manners when multi-line
1451 1456 input was present. Minor optimizations and cleanup.
1452 1457
1453 1458 (Logger): Remove old Changelog info for cleanup. This is the
1454 1459 information which was there from Janko's original code:
1455 1460
1456 1461 Changes to Logger: - made the default log filename a parameter
1457 1462
1458 1463 - put a check for lines beginning with !@? in log(). Needed
1459 1464 (even if the handlers properly log their lines) for mid-session
1460 1465 logging activation to work properly. Without this, lines logged
1461 1466 in mid session, which get read from the cache, would end up
1462 1467 'bare' (with !@? in the open) in the log. Now they are caught
1463 1468 and prepended with a #.
1464 1469
1465 1470 * IPython/iplib.py (InteractiveShell.init_readline): added check
1466 1471 in case MagicCompleter fails to be defined, so we don't crash.
1467 1472
1468 1473 2004-07-13 Fernando Perez <fperez@colorado.edu>
1469 1474
1470 1475 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1471 1476 of EPS if the requested filename ends in '.eps'.
1472 1477
1473 1478 2004-07-04 Fernando Perez <fperez@colorado.edu>
1474 1479
1475 1480 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1476 1481 escaping of quotes when calling the shell.
1477 1482
1478 1483 2004-07-02 Fernando Perez <fperez@colorado.edu>
1479 1484
1480 1485 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1481 1486 gettext not working because we were clobbering '_'. Fixes
1482 1487 http://www.scipy.net/roundup/ipython/issue6.
1483 1488
1484 1489 2004-07-01 Fernando Perez <fperez@colorado.edu>
1485 1490
1486 1491 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1487 1492 into @cd. Patch by Ville.
1488 1493
1489 1494 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1490 1495 new function to store things after ipmaker runs. Patch by Ville.
1491 1496 Eventually this will go away once ipmaker is removed and the class
1492 1497 gets cleaned up, but for now it's ok. Key functionality here is
1493 1498 the addition of the persistent storage mechanism, a dict for
1494 1499 keeping data across sessions (for now just bookmarks, but more can
1495 1500 be implemented later).
1496 1501
1497 1502 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1498 1503 persistent across sections. Patch by Ville, I modified it
1499 1504 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1500 1505 added a '-l' option to list all bookmarks.
1501 1506
1502 1507 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1503 1508 center for cleanup. Registered with atexit.register(). I moved
1504 1509 here the old exit_cleanup(). After a patch by Ville.
1505 1510
1506 1511 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1507 1512 characters in the hacked shlex_split for python 2.2.
1508 1513
1509 1514 * IPython/iplib.py (file_matches): more fixes to filenames with
1510 1515 whitespace in them. It's not perfect, but limitations in python's
1511 1516 readline make it impossible to go further.
1512 1517
1513 1518 2004-06-29 Fernando Perez <fperez@colorado.edu>
1514 1519
1515 1520 * IPython/iplib.py (file_matches): escape whitespace correctly in
1516 1521 filename completions. Bug reported by Ville.
1517 1522
1518 1523 2004-06-28 Fernando Perez <fperez@colorado.edu>
1519 1524
1520 1525 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1521 1526 the history file will be called 'history-PROFNAME' (or just
1522 1527 'history' if no profile is loaded). I was getting annoyed at
1523 1528 getting my Numerical work history clobbered by pysh sessions.
1524 1529
1525 1530 * IPython/iplib.py (InteractiveShell.__init__): Internal
1526 1531 getoutputerror() function so that we can honor the system_verbose
1527 1532 flag for _all_ system calls. I also added escaping of #
1528 1533 characters here to avoid confusing Itpl.
1529 1534
1530 1535 * IPython/Magic.py (shlex_split): removed call to shell in
1531 1536 parse_options and replaced it with shlex.split(). The annoying
1532 1537 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1533 1538 to backport it from 2.3, with several frail hacks (the shlex
1534 1539 module is rather limited in 2.2). Thanks to a suggestion by Ville
1535 1540 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1536 1541 problem.
1537 1542
1538 1543 (Magic.magic_system_verbose): new toggle to print the actual
1539 1544 system calls made by ipython. Mainly for debugging purposes.
1540 1545
1541 1546 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1542 1547 doesn't support persistence. Reported (and fix suggested) by
1543 1548 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1544 1549
1545 1550 2004-06-26 Fernando Perez <fperez@colorado.edu>
1546 1551
1547 1552 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1548 1553 continue prompts.
1549 1554
1550 1555 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1551 1556 function (basically a big docstring) and a few more things here to
1552 1557 speedup startup. pysh.py is now very lightweight. We want because
1553 1558 it gets execfile'd, while InterpreterExec gets imported, so
1554 1559 byte-compilation saves time.
1555 1560
1556 1561 2004-06-25 Fernando Perez <fperez@colorado.edu>
1557 1562
1558 1563 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1559 1564 -NUM', which was recently broken.
1560 1565
1561 1566 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1562 1567 in multi-line input (but not !!, which doesn't make sense there).
1563 1568
1564 1569 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1565 1570 It's just too useful, and people can turn it off in the less
1566 1571 common cases where it's a problem.
1567 1572
1568 1573 2004-06-24 Fernando Perez <fperez@colorado.edu>
1569 1574
1570 1575 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1571 1576 special syntaxes (like alias calling) is now allied in multi-line
1572 1577 input. This is still _very_ experimental, but it's necessary for
1573 1578 efficient shell usage combining python looping syntax with system
1574 1579 calls. For now it's restricted to aliases, I don't think it
1575 1580 really even makes sense to have this for magics.
1576 1581
1577 1582 2004-06-23 Fernando Perez <fperez@colorado.edu>
1578 1583
1579 1584 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1580 1585 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1581 1586
1582 1587 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1583 1588 extensions under Windows (after code sent by Gary Bishop). The
1584 1589 extensions considered 'executable' are stored in IPython's rc
1585 1590 structure as win_exec_ext.
1586 1591
1587 1592 * IPython/genutils.py (shell): new function, like system() but
1588 1593 without return value. Very useful for interactive shell work.
1589 1594
1590 1595 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1591 1596 delete aliases.
1592 1597
1593 1598 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1594 1599 sure that the alias table doesn't contain python keywords.
1595 1600
1596 1601 2004-06-21 Fernando Perez <fperez@colorado.edu>
1597 1602
1598 1603 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1599 1604 non-existent items are found in $PATH. Reported by Thorsten.
1600 1605
1601 1606 2004-06-20 Fernando Perez <fperez@colorado.edu>
1602 1607
1603 1608 * IPython/iplib.py (complete): modified the completer so that the
1604 1609 order of priorities can be easily changed at runtime.
1605 1610
1606 1611 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1607 1612 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1608 1613
1609 1614 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1610 1615 expand Python variables prepended with $ in all system calls. The
1611 1616 same was done to InteractiveShell.handle_shell_escape. Now all
1612 1617 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1613 1618 expansion of python variables and expressions according to the
1614 1619 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1615 1620
1616 1621 Though PEP-215 has been rejected, a similar (but simpler) one
1617 1622 seems like it will go into Python 2.4, PEP-292 -
1618 1623 http://www.python.org/peps/pep-0292.html.
1619 1624
1620 1625 I'll keep the full syntax of PEP-215, since IPython has since the
1621 1626 start used Ka-Ping Yee's reference implementation discussed there
1622 1627 (Itpl), and I actually like the powerful semantics it offers.
1623 1628
1624 1629 In order to access normal shell variables, the $ has to be escaped
1625 1630 via an extra $. For example:
1626 1631
1627 1632 In [7]: PATH='a python variable'
1628 1633
1629 1634 In [8]: !echo $PATH
1630 1635 a python variable
1631 1636
1632 1637 In [9]: !echo $$PATH
1633 1638 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1634 1639
1635 1640 (Magic.parse_options): escape $ so the shell doesn't evaluate
1636 1641 things prematurely.
1637 1642
1638 1643 * IPython/iplib.py (InteractiveShell.call_alias): added the
1639 1644 ability for aliases to expand python variables via $.
1640 1645
1641 1646 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1642 1647 system, now there's a @rehash/@rehashx pair of magics. These work
1643 1648 like the csh rehash command, and can be invoked at any time. They
1644 1649 build a table of aliases to everything in the user's $PATH
1645 1650 (@rehash uses everything, @rehashx is slower but only adds
1646 1651 executable files). With this, the pysh.py-based shell profile can
1647 1652 now simply call rehash upon startup, and full access to all
1648 1653 programs in the user's path is obtained.
1649 1654
1650 1655 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1651 1656 functionality is now fully in place. I removed the old dynamic
1652 1657 code generation based approach, in favor of a much lighter one
1653 1658 based on a simple dict. The advantage is that this allows me to
1654 1659 now have thousands of aliases with negligible cost (unthinkable
1655 1660 with the old system).
1656 1661
1657 1662 2004-06-19 Fernando Perez <fperez@colorado.edu>
1658 1663
1659 1664 * IPython/iplib.py (__init__): extended MagicCompleter class to
1660 1665 also complete (last in priority) on user aliases.
1661 1666
1662 1667 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1663 1668 call to eval.
1664 1669 (ItplNS.__init__): Added a new class which functions like Itpl,
1665 1670 but allows configuring the namespace for the evaluation to occur
1666 1671 in.
1667 1672
1668 1673 2004-06-18 Fernando Perez <fperez@colorado.edu>
1669 1674
1670 1675 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1671 1676 better message when 'exit' or 'quit' are typed (a common newbie
1672 1677 confusion).
1673 1678
1674 1679 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1675 1680 check for Windows users.
1676 1681
1677 1682 * IPython/iplib.py (InteractiveShell.user_setup): removed
1678 1683 disabling of colors for Windows. I'll test at runtime and issue a
1679 1684 warning if Gary's readline isn't found, as to nudge users to
1680 1685 download it.
1681 1686
1682 1687 2004-06-16 Fernando Perez <fperez@colorado.edu>
1683 1688
1684 1689 * IPython/genutils.py (Stream.__init__): changed to print errors
1685 1690 to sys.stderr. I had a circular dependency here. Now it's
1686 1691 possible to run ipython as IDLE's shell (consider this pre-alpha,
1687 1692 since true stdout things end up in the starting terminal instead
1688 1693 of IDLE's out).
1689 1694
1690 1695 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1691 1696 users who haven't # updated their prompt_in2 definitions. Remove
1692 1697 eventually.
1693 1698 (multiple_replace): added credit to original ASPN recipe.
1694 1699
1695 1700 2004-06-15 Fernando Perez <fperez@colorado.edu>
1696 1701
1697 1702 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1698 1703 list of auto-defined aliases.
1699 1704
1700 1705 2004-06-13 Fernando Perez <fperez@colorado.edu>
1701 1706
1702 1707 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1703 1708 install was really requested (so setup.py can be used for other
1704 1709 things under Windows).
1705 1710
1706 1711 2004-06-10 Fernando Perez <fperez@colorado.edu>
1707 1712
1708 1713 * IPython/Logger.py (Logger.create_log): Manually remove any old
1709 1714 backup, since os.remove may fail under Windows. Fixes bug
1710 1715 reported by Thorsten.
1711 1716
1712 1717 2004-06-09 Fernando Perez <fperez@colorado.edu>
1713 1718
1714 1719 * examples/example-embed.py: fixed all references to %n (replaced
1715 1720 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1716 1721 for all examples and the manual as well.
1717 1722
1718 1723 2004-06-08 Fernando Perez <fperez@colorado.edu>
1719 1724
1720 1725 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1721 1726 alignment and color management. All 3 prompt subsystems now
1722 1727 inherit from BasePrompt.
1723 1728
1724 1729 * tools/release: updates for windows installer build and tag rpms
1725 1730 with python version (since paths are fixed).
1726 1731
1727 1732 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1728 1733 which will become eventually obsolete. Also fixed the default
1729 1734 prompt_in2 to use \D, so at least new users start with the correct
1730 1735 defaults.
1731 1736 WARNING: Users with existing ipythonrc files will need to apply
1732 1737 this fix manually!
1733 1738
1734 1739 * setup.py: make windows installer (.exe). This is finally the
1735 1740 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1736 1741 which I hadn't included because it required Python 2.3 (or recent
1737 1742 distutils).
1738 1743
1739 1744 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1740 1745 usage of new '\D' escape.
1741 1746
1742 1747 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1743 1748 lacks os.getuid())
1744 1749 (CachedOutput.set_colors): Added the ability to turn coloring
1745 1750 on/off with @colors even for manually defined prompt colors. It
1746 1751 uses a nasty global, but it works safely and via the generic color
1747 1752 handling mechanism.
1748 1753 (Prompt2.__init__): Introduced new escape '\D' for continuation
1749 1754 prompts. It represents the counter ('\#') as dots.
1750 1755 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1751 1756 need to update their ipythonrc files and replace '%n' with '\D' in
1752 1757 their prompt_in2 settings everywhere. Sorry, but there's
1753 1758 otherwise no clean way to get all prompts to properly align. The
1754 1759 ipythonrc shipped with IPython has been updated.
1755 1760
1756 1761 2004-06-07 Fernando Perez <fperez@colorado.edu>
1757 1762
1758 1763 * setup.py (isfile): Pass local_icons option to latex2html, so the
1759 1764 resulting HTML file is self-contained. Thanks to
1760 1765 dryice-AT-liu.com.cn for the tip.
1761 1766
1762 1767 * pysh.py: I created a new profile 'shell', which implements a
1763 1768 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1764 1769 system shell, nor will it become one anytime soon. It's mainly
1765 1770 meant to illustrate the use of the new flexible bash-like prompts.
1766 1771 I guess it could be used by hardy souls for true shell management,
1767 1772 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1768 1773 profile. This uses the InterpreterExec extension provided by
1769 1774 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1770 1775
1771 1776 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1772 1777 auto-align itself with the length of the previous input prompt
1773 1778 (taking into account the invisible color escapes).
1774 1779 (CachedOutput.__init__): Large restructuring of this class. Now
1775 1780 all three prompts (primary1, primary2, output) are proper objects,
1776 1781 managed by the 'parent' CachedOutput class. The code is still a
1777 1782 bit hackish (all prompts share state via a pointer to the cache),
1778 1783 but it's overall far cleaner than before.
1779 1784
1780 1785 * IPython/genutils.py (getoutputerror): modified to add verbose,
1781 1786 debug and header options. This makes the interface of all getout*
1782 1787 functions uniform.
1783 1788 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1784 1789
1785 1790 * IPython/Magic.py (Magic.default_option): added a function to
1786 1791 allow registering default options for any magic command. This
1787 1792 makes it easy to have profiles which customize the magics globally
1788 1793 for a certain use. The values set through this function are
1789 1794 picked up by the parse_options() method, which all magics should
1790 1795 use to parse their options.
1791 1796
1792 1797 * IPython/genutils.py (warn): modified the warnings framework to
1793 1798 use the Term I/O class. I'm trying to slowly unify all of
1794 1799 IPython's I/O operations to pass through Term.
1795 1800
1796 1801 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1797 1802 the secondary prompt to correctly match the length of the primary
1798 1803 one for any prompt. Now multi-line code will properly line up
1799 1804 even for path dependent prompts, such as the new ones available
1800 1805 via the prompt_specials.
1801 1806
1802 1807 2004-06-06 Fernando Perez <fperez@colorado.edu>
1803 1808
1804 1809 * IPython/Prompts.py (prompt_specials): Added the ability to have
1805 1810 bash-like special sequences in the prompts, which get
1806 1811 automatically expanded. Things like hostname, current working
1807 1812 directory and username are implemented already, but it's easy to
1808 1813 add more in the future. Thanks to a patch by W.J. van der Laan
1809 1814 <gnufnork-AT-hetdigitalegat.nl>
1810 1815 (prompt_specials): Added color support for prompt strings, so
1811 1816 users can define arbitrary color setups for their prompts.
1812 1817
1813 1818 2004-06-05 Fernando Perez <fperez@colorado.edu>
1814 1819
1815 1820 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1816 1821 code to load Gary Bishop's readline and configure it
1817 1822 automatically. Thanks to Gary for help on this.
1818 1823
1819 1824 2004-06-01 Fernando Perez <fperez@colorado.edu>
1820 1825
1821 1826 * IPython/Logger.py (Logger.create_log): fix bug for logging
1822 1827 with no filename (previous fix was incomplete).
1823 1828
1824 1829 2004-05-25 Fernando Perez <fperez@colorado.edu>
1825 1830
1826 1831 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1827 1832 parens would get passed to the shell.
1828 1833
1829 1834 2004-05-20 Fernando Perez <fperez@colorado.edu>
1830 1835
1831 1836 * IPython/Magic.py (Magic.magic_prun): changed default profile
1832 1837 sort order to 'time' (the more common profiling need).
1833 1838
1834 1839 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1835 1840 so that source code shown is guaranteed in sync with the file on
1836 1841 disk (also changed in psource). Similar fix to the one for
1837 1842 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1838 1843 <yann.ledu-AT-noos.fr>.
1839 1844
1840 1845 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1841 1846 with a single option would not be correctly parsed. Closes
1842 1847 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1843 1848 introduced in 0.6.0 (on 2004-05-06).
1844 1849
1845 1850 2004-05-13 *** Released version 0.6.0
1846 1851
1847 1852 2004-05-13 Fernando Perez <fperez@colorado.edu>
1848 1853
1849 1854 * debian/: Added debian/ directory to CVS, so that debian support
1850 1855 is publicly accessible. The debian package is maintained by Jack
1851 1856 Moffit <jack-AT-xiph.org>.
1852 1857
1853 1858 * Documentation: included the notes about an ipython-based system
1854 1859 shell (the hypothetical 'pysh') into the new_design.pdf document,
1855 1860 so that these ideas get distributed to users along with the
1856 1861 official documentation.
1857 1862
1858 1863 2004-05-10 Fernando Perez <fperez@colorado.edu>
1859 1864
1860 1865 * IPython/Logger.py (Logger.create_log): fix recently introduced
1861 1866 bug (misindented line) where logstart would fail when not given an
1862 1867 explicit filename.
1863 1868
1864 1869 2004-05-09 Fernando Perez <fperez@colorado.edu>
1865 1870
1866 1871 * IPython/Magic.py (Magic.parse_options): skip system call when
1867 1872 there are no options to look for. Faster, cleaner for the common
1868 1873 case.
1869 1874
1870 1875 * Documentation: many updates to the manual: describing Windows
1871 1876 support better, Gnuplot updates, credits, misc small stuff. Also
1872 1877 updated the new_design doc a bit.
1873 1878
1874 1879 2004-05-06 *** Released version 0.6.0.rc1
1875 1880
1876 1881 2004-05-06 Fernando Perez <fperez@colorado.edu>
1877 1882
1878 1883 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1879 1884 operations to use the vastly more efficient list/''.join() method.
1880 1885 (FormattedTB.text): Fix
1881 1886 http://www.scipy.net/roundup/ipython/issue12 - exception source
1882 1887 extract not updated after reload. Thanks to Mike Salib
1883 1888 <msalib-AT-mit.edu> for pinning the source of the problem.
1884 1889 Fortunately, the solution works inside ipython and doesn't require
1885 1890 any changes to python proper.
1886 1891
1887 1892 * IPython/Magic.py (Magic.parse_options): Improved to process the
1888 1893 argument list as a true shell would (by actually using the
1889 1894 underlying system shell). This way, all @magics automatically get
1890 1895 shell expansion for variables. Thanks to a comment by Alex
1891 1896 Schmolck.
1892 1897
1893 1898 2004-04-04 Fernando Perez <fperez@colorado.edu>
1894 1899
1895 1900 * IPython/iplib.py (InteractiveShell.interact): Added a special
1896 1901 trap for a debugger quit exception, which is basically impossible
1897 1902 to handle by normal mechanisms, given what pdb does to the stack.
1898 1903 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1899 1904
1900 1905 2004-04-03 Fernando Perez <fperez@colorado.edu>
1901 1906
1902 1907 * IPython/genutils.py (Term): Standardized the names of the Term
1903 1908 class streams to cin/cout/cerr, following C++ naming conventions
1904 1909 (I can't use in/out/err because 'in' is not a valid attribute
1905 1910 name).
1906 1911
1907 1912 * IPython/iplib.py (InteractiveShell.interact): don't increment
1908 1913 the prompt if there's no user input. By Daniel 'Dang' Griffith
1909 1914 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
1910 1915 Francois Pinard.
1911 1916
1912 1917 2004-04-02 Fernando Perez <fperez@colorado.edu>
1913 1918
1914 1919 * IPython/genutils.py (Stream.__init__): Modified to survive at
1915 1920 least importing in contexts where stdin/out/err aren't true file
1916 1921 objects, such as PyCrust (they lack fileno() and mode). However,
1917 1922 the recovery facilities which rely on these things existing will
1918 1923 not work.
1919 1924
1920 1925 2004-04-01 Fernando Perez <fperez@colorado.edu>
1921 1926
1922 1927 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
1923 1928 use the new getoutputerror() function, so it properly
1924 1929 distinguishes stdout/err.
1925 1930
1926 1931 * IPython/genutils.py (getoutputerror): added a function to
1927 1932 capture separately the standard output and error of a command.
1928 1933 After a comment from dang on the mailing lists. This code is
1929 1934 basically a modified version of commands.getstatusoutput(), from
1930 1935 the standard library.
1931 1936
1932 1937 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
1933 1938 '!!' as a special syntax (shorthand) to access @sx.
1934 1939
1935 1940 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
1936 1941 command and return its output as a list split on '\n'.
1937 1942
1938 1943 2004-03-31 Fernando Perez <fperez@colorado.edu>
1939 1944
1940 1945 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
1941 1946 method to dictionaries used as FakeModule instances if they lack
1942 1947 it. At least pydoc in python2.3 breaks for runtime-defined
1943 1948 functions without this hack. At some point I need to _really_
1944 1949 understand what FakeModule is doing, because it's a gross hack.
1945 1950 But it solves Arnd's problem for now...
1946 1951
1947 1952 2004-02-27 Fernando Perez <fperez@colorado.edu>
1948 1953
1949 1954 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
1950 1955 mode would behave erratically. Also increased the number of
1951 1956 possible logs in rotate mod to 999. Thanks to Rod Holland
1952 1957 <rhh@StructureLABS.com> for the report and fixes.
1953 1958
1954 1959 2004-02-26 Fernando Perez <fperez@colorado.edu>
1955 1960
1956 1961 * IPython/genutils.py (page): Check that the curses module really
1957 1962 has the initscr attribute before trying to use it. For some
1958 1963 reason, the Solaris curses module is missing this. I think this
1959 1964 should be considered a Solaris python bug, but I'm not sure.
1960 1965
1961 1966 2004-01-17 Fernando Perez <fperez@colorado.edu>
1962 1967
1963 1968 * IPython/genutils.py (Stream.__init__): Changes to try to make
1964 1969 ipython robust against stdin/out/err being closed by the user.
1965 1970 This is 'user error' (and blocks a normal python session, at least
1966 1971 the stdout case). However, Ipython should be able to survive such
1967 1972 instances of abuse as gracefully as possible. To simplify the
1968 1973 coding and maintain compatibility with Gary Bishop's Term
1969 1974 contributions, I've made use of classmethods for this. I think
1970 1975 this introduces a dependency on python 2.2.
1971 1976
1972 1977 2004-01-13 Fernando Perez <fperez@colorado.edu>
1973 1978
1974 1979 * IPython/numutils.py (exp_safe): simplified the code a bit and
1975 1980 removed the need for importing the kinds module altogether.
1976 1981
1977 1982 2004-01-06 Fernando Perez <fperez@colorado.edu>
1978 1983
1979 1984 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
1980 1985 a magic function instead, after some community feedback. No
1981 1986 special syntax will exist for it, but its name is deliberately
1982 1987 very short.
1983 1988
1984 1989 2003-12-20 Fernando Perez <fperez@colorado.edu>
1985 1990
1986 1991 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
1987 1992 new functionality, to automagically assign the result of a shell
1988 1993 command to a variable. I'll solicit some community feedback on
1989 1994 this before making it permanent.
1990 1995
1991 1996 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
1992 1997 requested about callables for which inspect couldn't obtain a
1993 1998 proper argspec. Thanks to a crash report sent by Etienne
1994 1999 Posthumus <etienne-AT-apple01.cs.vu.nl>.
1995 2000
1996 2001 2003-12-09 Fernando Perez <fperez@colorado.edu>
1997 2002
1998 2003 * IPython/genutils.py (page): patch for the pager to work across
1999 2004 various versions of Windows. By Gary Bishop.
2000 2005
2001 2006 2003-12-04 Fernando Perez <fperez@colorado.edu>
2002 2007
2003 2008 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2004 2009 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2005 2010 While I tested this and it looks ok, there may still be corner
2006 2011 cases I've missed.
2007 2012
2008 2013 2003-12-01 Fernando Perez <fperez@colorado.edu>
2009 2014
2010 2015 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2011 2016 where a line like 'p,q=1,2' would fail because the automagic
2012 2017 system would be triggered for @p.
2013 2018
2014 2019 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2015 2020 cleanups, code unmodified.
2016 2021
2017 2022 * IPython/genutils.py (Term): added a class for IPython to handle
2018 2023 output. In most cases it will just be a proxy for stdout/err, but
2019 2024 having this allows modifications to be made for some platforms,
2020 2025 such as handling color escapes under Windows. All of this code
2021 2026 was contributed by Gary Bishop, with minor modifications by me.
2022 2027 The actual changes affect many files.
2023 2028
2024 2029 2003-11-30 Fernando Perez <fperez@colorado.edu>
2025 2030
2026 2031 * IPython/iplib.py (file_matches): new completion code, courtesy
2027 2032 of Jeff Collins. This enables filename completion again under
2028 2033 python 2.3, which disabled it at the C level.
2029 2034
2030 2035 2003-11-11 Fernando Perez <fperez@colorado.edu>
2031 2036
2032 2037 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2033 2038 for Numeric.array(map(...)), but often convenient.
2034 2039
2035 2040 2003-11-05 Fernando Perez <fperez@colorado.edu>
2036 2041
2037 2042 * IPython/numutils.py (frange): Changed a call from int() to
2038 2043 int(round()) to prevent a problem reported with arange() in the
2039 2044 numpy list.
2040 2045
2041 2046 2003-10-06 Fernando Perez <fperez@colorado.edu>
2042 2047
2043 2048 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2044 2049 prevent crashes if sys lacks an argv attribute (it happens with
2045 2050 embedded interpreters which build a bare-bones sys module).
2046 2051 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2047 2052
2048 2053 2003-09-24 Fernando Perez <fperez@colorado.edu>
2049 2054
2050 2055 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2051 2056 to protect against poorly written user objects where __getattr__
2052 2057 raises exceptions other than AttributeError. Thanks to a bug
2053 2058 report by Oliver Sander <osander-AT-gmx.de>.
2054 2059
2055 2060 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2056 2061 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2057 2062
2058 2063 2003-09-09 Fernando Perez <fperez@colorado.edu>
2059 2064
2060 2065 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2061 2066 unpacking a list whith a callable as first element would
2062 2067 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2063 2068 Collins.
2064 2069
2065 2070 2003-08-25 *** Released version 0.5.0
2066 2071
2067 2072 2003-08-22 Fernando Perez <fperez@colorado.edu>
2068 2073
2069 2074 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2070 2075 improperly defined user exceptions. Thanks to feedback from Mark
2071 2076 Russell <mrussell-AT-verio.net>.
2072 2077
2073 2078 2003-08-20 Fernando Perez <fperez@colorado.edu>
2074 2079
2075 2080 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2076 2081 printing so that it would print multi-line string forms starting
2077 2082 with a new line. This way the formatting is better respected for
2078 2083 objects which work hard to make nice string forms.
2079 2084
2080 2085 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2081 2086 autocall would overtake data access for objects with both
2082 2087 __getitem__ and __call__.
2083 2088
2084 2089 2003-08-19 *** Released version 0.5.0-rc1
2085 2090
2086 2091 2003-08-19 Fernando Perez <fperez@colorado.edu>
2087 2092
2088 2093 * IPython/deep_reload.py (load_tail): single tiny change here
2089 2094 seems to fix the long-standing bug of dreload() failing to work
2090 2095 for dotted names. But this module is pretty tricky, so I may have
2091 2096 missed some subtlety. Needs more testing!.
2092 2097
2093 2098 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2094 2099 exceptions which have badly implemented __str__ methods.
2095 2100 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2096 2101 which I've been getting reports about from Python 2.3 users. I
2097 2102 wish I had a simple test case to reproduce the problem, so I could
2098 2103 either write a cleaner workaround or file a bug report if
2099 2104 necessary.
2100 2105
2101 2106 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2102 2107 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2103 2108 a bug report by Tjabo Kloppenburg.
2104 2109
2105 2110 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2106 2111 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2107 2112 seems rather unstable. Thanks to a bug report by Tjabo
2108 2113 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2109 2114
2110 2115 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2111 2116 this out soon because of the critical fixes in the inner loop for
2112 2117 generators.
2113 2118
2114 2119 * IPython/Magic.py (Magic.getargspec): removed. This (and
2115 2120 _get_def) have been obsoleted by OInspect for a long time, I
2116 2121 hadn't noticed that they were dead code.
2117 2122 (Magic._ofind): restored _ofind functionality for a few literals
2118 2123 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2119 2124 for things like "hello".capitalize?, since that would require a
2120 2125 potentially dangerous eval() again.
2121 2126
2122 2127 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2123 2128 logic a bit more to clean up the escapes handling and minimize the
2124 2129 use of _ofind to only necessary cases. The interactive 'feel' of
2125 2130 IPython should have improved quite a bit with the changes in
2126 2131 _prefilter and _ofind (besides being far safer than before).
2127 2132
2128 2133 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2129 2134 obscure, never reported). Edit would fail to find the object to
2130 2135 edit under some circumstances.
2131 2136 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2132 2137 which were causing double-calling of generators. Those eval calls
2133 2138 were _very_ dangerous, since code with side effects could be
2134 2139 triggered. As they say, 'eval is evil'... These were the
2135 2140 nastiest evals in IPython. Besides, _ofind is now far simpler,
2136 2141 and it should also be quite a bit faster. Its use of inspect is
2137 2142 also safer, so perhaps some of the inspect-related crashes I've
2138 2143 seen lately with Python 2.3 might be taken care of. That will
2139 2144 need more testing.
2140 2145
2141 2146 2003-08-17 Fernando Perez <fperez@colorado.edu>
2142 2147
2143 2148 * IPython/iplib.py (InteractiveShell._prefilter): significant
2144 2149 simplifications to the logic for handling user escapes. Faster
2145 2150 and simpler code.
2146 2151
2147 2152 2003-08-14 Fernando Perez <fperez@colorado.edu>
2148 2153
2149 2154 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2150 2155 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2151 2156 but it should be quite a bit faster. And the recursive version
2152 2157 generated O(log N) intermediate storage for all rank>1 arrays,
2153 2158 even if they were contiguous.
2154 2159 (l1norm): Added this function.
2155 2160 (norm): Added this function for arbitrary norms (including
2156 2161 l-infinity). l1 and l2 are still special cases for convenience
2157 2162 and speed.
2158 2163
2159 2164 2003-08-03 Fernando Perez <fperez@colorado.edu>
2160 2165
2161 2166 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2162 2167 exceptions, which now raise PendingDeprecationWarnings in Python
2163 2168 2.3. There were some in Magic and some in Gnuplot2.
2164 2169
2165 2170 2003-06-30 Fernando Perez <fperez@colorado.edu>
2166 2171
2167 2172 * IPython/genutils.py (page): modified to call curses only for
2168 2173 terminals where TERM=='xterm'. After problems under many other
2169 2174 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2170 2175
2171 2176 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2172 2177 would be triggered when readline was absent. This was just an old
2173 2178 debugging statement I'd forgotten to take out.
2174 2179
2175 2180 2003-06-20 Fernando Perez <fperez@colorado.edu>
2176 2181
2177 2182 * IPython/genutils.py (clock): modified to return only user time
2178 2183 (not counting system time), after a discussion on scipy. While
2179 2184 system time may be a useful quantity occasionally, it may much
2180 2185 more easily be skewed by occasional swapping or other similar
2181 2186 activity.
2182 2187
2183 2188 2003-06-05 Fernando Perez <fperez@colorado.edu>
2184 2189
2185 2190 * IPython/numutils.py (identity): new function, for building
2186 2191 arbitrary rank Kronecker deltas (mostly backwards compatible with
2187 2192 Numeric.identity)
2188 2193
2189 2194 2003-06-03 Fernando Perez <fperez@colorado.edu>
2190 2195
2191 2196 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2192 2197 arguments passed to magics with spaces, to allow trailing '\' to
2193 2198 work normally (mainly for Windows users).
2194 2199
2195 2200 2003-05-29 Fernando Perez <fperez@colorado.edu>
2196 2201
2197 2202 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2198 2203 instead of pydoc.help. This fixes a bizarre behavior where
2199 2204 printing '%s' % locals() would trigger the help system. Now
2200 2205 ipython behaves like normal python does.
2201 2206
2202 2207 Note that if one does 'from pydoc import help', the bizarre
2203 2208 behavior returns, but this will also happen in normal python, so
2204 2209 it's not an ipython bug anymore (it has to do with how pydoc.help
2205 2210 is implemented).
2206 2211
2207 2212 2003-05-22 Fernando Perez <fperez@colorado.edu>
2208 2213
2209 2214 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2210 2215 return [] instead of None when nothing matches, also match to end
2211 2216 of line. Patch by Gary Bishop.
2212 2217
2213 2218 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2214 2219 protection as before, for files passed on the command line. This
2215 2220 prevents the CrashHandler from kicking in if user files call into
2216 2221 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2217 2222 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2218 2223
2219 2224 2003-05-20 *** Released version 0.4.0
2220 2225
2221 2226 2003-05-20 Fernando Perez <fperez@colorado.edu>
2222 2227
2223 2228 * setup.py: added support for manpages. It's a bit hackish b/c of
2224 2229 a bug in the way the bdist_rpm distutils target handles gzipped
2225 2230 manpages, but it works. After a patch by Jack.
2226 2231
2227 2232 2003-05-19 Fernando Perez <fperez@colorado.edu>
2228 2233
2229 2234 * IPython/numutils.py: added a mockup of the kinds module, since
2230 2235 it was recently removed from Numeric. This way, numutils will
2231 2236 work for all users even if they are missing kinds.
2232 2237
2233 2238 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2234 2239 failure, which can occur with SWIG-wrapped extensions. After a
2235 2240 crash report from Prabhu.
2236 2241
2237 2242 2003-05-16 Fernando Perez <fperez@colorado.edu>
2238 2243
2239 2244 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2240 2245 protect ipython from user code which may call directly
2241 2246 sys.excepthook (this looks like an ipython crash to the user, even
2242 2247 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2243 2248 This is especially important to help users of WxWindows, but may
2244 2249 also be useful in other cases.
2245 2250
2246 2251 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2247 2252 an optional tb_offset to be specified, and to preserve exception
2248 2253 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2249 2254
2250 2255 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2251 2256
2252 2257 2003-05-15 Fernando Perez <fperez@colorado.edu>
2253 2258
2254 2259 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2255 2260 installing for a new user under Windows.
2256 2261
2257 2262 2003-05-12 Fernando Perez <fperez@colorado.edu>
2258 2263
2259 2264 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2260 2265 handler for Emacs comint-based lines. Currently it doesn't do
2261 2266 much (but importantly, it doesn't update the history cache). In
2262 2267 the future it may be expanded if Alex needs more functionality
2263 2268 there.
2264 2269
2265 2270 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2266 2271 info to crash reports.
2267 2272
2268 2273 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2269 2274 just like Python's -c. Also fixed crash with invalid -color
2270 2275 option value at startup. Thanks to Will French
2271 2276 <wfrench-AT-bestweb.net> for the bug report.
2272 2277
2273 2278 2003-05-09 Fernando Perez <fperez@colorado.edu>
2274 2279
2275 2280 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2276 2281 to EvalDict (it's a mapping, after all) and simplified its code
2277 2282 quite a bit, after a nice discussion on c.l.py where Gustavo
2278 2283 Córdova <gcordova-AT-sismex.com> suggested the new version.
2279 2284
2280 2285 2003-04-30 Fernando Perez <fperez@colorado.edu>
2281 2286
2282 2287 * IPython/genutils.py (timings_out): modified it to reduce its
2283 2288 overhead in the common reps==1 case.
2284 2289
2285 2290 2003-04-29 Fernando Perez <fperez@colorado.edu>
2286 2291
2287 2292 * IPython/genutils.py (timings_out): Modified to use the resource
2288 2293 module, which avoids the wraparound problems of time.clock().
2289 2294
2290 2295 2003-04-17 *** Released version 0.2.15pre4
2291 2296
2292 2297 2003-04-17 Fernando Perez <fperez@colorado.edu>
2293 2298
2294 2299 * setup.py (scriptfiles): Split windows-specific stuff over to a
2295 2300 separate file, in an attempt to have a Windows GUI installer.
2296 2301 That didn't work, but part of the groundwork is done.
2297 2302
2298 2303 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2299 2304 indent/unindent with 4 spaces. Particularly useful in combination
2300 2305 with the new auto-indent option.
2301 2306
2302 2307 2003-04-16 Fernando Perez <fperez@colorado.edu>
2303 2308
2304 2309 * IPython/Magic.py: various replacements of self.rc for
2305 2310 self.shell.rc. A lot more remains to be done to fully disentangle
2306 2311 this class from the main Shell class.
2307 2312
2308 2313 * IPython/GnuplotRuntime.py: added checks for mouse support so
2309 2314 that we don't try to enable it if the current gnuplot doesn't
2310 2315 really support it. Also added checks so that we don't try to
2311 2316 enable persist under Windows (where Gnuplot doesn't recognize the
2312 2317 option).
2313 2318
2314 2319 * IPython/iplib.py (InteractiveShell.interact): Added optional
2315 2320 auto-indenting code, after a patch by King C. Shu
2316 2321 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2317 2322 get along well with pasting indented code. If I ever figure out
2318 2323 how to make that part go well, it will become on by default.
2319 2324
2320 2325 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2321 2326 crash ipython if there was an unmatched '%' in the user's prompt
2322 2327 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2323 2328
2324 2329 * IPython/iplib.py (InteractiveShell.interact): removed the
2325 2330 ability to ask the user whether he wants to crash or not at the
2326 2331 'last line' exception handler. Calling functions at that point
2327 2332 changes the stack, and the error reports would have incorrect
2328 2333 tracebacks.
2329 2334
2330 2335 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2331 2336 pass through a peger a pretty-printed form of any object. After a
2332 2337 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2333 2338
2334 2339 2003-04-14 Fernando Perez <fperez@colorado.edu>
2335 2340
2336 2341 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2337 2342 all files in ~ would be modified at first install (instead of
2338 2343 ~/.ipython). This could be potentially disastrous, as the
2339 2344 modification (make line-endings native) could damage binary files.
2340 2345
2341 2346 2003-04-10 Fernando Perez <fperez@colorado.edu>
2342 2347
2343 2348 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2344 2349 handle only lines which are invalid python. This now means that
2345 2350 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2346 2351 for the bug report.
2347 2352
2348 2353 2003-04-01 Fernando Perez <fperez@colorado.edu>
2349 2354
2350 2355 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2351 2356 where failing to set sys.last_traceback would crash pdb.pm().
2352 2357 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2353 2358 report.
2354 2359
2355 2360 2003-03-25 Fernando Perez <fperez@colorado.edu>
2356 2361
2357 2362 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2358 2363 before printing it (it had a lot of spurious blank lines at the
2359 2364 end).
2360 2365
2361 2366 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2362 2367 output would be sent 21 times! Obviously people don't use this
2363 2368 too often, or I would have heard about it.
2364 2369
2365 2370 2003-03-24 Fernando Perez <fperez@colorado.edu>
2366 2371
2367 2372 * setup.py (scriptfiles): renamed the data_files parameter from
2368 2373 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2369 2374 for the patch.
2370 2375
2371 2376 2003-03-20 Fernando Perez <fperez@colorado.edu>
2372 2377
2373 2378 * IPython/genutils.py (error): added error() and fatal()
2374 2379 functions.
2375 2380
2376 2381 2003-03-18 *** Released version 0.2.15pre3
2377 2382
2378 2383 2003-03-18 Fernando Perez <fperez@colorado.edu>
2379 2384
2380 2385 * setupext/install_data_ext.py
2381 2386 (install_data_ext.initialize_options): Class contributed by Jack
2382 2387 Moffit for fixing the old distutils hack. He is sending this to
2383 2388 the distutils folks so in the future we may not need it as a
2384 2389 private fix.
2385 2390
2386 2391 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2387 2392 changes for Debian packaging. See his patch for full details.
2388 2393 The old distutils hack of making the ipythonrc* files carry a
2389 2394 bogus .py extension is gone, at last. Examples were moved to a
2390 2395 separate subdir under doc/, and the separate executable scripts
2391 2396 now live in their own directory. Overall a great cleanup. The
2392 2397 manual was updated to use the new files, and setup.py has been
2393 2398 fixed for this setup.
2394 2399
2395 2400 * IPython/PyColorize.py (Parser.usage): made non-executable and
2396 2401 created a pycolor wrapper around it to be included as a script.
2397 2402
2398 2403 2003-03-12 *** Released version 0.2.15pre2
2399 2404
2400 2405 2003-03-12 Fernando Perez <fperez@colorado.edu>
2401 2406
2402 2407 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2403 2408 long-standing problem with garbage characters in some terminals.
2404 2409 The issue was really that the \001 and \002 escapes must _only_ be
2405 2410 passed to input prompts (which call readline), but _never_ to
2406 2411 normal text to be printed on screen. I changed ColorANSI to have
2407 2412 two classes: TermColors and InputTermColors, each with the
2408 2413 appropriate escapes for input prompts or normal text. The code in
2409 2414 Prompts.py got slightly more complicated, but this very old and
2410 2415 annoying bug is finally fixed.
2411 2416
2412 2417 All the credit for nailing down the real origin of this problem
2413 2418 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2414 2419 *Many* thanks to him for spending quite a bit of effort on this.
2415 2420
2416 2421 2003-03-05 *** Released version 0.2.15pre1
2417 2422
2418 2423 2003-03-03 Fernando Perez <fperez@colorado.edu>
2419 2424
2420 2425 * IPython/FakeModule.py: Moved the former _FakeModule to a
2421 2426 separate file, because it's also needed by Magic (to fix a similar
2422 2427 pickle-related issue in @run).
2423 2428
2424 2429 2003-03-02 Fernando Perez <fperez@colorado.edu>
2425 2430
2426 2431 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2427 2432 the autocall option at runtime.
2428 2433 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2429 2434 across Magic.py to start separating Magic from InteractiveShell.
2430 2435 (Magic._ofind): Fixed to return proper namespace for dotted
2431 2436 names. Before, a dotted name would always return 'not currently
2432 2437 defined', because it would find the 'parent'. s.x would be found,
2433 2438 but since 'x' isn't defined by itself, it would get confused.
2434 2439 (Magic.magic_run): Fixed pickling problems reported by Ralf
2435 2440 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2436 2441 that I'd used when Mike Heeter reported similar issues at the
2437 2442 top-level, but now for @run. It boils down to injecting the
2438 2443 namespace where code is being executed with something that looks
2439 2444 enough like a module to fool pickle.dump(). Since a pickle stores
2440 2445 a named reference to the importing module, we need this for
2441 2446 pickles to save something sensible.
2442 2447
2443 2448 * IPython/ipmaker.py (make_IPython): added an autocall option.
2444 2449
2445 2450 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2446 2451 the auto-eval code. Now autocalling is an option, and the code is
2447 2452 also vastly safer. There is no more eval() involved at all.
2448 2453
2449 2454 2003-03-01 Fernando Perez <fperez@colorado.edu>
2450 2455
2451 2456 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2452 2457 dict with named keys instead of a tuple.
2453 2458
2454 2459 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2455 2460
2456 2461 * setup.py (make_shortcut): Fixed message about directories
2457 2462 created during Windows installation (the directories were ok, just
2458 2463 the printed message was misleading). Thanks to Chris Liechti
2459 2464 <cliechti-AT-gmx.net> for the heads up.
2460 2465
2461 2466 2003-02-21 Fernando Perez <fperez@colorado.edu>
2462 2467
2463 2468 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2464 2469 of ValueError exception when checking for auto-execution. This
2465 2470 one is raised by things like Numeric arrays arr.flat when the
2466 2471 array is non-contiguous.
2467 2472
2468 2473 2003-01-31 Fernando Perez <fperez@colorado.edu>
2469 2474
2470 2475 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2471 2476 not return any value at all (even though the command would get
2472 2477 executed).
2473 2478 (xsys): Flush stdout right after printing the command to ensure
2474 2479 proper ordering of commands and command output in the total
2475 2480 output.
2476 2481 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2477 2482 system/getoutput as defaults. The old ones are kept for
2478 2483 compatibility reasons, so no code which uses this library needs
2479 2484 changing.
2480 2485
2481 2486 2003-01-27 *** Released version 0.2.14
2482 2487
2483 2488 2003-01-25 Fernando Perez <fperez@colorado.edu>
2484 2489
2485 2490 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2486 2491 functions defined in previous edit sessions could not be re-edited
2487 2492 (because the temp files were immediately removed). Now temp files
2488 2493 are removed only at IPython's exit.
2489 2494 (Magic.magic_run): Improved @run to perform shell-like expansions
2490 2495 on its arguments (~users and $VARS). With this, @run becomes more
2491 2496 like a normal command-line.
2492 2497
2493 2498 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2494 2499 bugs related to embedding and cleaned up that code. A fairly
2495 2500 important one was the impossibility to access the global namespace
2496 2501 through the embedded IPython (only local variables were visible).
2497 2502
2498 2503 2003-01-14 Fernando Perez <fperez@colorado.edu>
2499 2504
2500 2505 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2501 2506 auto-calling to be a bit more conservative. Now it doesn't get
2502 2507 triggered if any of '!=()<>' are in the rest of the input line, to
2503 2508 allow comparing callables. Thanks to Alex for the heads up.
2504 2509
2505 2510 2003-01-07 Fernando Perez <fperez@colorado.edu>
2506 2511
2507 2512 * IPython/genutils.py (page): fixed estimation of the number of
2508 2513 lines in a string to be paged to simply count newlines. This
2509 2514 prevents over-guessing due to embedded escape sequences. A better
2510 2515 long-term solution would involve stripping out the control chars
2511 2516 for the count, but it's potentially so expensive I just don't
2512 2517 think it's worth doing.
2513 2518
2514 2519 2002-12-19 *** Released version 0.2.14pre50
2515 2520
2516 2521 2002-12-19 Fernando Perez <fperez@colorado.edu>
2517 2522
2518 2523 * tools/release (version): Changed release scripts to inform
2519 2524 Andrea and build a NEWS file with a list of recent changes.
2520 2525
2521 2526 * IPython/ColorANSI.py (__all__): changed terminal detection
2522 2527 code. Seems to work better for xterms without breaking
2523 2528 konsole. Will need more testing to determine if WinXP and Mac OSX
2524 2529 also work ok.
2525 2530
2526 2531 2002-12-18 *** Released version 0.2.14pre49
2527 2532
2528 2533 2002-12-18 Fernando Perez <fperez@colorado.edu>
2529 2534
2530 2535 * Docs: added new info about Mac OSX, from Andrea.
2531 2536
2532 2537 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2533 2538 allow direct plotting of python strings whose format is the same
2534 2539 of gnuplot data files.
2535 2540
2536 2541 2002-12-16 Fernando Perez <fperez@colorado.edu>
2537 2542
2538 2543 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2539 2544 value of exit question to be acknowledged.
2540 2545
2541 2546 2002-12-03 Fernando Perez <fperez@colorado.edu>
2542 2547
2543 2548 * IPython/ipmaker.py: removed generators, which had been added
2544 2549 by mistake in an earlier debugging run. This was causing trouble
2545 2550 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2546 2551 for pointing this out.
2547 2552
2548 2553 2002-11-17 Fernando Perez <fperez@colorado.edu>
2549 2554
2550 2555 * Manual: updated the Gnuplot section.
2551 2556
2552 2557 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2553 2558 a much better split of what goes in Runtime and what goes in
2554 2559 Interactive.
2555 2560
2556 2561 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2557 2562 being imported from iplib.
2558 2563
2559 2564 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2560 2565 for command-passing. Now the global Gnuplot instance is called
2561 2566 'gp' instead of 'g', which was really a far too fragile and
2562 2567 common name.
2563 2568
2564 2569 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2565 2570 bounding boxes generated by Gnuplot for square plots.
2566 2571
2567 2572 * IPython/genutils.py (popkey): new function added. I should
2568 2573 suggest this on c.l.py as a dict method, it seems useful.
2569 2574
2570 2575 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2571 2576 to transparently handle PostScript generation. MUCH better than
2572 2577 the previous plot_eps/replot_eps (which I removed now). The code
2573 2578 is also fairly clean and well documented now (including
2574 2579 docstrings).
2575 2580
2576 2581 2002-11-13 Fernando Perez <fperez@colorado.edu>
2577 2582
2578 2583 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2579 2584 (inconsistent with options).
2580 2585
2581 2586 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2582 2587 manually disabled, I don't know why. Fixed it.
2583 2588 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2584 2589 eps output.
2585 2590
2586 2591 2002-11-12 Fernando Perez <fperez@colorado.edu>
2587 2592
2588 2593 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2589 2594 don't propagate up to caller. Fixes crash reported by François
2590 2595 Pinard.
2591 2596
2592 2597 2002-11-09 Fernando Perez <fperez@colorado.edu>
2593 2598
2594 2599 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2595 2600 history file for new users.
2596 2601 (make_IPython): fixed bug where initial install would leave the
2597 2602 user running in the .ipython dir.
2598 2603 (make_IPython): fixed bug where config dir .ipython would be
2599 2604 created regardless of the given -ipythondir option. Thanks to Cory
2600 2605 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2601 2606
2602 2607 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2603 2608 type confirmations. Will need to use it in all of IPython's code
2604 2609 consistently.
2605 2610
2606 2611 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2607 2612 context to print 31 lines instead of the default 5. This will make
2608 2613 the crash reports extremely detailed in case the problem is in
2609 2614 libraries I don't have access to.
2610 2615
2611 2616 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2612 2617 line of defense' code to still crash, but giving users fair
2613 2618 warning. I don't want internal errors to go unreported: if there's
2614 2619 an internal problem, IPython should crash and generate a full
2615 2620 report.
2616 2621
2617 2622 2002-11-08 Fernando Perez <fperez@colorado.edu>
2618 2623
2619 2624 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2620 2625 otherwise uncaught exceptions which can appear if people set
2621 2626 sys.stdout to something badly broken. Thanks to a crash report
2622 2627 from henni-AT-mail.brainbot.com.
2623 2628
2624 2629 2002-11-04 Fernando Perez <fperez@colorado.edu>
2625 2630
2626 2631 * IPython/iplib.py (InteractiveShell.interact): added
2627 2632 __IPYTHON__active to the builtins. It's a flag which goes on when
2628 2633 the interaction starts and goes off again when it stops. This
2629 2634 allows embedding code to detect being inside IPython. Before this
2630 2635 was done via __IPYTHON__, but that only shows that an IPython
2631 2636 instance has been created.
2632 2637
2633 2638 * IPython/Magic.py (Magic.magic_env): I realized that in a
2634 2639 UserDict, instance.data holds the data as a normal dict. So I
2635 2640 modified @env to return os.environ.data instead of rebuilding a
2636 2641 dict by hand.
2637 2642
2638 2643 2002-11-02 Fernando Perez <fperez@colorado.edu>
2639 2644
2640 2645 * IPython/genutils.py (warn): changed so that level 1 prints no
2641 2646 header. Level 2 is now the default (with 'WARNING' header, as
2642 2647 before). I think I tracked all places where changes were needed in
2643 2648 IPython, but outside code using the old level numbering may have
2644 2649 broken.
2645 2650
2646 2651 * IPython/iplib.py (InteractiveShell.runcode): added this to
2647 2652 handle the tracebacks in SystemExit traps correctly. The previous
2648 2653 code (through interact) was printing more of the stack than
2649 2654 necessary, showing IPython internal code to the user.
2650 2655
2651 2656 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2652 2657 default. Now that the default at the confirmation prompt is yes,
2653 2658 it's not so intrusive. François' argument that ipython sessions
2654 2659 tend to be complex enough not to lose them from an accidental C-d,
2655 2660 is a valid one.
2656 2661
2657 2662 * IPython/iplib.py (InteractiveShell.interact): added a
2658 2663 showtraceback() call to the SystemExit trap, and modified the exit
2659 2664 confirmation to have yes as the default.
2660 2665
2661 2666 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2662 2667 this file. It's been gone from the code for a long time, this was
2663 2668 simply leftover junk.
2664 2669
2665 2670 2002-11-01 Fernando Perez <fperez@colorado.edu>
2666 2671
2667 2672 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2668 2673 added. If set, IPython now traps EOF and asks for
2669 2674 confirmation. After a request by François Pinard.
2670 2675
2671 2676 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2672 2677 of @abort, and with a new (better) mechanism for handling the
2673 2678 exceptions.
2674 2679
2675 2680 2002-10-27 Fernando Perez <fperez@colorado.edu>
2676 2681
2677 2682 * IPython/usage.py (__doc__): updated the --help information and
2678 2683 the ipythonrc file to indicate that -log generates
2679 2684 ./ipython.log. Also fixed the corresponding info in @logstart.
2680 2685 This and several other fixes in the manuals thanks to reports by
2681 2686 François Pinard <pinard-AT-iro.umontreal.ca>.
2682 2687
2683 2688 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2684 2689 refer to @logstart (instead of @log, which doesn't exist).
2685 2690
2686 2691 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2687 2692 AttributeError crash. Thanks to Christopher Armstrong
2688 2693 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2689 2694 introduced recently (in 0.2.14pre37) with the fix to the eval
2690 2695 problem mentioned below.
2691 2696
2692 2697 2002-10-17 Fernando Perez <fperez@colorado.edu>
2693 2698
2694 2699 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2695 2700 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2696 2701
2697 2702 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2698 2703 this function to fix a problem reported by Alex Schmolck. He saw
2699 2704 it with list comprehensions and generators, which were getting
2700 2705 called twice. The real problem was an 'eval' call in testing for
2701 2706 automagic which was evaluating the input line silently.
2702 2707
2703 2708 This is a potentially very nasty bug, if the input has side
2704 2709 effects which must not be repeated. The code is much cleaner now,
2705 2710 without any blanket 'except' left and with a regexp test for
2706 2711 actual function names.
2707 2712
2708 2713 But an eval remains, which I'm not fully comfortable with. I just
2709 2714 don't know how to find out if an expression could be a callable in
2710 2715 the user's namespace without doing an eval on the string. However
2711 2716 that string is now much more strictly checked so that no code
2712 2717 slips by, so the eval should only happen for things that can
2713 2718 really be only function/method names.
2714 2719
2715 2720 2002-10-15 Fernando Perez <fperez@colorado.edu>
2716 2721
2717 2722 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2718 2723 OSX information to main manual, removed README_Mac_OSX file from
2719 2724 distribution. Also updated credits for recent additions.
2720 2725
2721 2726 2002-10-10 Fernando Perez <fperez@colorado.edu>
2722 2727
2723 2728 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2724 2729 terminal-related issues. Many thanks to Andrea Riciputi
2725 2730 <andrea.riciputi-AT-libero.it> for writing it.
2726 2731
2727 2732 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2728 2733 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2729 2734
2730 2735 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2731 2736 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2732 2737 <syver-en-AT-online.no> who both submitted patches for this problem.
2733 2738
2734 2739 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2735 2740 global embedding to make sure that things don't overwrite user
2736 2741 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2737 2742
2738 2743 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2739 2744 compatibility. Thanks to Hayden Callow
2740 2745 <h.callow-AT-elec.canterbury.ac.nz>
2741 2746
2742 2747 2002-10-04 Fernando Perez <fperez@colorado.edu>
2743 2748
2744 2749 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2745 2750 Gnuplot.File objects.
2746 2751
2747 2752 2002-07-23 Fernando Perez <fperez@colorado.edu>
2748 2753
2749 2754 * IPython/genutils.py (timing): Added timings() and timing() for
2750 2755 quick access to the most commonly needed data, the execution
2751 2756 times. Old timing() renamed to timings_out().
2752 2757
2753 2758 2002-07-18 Fernando Perez <fperez@colorado.edu>
2754 2759
2755 2760 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2756 2761 bug with nested instances disrupting the parent's tab completion.
2757 2762
2758 2763 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2759 2764 all_completions code to begin the emacs integration.
2760 2765
2761 2766 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2762 2767 argument to allow titling individual arrays when plotting.
2763 2768
2764 2769 2002-07-15 Fernando Perez <fperez@colorado.edu>
2765 2770
2766 2771 * setup.py (make_shortcut): changed to retrieve the value of
2767 2772 'Program Files' directory from the registry (this value changes in
2768 2773 non-english versions of Windows). Thanks to Thomas Fanslau
2769 2774 <tfanslau-AT-gmx.de> for the report.
2770 2775
2771 2776 2002-07-10 Fernando Perez <fperez@colorado.edu>
2772 2777
2773 2778 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2774 2779 a bug in pdb, which crashes if a line with only whitespace is
2775 2780 entered. Bug report submitted to sourceforge.
2776 2781
2777 2782 2002-07-09 Fernando Perez <fperez@colorado.edu>
2778 2783
2779 2784 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2780 2785 reporting exceptions (it's a bug in inspect.py, I just set a
2781 2786 workaround).
2782 2787
2783 2788 2002-07-08 Fernando Perez <fperez@colorado.edu>
2784 2789
2785 2790 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2786 2791 __IPYTHON__ in __builtins__ to show up in user_ns.
2787 2792
2788 2793 2002-07-03 Fernando Perez <fperez@colorado.edu>
2789 2794
2790 2795 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2791 2796 name from @gp_set_instance to @gp_set_default.
2792 2797
2793 2798 * IPython/ipmaker.py (make_IPython): default editor value set to
2794 2799 '0' (a string), to match the rc file. Otherwise will crash when
2795 2800 .strip() is called on it.
2796 2801
2797 2802
2798 2803 2002-06-28 Fernando Perez <fperez@colorado.edu>
2799 2804
2800 2805 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2801 2806 of files in current directory when a file is executed via
2802 2807 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2803 2808
2804 2809 * setup.py (manfiles): fix for rpm builds, submitted by RA
2805 2810 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2806 2811
2807 2812 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2808 2813 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2809 2814 string!). A. Schmolck caught this one.
2810 2815
2811 2816 2002-06-27 Fernando Perez <fperez@colorado.edu>
2812 2817
2813 2818 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2814 2819 defined files at the cmd line. __name__ wasn't being set to
2815 2820 __main__.
2816 2821
2817 2822 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2818 2823 regular lists and tuples besides Numeric arrays.
2819 2824
2820 2825 * IPython/Prompts.py (CachedOutput.__call__): Added output
2821 2826 supression for input ending with ';'. Similar to Mathematica and
2822 2827 Matlab. The _* vars and Out[] list are still updated, just like
2823 2828 Mathematica behaves.
2824 2829
2825 2830 2002-06-25 Fernando Perez <fperez@colorado.edu>
2826 2831
2827 2832 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2828 2833 .ini extensions for profiels under Windows.
2829 2834
2830 2835 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2831 2836 string form. Fix contributed by Alexander Schmolck
2832 2837 <a.schmolck-AT-gmx.net>
2833 2838
2834 2839 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2835 2840 pre-configured Gnuplot instance.
2836 2841
2837 2842 2002-06-21 Fernando Perez <fperez@colorado.edu>
2838 2843
2839 2844 * IPython/numutils.py (exp_safe): new function, works around the
2840 2845 underflow problems in Numeric.
2841 2846 (log2): New fn. Safe log in base 2: returns exact integer answer
2842 2847 for exact integer powers of 2.
2843 2848
2844 2849 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2845 2850 properly.
2846 2851
2847 2852 2002-06-20 Fernando Perez <fperez@colorado.edu>
2848 2853
2849 2854 * IPython/genutils.py (timing): new function like
2850 2855 Mathematica's. Similar to time_test, but returns more info.
2851 2856
2852 2857 2002-06-18 Fernando Perez <fperez@colorado.edu>
2853 2858
2854 2859 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2855 2860 according to Mike Heeter's suggestions.
2856 2861
2857 2862 2002-06-16 Fernando Perez <fperez@colorado.edu>
2858 2863
2859 2864 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2860 2865 system. GnuplotMagic is gone as a user-directory option. New files
2861 2866 make it easier to use all the gnuplot stuff both from external
2862 2867 programs as well as from IPython. Had to rewrite part of
2863 2868 hardcopy() b/c of a strange bug: often the ps files simply don't
2864 2869 get created, and require a repeat of the command (often several
2865 2870 times).
2866 2871
2867 2872 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2868 2873 resolve output channel at call time, so that if sys.stderr has
2869 2874 been redirected by user this gets honored.
2870 2875
2871 2876 2002-06-13 Fernando Perez <fperez@colorado.edu>
2872 2877
2873 2878 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2874 2879 IPShell. Kept a copy with the old names to avoid breaking people's
2875 2880 embedded code.
2876 2881
2877 2882 * IPython/ipython: simplified it to the bare minimum after
2878 2883 Holger's suggestions. Added info about how to use it in
2879 2884 PYTHONSTARTUP.
2880 2885
2881 2886 * IPython/Shell.py (IPythonShell): changed the options passing
2882 2887 from a string with funky %s replacements to a straight list. Maybe
2883 2888 a bit more typing, but it follows sys.argv conventions, so there's
2884 2889 less special-casing to remember.
2885 2890
2886 2891 2002-06-12 Fernando Perez <fperez@colorado.edu>
2887 2892
2888 2893 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2889 2894 command. Thanks to a suggestion by Mike Heeter.
2890 2895 (Magic.magic_pfile): added behavior to look at filenames if given
2891 2896 arg is not a defined object.
2892 2897 (Magic.magic_save): New @save function to save code snippets. Also
2893 2898 a Mike Heeter idea.
2894 2899
2895 2900 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2896 2901 plot() and replot(). Much more convenient now, especially for
2897 2902 interactive use.
2898 2903
2899 2904 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2900 2905 filenames.
2901 2906
2902 2907 2002-06-02 Fernando Perez <fperez@colorado.edu>
2903 2908
2904 2909 * IPython/Struct.py (Struct.__init__): modified to admit
2905 2910 initialization via another struct.
2906 2911
2907 2912 * IPython/genutils.py (SystemExec.__init__): New stateful
2908 2913 interface to xsys and bq. Useful for writing system scripts.
2909 2914
2910 2915 2002-05-30 Fernando Perez <fperez@colorado.edu>
2911 2916
2912 2917 * MANIFEST.in: Changed docfile selection to exclude all the lyx
2913 2918 documents. This will make the user download smaller (it's getting
2914 2919 too big).
2915 2920
2916 2921 2002-05-29 Fernando Perez <fperez@colorado.edu>
2917 2922
2918 2923 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
2919 2924 fix problems with shelve and pickle. Seems to work, but I don't
2920 2925 know if corner cases break it. Thanks to Mike Heeter
2921 2926 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
2922 2927
2923 2928 2002-05-24 Fernando Perez <fperez@colorado.edu>
2924 2929
2925 2930 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
2926 2931 macros having broken.
2927 2932
2928 2933 2002-05-21 Fernando Perez <fperez@colorado.edu>
2929 2934
2930 2935 * IPython/Magic.py (Magic.magic_logstart): fixed recently
2931 2936 introduced logging bug: all history before logging started was
2932 2937 being written one character per line! This came from the redesign
2933 2938 of the input history as a special list which slices to strings,
2934 2939 not to lists.
2935 2940
2936 2941 2002-05-20 Fernando Perez <fperez@colorado.edu>
2937 2942
2938 2943 * IPython/Prompts.py (CachedOutput.__init__): made the color table
2939 2944 be an attribute of all classes in this module. The design of these
2940 2945 classes needs some serious overhauling.
2941 2946
2942 2947 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
2943 2948 which was ignoring '_' in option names.
2944 2949
2945 2950 * IPython/ultraTB.py (FormattedTB.__init__): Changed
2946 2951 'Verbose_novars' to 'Context' and made it the new default. It's a
2947 2952 bit more readable and also safer than verbose.
2948 2953
2949 2954 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
2950 2955 triple-quoted strings.
2951 2956
2952 2957 * IPython/OInspect.py (__all__): new module exposing the object
2953 2958 introspection facilities. Now the corresponding magics are dummy
2954 2959 wrappers around this. Having this module will make it much easier
2955 2960 to put these functions into our modified pdb.
2956 2961 This new object inspector system uses the new colorizing module,
2957 2962 so source code and other things are nicely syntax highlighted.
2958 2963
2959 2964 2002-05-18 Fernando Perez <fperez@colorado.edu>
2960 2965
2961 2966 * IPython/ColorANSI.py: Split the coloring tools into a separate
2962 2967 module so I can use them in other code easier (they were part of
2963 2968 ultraTB).
2964 2969
2965 2970 2002-05-17 Fernando Perez <fperez@colorado.edu>
2966 2971
2967 2972 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2968 2973 fixed it to set the global 'g' also to the called instance, as
2969 2974 long as 'g' was still a gnuplot instance (so it doesn't overwrite
2970 2975 user's 'g' variables).
2971 2976
2972 2977 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
2973 2978 global variables (aliases to _ih,_oh) so that users which expect
2974 2979 In[5] or Out[7] to work aren't unpleasantly surprised.
2975 2980 (InputList.__getslice__): new class to allow executing slices of
2976 2981 input history directly. Very simple class, complements the use of
2977 2982 macros.
2978 2983
2979 2984 2002-05-16 Fernando Perez <fperez@colorado.edu>
2980 2985
2981 2986 * setup.py (docdirbase): make doc directory be just doc/IPython
2982 2987 without version numbers, it will reduce clutter for users.
2983 2988
2984 2989 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
2985 2990 execfile call to prevent possible memory leak. See for details:
2986 2991 http://mail.python.org/pipermail/python-list/2002-February/088476.html
2987 2992
2988 2993 2002-05-15 Fernando Perez <fperez@colorado.edu>
2989 2994
2990 2995 * IPython/Magic.py (Magic.magic_psource): made the object
2991 2996 introspection names be more standard: pdoc, pdef, pfile and
2992 2997 psource. They all print/page their output, and it makes
2993 2998 remembering them easier. Kept old names for compatibility as
2994 2999 aliases.
2995 3000
2996 3001 2002-05-14 Fernando Perez <fperez@colorado.edu>
2997 3002
2998 3003 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
2999 3004 what the mouse problem was. The trick is to use gnuplot with temp
3000 3005 files and NOT with pipes (for data communication), because having
3001 3006 both pipes and the mouse on is bad news.
3002 3007
3003 3008 2002-05-13 Fernando Perez <fperez@colorado.edu>
3004 3009
3005 3010 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3006 3011 bug. Information would be reported about builtins even when
3007 3012 user-defined functions overrode them.
3008 3013
3009 3014 2002-05-11 Fernando Perez <fperez@colorado.edu>
3010 3015
3011 3016 * IPython/__init__.py (__all__): removed FlexCompleter from
3012 3017 __all__ so that things don't fail in platforms without readline.
3013 3018
3014 3019 2002-05-10 Fernando Perez <fperez@colorado.edu>
3015 3020
3016 3021 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3017 3022 it requires Numeric, effectively making Numeric a dependency for
3018 3023 IPython.
3019 3024
3020 3025 * Released 0.2.13
3021 3026
3022 3027 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3023 3028 profiler interface. Now all the major options from the profiler
3024 3029 module are directly supported in IPython, both for single
3025 3030 expressions (@prun) and for full programs (@run -p).
3026 3031
3027 3032 2002-05-09 Fernando Perez <fperez@colorado.edu>
3028 3033
3029 3034 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3030 3035 magic properly formatted for screen.
3031 3036
3032 3037 * setup.py (make_shortcut): Changed things to put pdf version in
3033 3038 doc/ instead of doc/manual (had to change lyxport a bit).
3034 3039
3035 3040 * IPython/Magic.py (Profile.string_stats): made profile runs go
3036 3041 through pager (they are long and a pager allows searching, saving,
3037 3042 etc.)
3038 3043
3039 3044 2002-05-08 Fernando Perez <fperez@colorado.edu>
3040 3045
3041 3046 * Released 0.2.12
3042 3047
3043 3048 2002-05-06 Fernando Perez <fperez@colorado.edu>
3044 3049
3045 3050 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3046 3051 introduced); 'hist n1 n2' was broken.
3047 3052 (Magic.magic_pdb): added optional on/off arguments to @pdb
3048 3053 (Magic.magic_run): added option -i to @run, which executes code in
3049 3054 the IPython namespace instead of a clean one. Also added @irun as
3050 3055 an alias to @run -i.
3051 3056
3052 3057 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3053 3058 fixed (it didn't really do anything, the namespaces were wrong).
3054 3059
3055 3060 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3056 3061
3057 3062 * IPython/__init__.py (__all__): Fixed package namespace, now
3058 3063 'import IPython' does give access to IPython.<all> as
3059 3064 expected. Also renamed __release__ to Release.
3060 3065
3061 3066 * IPython/Debugger.py (__license__): created new Pdb class which
3062 3067 functions like a drop-in for the normal pdb.Pdb but does NOT
3063 3068 import readline by default. This way it doesn't muck up IPython's
3064 3069 readline handling, and now tab-completion finally works in the
3065 3070 debugger -- sort of. It completes things globally visible, but the
3066 3071 completer doesn't track the stack as pdb walks it. That's a bit
3067 3072 tricky, and I'll have to implement it later.
3068 3073
3069 3074 2002-05-05 Fernando Perez <fperez@colorado.edu>
3070 3075
3071 3076 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3072 3077 magic docstrings when printed via ? (explicit \'s were being
3073 3078 printed).
3074 3079
3075 3080 * IPython/ipmaker.py (make_IPython): fixed namespace
3076 3081 identification bug. Now variables loaded via logs or command-line
3077 3082 files are recognized in the interactive namespace by @who.
3078 3083
3079 3084 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3080 3085 log replay system stemming from the string form of Structs.
3081 3086
3082 3087 * IPython/Magic.py (Macro.__init__): improved macros to properly
3083 3088 handle magic commands in them.
3084 3089 (Magic.magic_logstart): usernames are now expanded so 'logstart
3085 3090 ~/mylog' now works.
3086 3091
3087 3092 * IPython/iplib.py (complete): fixed bug where paths starting with
3088 3093 '/' would be completed as magic names.
3089 3094
3090 3095 2002-05-04 Fernando Perez <fperez@colorado.edu>
3091 3096
3092 3097 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3093 3098 allow running full programs under the profiler's control.
3094 3099
3095 3100 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3096 3101 mode to report exceptions verbosely but without formatting
3097 3102 variables. This addresses the issue of ipython 'freezing' (it's
3098 3103 not frozen, but caught in an expensive formatting loop) when huge
3099 3104 variables are in the context of an exception.
3100 3105 (VerboseTB.text): Added '--->' markers at line where exception was
3101 3106 triggered. Much clearer to read, especially in NoColor modes.
3102 3107
3103 3108 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3104 3109 implemented in reverse when changing to the new parse_options().
3105 3110
3106 3111 2002-05-03 Fernando Perez <fperez@colorado.edu>
3107 3112
3108 3113 * IPython/Magic.py (Magic.parse_options): new function so that
3109 3114 magics can parse options easier.
3110 3115 (Magic.magic_prun): new function similar to profile.run(),
3111 3116 suggested by Chris Hart.
3112 3117 (Magic.magic_cd): fixed behavior so that it only changes if
3113 3118 directory actually is in history.
3114 3119
3115 3120 * IPython/usage.py (__doc__): added information about potential
3116 3121 slowness of Verbose exception mode when there are huge data
3117 3122 structures to be formatted (thanks to Archie Paulson).
3118 3123
3119 3124 * IPython/ipmaker.py (make_IPython): Changed default logging
3120 3125 (when simply called with -log) to use curr_dir/ipython.log in
3121 3126 rotate mode. Fixed crash which was occuring with -log before
3122 3127 (thanks to Jim Boyle).
3123 3128
3124 3129 2002-05-01 Fernando Perez <fperez@colorado.edu>
3125 3130
3126 3131 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3127 3132 was nasty -- though somewhat of a corner case).
3128 3133
3129 3134 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3130 3135 text (was a bug).
3131 3136
3132 3137 2002-04-30 Fernando Perez <fperez@colorado.edu>
3133 3138
3134 3139 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3135 3140 a print after ^D or ^C from the user so that the In[] prompt
3136 3141 doesn't over-run the gnuplot one.
3137 3142
3138 3143 2002-04-29 Fernando Perez <fperez@colorado.edu>
3139 3144
3140 3145 * Released 0.2.10
3141 3146
3142 3147 * IPython/__release__.py (version): get date dynamically.
3143 3148
3144 3149 * Misc. documentation updates thanks to Arnd's comments. Also ran
3145 3150 a full spellcheck on the manual (hadn't been done in a while).
3146 3151
3147 3152 2002-04-27 Fernando Perez <fperez@colorado.edu>
3148 3153
3149 3154 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3150 3155 starting a log in mid-session would reset the input history list.
3151 3156
3152 3157 2002-04-26 Fernando Perez <fperez@colorado.edu>
3153 3158
3154 3159 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3155 3160 all files were being included in an update. Now anything in
3156 3161 UserConfig that matches [A-Za-z]*.py will go (this excludes
3157 3162 __init__.py)
3158 3163
3159 3164 2002-04-25 Fernando Perez <fperez@colorado.edu>
3160 3165
3161 3166 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3162 3167 to __builtins__ so that any form of embedded or imported code can
3163 3168 test for being inside IPython.
3164 3169
3165 3170 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3166 3171 changed to GnuplotMagic because it's now an importable module,
3167 3172 this makes the name follow that of the standard Gnuplot module.
3168 3173 GnuplotMagic can now be loaded at any time in mid-session.
3169 3174
3170 3175 2002-04-24 Fernando Perez <fperez@colorado.edu>
3171 3176
3172 3177 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3173 3178 the globals (IPython has its own namespace) and the
3174 3179 PhysicalQuantity stuff is much better anyway.
3175 3180
3176 3181 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3177 3182 embedding example to standard user directory for
3178 3183 distribution. Also put it in the manual.
3179 3184
3180 3185 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3181 3186 instance as first argument (so it doesn't rely on some obscure
3182 3187 hidden global).
3183 3188
3184 3189 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3185 3190 delimiters. While it prevents ().TAB from working, it allows
3186 3191 completions in open (... expressions. This is by far a more common
3187 3192 case.
3188 3193
3189 3194 2002-04-23 Fernando Perez <fperez@colorado.edu>
3190 3195
3191 3196 * IPython/Extensions/InterpreterPasteInput.py: new
3192 3197 syntax-processing module for pasting lines with >>> or ... at the
3193 3198 start.
3194 3199
3195 3200 * IPython/Extensions/PhysicalQ_Interactive.py
3196 3201 (PhysicalQuantityInteractive.__int__): fixed to work with either
3197 3202 Numeric or math.
3198 3203
3199 3204 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3200 3205 provided profiles. Now we have:
3201 3206 -math -> math module as * and cmath with its own namespace.
3202 3207 -numeric -> Numeric as *, plus gnuplot & grace
3203 3208 -physics -> same as before
3204 3209
3205 3210 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3206 3211 user-defined magics wouldn't be found by @magic if they were
3207 3212 defined as class methods. Also cleaned up the namespace search
3208 3213 logic and the string building (to use %s instead of many repeated
3209 3214 string adds).
3210 3215
3211 3216 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3212 3217 of user-defined magics to operate with class methods (cleaner, in
3213 3218 line with the gnuplot code).
3214 3219
3215 3220 2002-04-22 Fernando Perez <fperez@colorado.edu>
3216 3221
3217 3222 * setup.py: updated dependency list so that manual is updated when
3218 3223 all included files change.
3219 3224
3220 3225 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3221 3226 the delimiter removal option (the fix is ugly right now).
3222 3227
3223 3228 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3224 3229 all of the math profile (quicker loading, no conflict between
3225 3230 g-9.8 and g-gnuplot).
3226 3231
3227 3232 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3228 3233 name of post-mortem files to IPython_crash_report.txt.
3229 3234
3230 3235 * Cleanup/update of the docs. Added all the new readline info and
3231 3236 formatted all lists as 'real lists'.
3232 3237
3233 3238 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3234 3239 tab-completion options, since the full readline parse_and_bind is
3235 3240 now accessible.
3236 3241
3237 3242 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3238 3243 handling of readline options. Now users can specify any string to
3239 3244 be passed to parse_and_bind(), as well as the delimiters to be
3240 3245 removed.
3241 3246 (InteractiveShell.__init__): Added __name__ to the global
3242 3247 namespace so that things like Itpl which rely on its existence
3243 3248 don't crash.
3244 3249 (InteractiveShell._prefilter): Defined the default with a _ so
3245 3250 that prefilter() is easier to override, while the default one
3246 3251 remains available.
3247 3252
3248 3253 2002-04-18 Fernando Perez <fperez@colorado.edu>
3249 3254
3250 3255 * Added information about pdb in the docs.
3251 3256
3252 3257 2002-04-17 Fernando Perez <fperez@colorado.edu>
3253 3258
3254 3259 * IPython/ipmaker.py (make_IPython): added rc_override option to
3255 3260 allow passing config options at creation time which may override
3256 3261 anything set in the config files or command line. This is
3257 3262 particularly useful for configuring embedded instances.
3258 3263
3259 3264 2002-04-15 Fernando Perez <fperez@colorado.edu>
3260 3265
3261 3266 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3262 3267 crash embedded instances because of the input cache falling out of
3263 3268 sync with the output counter.
3264 3269
3265 3270 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3266 3271 mode which calls pdb after an uncaught exception in IPython itself.
3267 3272
3268 3273 2002-04-14 Fernando Perez <fperez@colorado.edu>
3269 3274
3270 3275 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3271 3276 readline, fix it back after each call.
3272 3277
3273 3278 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3274 3279 method to force all access via __call__(), which guarantees that
3275 3280 traceback references are properly deleted.
3276 3281
3277 3282 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3278 3283 improve printing when pprint is in use.
3279 3284
3280 3285 2002-04-13 Fernando Perez <fperez@colorado.edu>
3281 3286
3282 3287 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3283 3288 exceptions aren't caught anymore. If the user triggers one, he
3284 3289 should know why he's doing it and it should go all the way up,
3285 3290 just like any other exception. So now @abort will fully kill the
3286 3291 embedded interpreter and the embedding code (unless that happens
3287 3292 to catch SystemExit).
3288 3293
3289 3294 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3290 3295 and a debugger() method to invoke the interactive pdb debugger
3291 3296 after printing exception information. Also added the corresponding
3292 3297 -pdb option and @pdb magic to control this feature, and updated
3293 3298 the docs. After a suggestion from Christopher Hart
3294 3299 (hart-AT-caltech.edu).
3295 3300
3296 3301 2002-04-12 Fernando Perez <fperez@colorado.edu>
3297 3302
3298 3303 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3299 3304 the exception handlers defined by the user (not the CrashHandler)
3300 3305 so that user exceptions don't trigger an ipython bug report.
3301 3306
3302 3307 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3303 3308 configurable (it should have always been so).
3304 3309
3305 3310 2002-03-26 Fernando Perez <fperez@colorado.edu>
3306 3311
3307 3312 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3308 3313 and there to fix embedding namespace issues. This should all be
3309 3314 done in a more elegant way.
3310 3315
3311 3316 2002-03-25 Fernando Perez <fperez@colorado.edu>
3312 3317
3313 3318 * IPython/genutils.py (get_home_dir): Try to make it work under
3314 3319 win9x also.
3315 3320
3316 3321 2002-03-20 Fernando Perez <fperez@colorado.edu>
3317 3322
3318 3323 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3319 3324 sys.displayhook untouched upon __init__.
3320 3325
3321 3326 2002-03-19 Fernando Perez <fperez@colorado.edu>
3322 3327
3323 3328 * Released 0.2.9 (for embedding bug, basically).
3324 3329
3325 3330 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3326 3331 exceptions so that enclosing shell's state can be restored.
3327 3332
3328 3333 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3329 3334 naming conventions in the .ipython/ dir.
3330 3335
3331 3336 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3332 3337 from delimiters list so filenames with - in them get expanded.
3333 3338
3334 3339 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3335 3340 sys.displayhook not being properly restored after an embedded call.
3336 3341
3337 3342 2002-03-18 Fernando Perez <fperez@colorado.edu>
3338 3343
3339 3344 * Released 0.2.8
3340 3345
3341 3346 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3342 3347 some files weren't being included in a -upgrade.
3343 3348 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3344 3349 on' so that the first tab completes.
3345 3350 (InteractiveShell.handle_magic): fixed bug with spaces around
3346 3351 quotes breaking many magic commands.
3347 3352
3348 3353 * setup.py: added note about ignoring the syntax error messages at
3349 3354 installation.
3350 3355
3351 3356 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3352 3357 streamlining the gnuplot interface, now there's only one magic @gp.
3353 3358
3354 3359 2002-03-17 Fernando Perez <fperez@colorado.edu>
3355 3360
3356 3361 * IPython/UserConfig/magic_gnuplot.py: new name for the
3357 3362 example-magic_pm.py file. Much enhanced system, now with a shell
3358 3363 for communicating directly with gnuplot, one command at a time.
3359 3364
3360 3365 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3361 3366 setting __name__=='__main__'.
3362 3367
3363 3368 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3364 3369 mini-shell for accessing gnuplot from inside ipython. Should
3365 3370 extend it later for grace access too. Inspired by Arnd's
3366 3371 suggestion.
3367 3372
3368 3373 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3369 3374 calling magic functions with () in their arguments. Thanks to Arnd
3370 3375 Baecker for pointing this to me.
3371 3376
3372 3377 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3373 3378 infinitely for integer or complex arrays (only worked with floats).
3374 3379
3375 3380 2002-03-16 Fernando Perez <fperez@colorado.edu>
3376 3381
3377 3382 * setup.py: Merged setup and setup_windows into a single script
3378 3383 which properly handles things for windows users.
3379 3384
3380 3385 2002-03-15 Fernando Perez <fperez@colorado.edu>
3381 3386
3382 3387 * Big change to the manual: now the magics are all automatically
3383 3388 documented. This information is generated from their docstrings
3384 3389 and put in a latex file included by the manual lyx file. This way
3385 3390 we get always up to date information for the magics. The manual
3386 3391 now also has proper version information, also auto-synced.
3387 3392
3388 3393 For this to work, an undocumented --magic_docstrings option was added.
3389 3394
3390 3395 2002-03-13 Fernando Perez <fperez@colorado.edu>
3391 3396
3392 3397 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3393 3398 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3394 3399
3395 3400 2002-03-12 Fernando Perez <fperez@colorado.edu>
3396 3401
3397 3402 * IPython/ultraTB.py (TermColors): changed color escapes again to
3398 3403 fix the (old, reintroduced) line-wrapping bug. Basically, if
3399 3404 \001..\002 aren't given in the color escapes, lines get wrapped
3400 3405 weirdly. But giving those screws up old xterms and emacs terms. So
3401 3406 I added some logic for emacs terms to be ok, but I can't identify old
3402 3407 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3403 3408
3404 3409 2002-03-10 Fernando Perez <fperez@colorado.edu>
3405 3410
3406 3411 * IPython/usage.py (__doc__): Various documentation cleanups and
3407 3412 updates, both in usage docstrings and in the manual.
3408 3413
3409 3414 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3410 3415 handling of caching. Set minimum acceptabe value for having a
3411 3416 cache at 20 values.
3412 3417
3413 3418 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3414 3419 install_first_time function to a method, renamed it and added an
3415 3420 'upgrade' mode. Now people can update their config directory with
3416 3421 a simple command line switch (-upgrade, also new).
3417 3422
3418 3423 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3419 3424 @file (convenient for automagic users under Python >= 2.2).
3420 3425 Removed @files (it seemed more like a plural than an abbrev. of
3421 3426 'file show').
3422 3427
3423 3428 * IPython/iplib.py (install_first_time): Fixed crash if there were
3424 3429 backup files ('~') in .ipython/ install directory.
3425 3430
3426 3431 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3427 3432 system. Things look fine, but these changes are fairly
3428 3433 intrusive. Test them for a few days.
3429 3434
3430 3435 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3431 3436 the prompts system. Now all in/out prompt strings are user
3432 3437 controllable. This is particularly useful for embedding, as one
3433 3438 can tag embedded instances with particular prompts.
3434 3439
3435 3440 Also removed global use of sys.ps1/2, which now allows nested
3436 3441 embeddings without any problems. Added command-line options for
3437 3442 the prompt strings.
3438 3443
3439 3444 2002-03-08 Fernando Perez <fperez@colorado.edu>
3440 3445
3441 3446 * IPython/UserConfig/example-embed-short.py (ipshell): added
3442 3447 example file with the bare minimum code for embedding.
3443 3448
3444 3449 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3445 3450 functionality for the embeddable shell to be activated/deactivated
3446 3451 either globally or at each call.
3447 3452
3448 3453 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3449 3454 rewriting the prompt with '--->' for auto-inputs with proper
3450 3455 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3451 3456 this is handled by the prompts class itself, as it should.
3452 3457
3453 3458 2002-03-05 Fernando Perez <fperez@colorado.edu>
3454 3459
3455 3460 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3456 3461 @logstart to avoid name clashes with the math log function.
3457 3462
3458 3463 * Big updates to X/Emacs section of the manual.
3459 3464
3460 3465 * Removed ipython_emacs. Milan explained to me how to pass
3461 3466 arguments to ipython through Emacs. Some day I'm going to end up
3462 3467 learning some lisp...
3463 3468
3464 3469 2002-03-04 Fernando Perez <fperez@colorado.edu>
3465 3470
3466 3471 * IPython/ipython_emacs: Created script to be used as the
3467 3472 py-python-command Emacs variable so we can pass IPython
3468 3473 parameters. I can't figure out how to tell Emacs directly to pass
3469 3474 parameters to IPython, so a dummy shell script will do it.
3470 3475
3471 3476 Other enhancements made for things to work better under Emacs'
3472 3477 various types of terminals. Many thanks to Milan Zamazal
3473 3478 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3474 3479
3475 3480 2002-03-01 Fernando Perez <fperez@colorado.edu>
3476 3481
3477 3482 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3478 3483 that loading of readline is now optional. This gives better
3479 3484 control to emacs users.
3480 3485
3481 3486 * IPython/ultraTB.py (__date__): Modified color escape sequences
3482 3487 and now things work fine under xterm and in Emacs' term buffers
3483 3488 (though not shell ones). Well, in emacs you get colors, but all
3484 3489 seem to be 'light' colors (no difference between dark and light
3485 3490 ones). But the garbage chars are gone, and also in xterms. It
3486 3491 seems that now I'm using 'cleaner' ansi sequences.
3487 3492
3488 3493 2002-02-21 Fernando Perez <fperez@colorado.edu>
3489 3494
3490 3495 * Released 0.2.7 (mainly to publish the scoping fix).
3491 3496
3492 3497 * IPython/Logger.py (Logger.logstate): added. A corresponding
3493 3498 @logstate magic was created.
3494 3499
3495 3500 * IPython/Magic.py: fixed nested scoping problem under Python
3496 3501 2.1.x (automagic wasn't working).
3497 3502
3498 3503 2002-02-20 Fernando Perez <fperez@colorado.edu>
3499 3504
3500 3505 * Released 0.2.6.
3501 3506
3502 3507 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3503 3508 option so that logs can come out without any headers at all.
3504 3509
3505 3510 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3506 3511 SciPy.
3507 3512
3508 3513 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3509 3514 that embedded IPython calls don't require vars() to be explicitly
3510 3515 passed. Now they are extracted from the caller's frame (code
3511 3516 snatched from Eric Jones' weave). Added better documentation to
3512 3517 the section on embedding and the example file.
3513 3518
3514 3519 * IPython/genutils.py (page): Changed so that under emacs, it just
3515 3520 prints the string. You can then page up and down in the emacs
3516 3521 buffer itself. This is how the builtin help() works.
3517 3522
3518 3523 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3519 3524 macro scoping: macros need to be executed in the user's namespace
3520 3525 to work as if they had been typed by the user.
3521 3526
3522 3527 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3523 3528 execute automatically (no need to type 'exec...'). They then
3524 3529 behave like 'true macros'. The printing system was also modified
3525 3530 for this to work.
3526 3531
3527 3532 2002-02-19 Fernando Perez <fperez@colorado.edu>
3528 3533
3529 3534 * IPython/genutils.py (page_file): new function for paging files
3530 3535 in an OS-independent way. Also necessary for file viewing to work
3531 3536 well inside Emacs buffers.
3532 3537 (page): Added checks for being in an emacs buffer.
3533 3538 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3534 3539 same bug in iplib.
3535 3540
3536 3541 2002-02-18 Fernando Perez <fperez@colorado.edu>
3537 3542
3538 3543 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3539 3544 of readline so that IPython can work inside an Emacs buffer.
3540 3545
3541 3546 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3542 3547 method signatures (they weren't really bugs, but it looks cleaner
3543 3548 and keeps PyChecker happy).
3544 3549
3545 3550 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3546 3551 for implementing various user-defined hooks. Currently only
3547 3552 display is done.
3548 3553
3549 3554 * IPython/Prompts.py (CachedOutput._display): changed display
3550 3555 functions so that they can be dynamically changed by users easily.
3551 3556
3552 3557 * IPython/Extensions/numeric_formats.py (num_display): added an
3553 3558 extension for printing NumPy arrays in flexible manners. It
3554 3559 doesn't do anything yet, but all the structure is in
3555 3560 place. Ultimately the plan is to implement output format control
3556 3561 like in Octave.
3557 3562
3558 3563 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3559 3564 methods are found at run-time by all the automatic machinery.
3560 3565
3561 3566 2002-02-17 Fernando Perez <fperez@colorado.edu>
3562 3567
3563 3568 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3564 3569 whole file a little.
3565 3570
3566 3571 * ToDo: closed this document. Now there's a new_design.lyx
3567 3572 document for all new ideas. Added making a pdf of it for the
3568 3573 end-user distro.
3569 3574
3570 3575 * IPython/Logger.py (Logger.switch_log): Created this to replace
3571 3576 logon() and logoff(). It also fixes a nasty crash reported by
3572 3577 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3573 3578
3574 3579 * IPython/iplib.py (complete): got auto-completion to work with
3575 3580 automagic (I had wanted this for a long time).
3576 3581
3577 3582 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3578 3583 to @file, since file() is now a builtin and clashes with automagic
3579 3584 for @file.
3580 3585
3581 3586 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3582 3587 of this was previously in iplib, which had grown to more than 2000
3583 3588 lines, way too long. No new functionality, but it makes managing
3584 3589 the code a bit easier.
3585 3590
3586 3591 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3587 3592 information to crash reports.
3588 3593
3589 3594 2002-02-12 Fernando Perez <fperez@colorado.edu>
3590 3595
3591 3596 * Released 0.2.5.
3592 3597
3593 3598 2002-02-11 Fernando Perez <fperez@colorado.edu>
3594 3599
3595 3600 * Wrote a relatively complete Windows installer. It puts
3596 3601 everything in place, creates Start Menu entries and fixes the
3597 3602 color issues. Nothing fancy, but it works.
3598 3603
3599 3604 2002-02-10 Fernando Perez <fperez@colorado.edu>
3600 3605
3601 3606 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3602 3607 os.path.expanduser() call so that we can type @run ~/myfile.py and
3603 3608 have thigs work as expected.
3604 3609
3605 3610 * IPython/genutils.py (page): fixed exception handling so things
3606 3611 work both in Unix and Windows correctly. Quitting a pager triggers
3607 3612 an IOError/broken pipe in Unix, and in windows not finding a pager
3608 3613 is also an IOError, so I had to actually look at the return value
3609 3614 of the exception, not just the exception itself. Should be ok now.
3610 3615
3611 3616 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3612 3617 modified to allow case-insensitive color scheme changes.
3613 3618
3614 3619 2002-02-09 Fernando Perez <fperez@colorado.edu>
3615 3620
3616 3621 * IPython/genutils.py (native_line_ends): new function to leave
3617 3622 user config files with os-native line-endings.
3618 3623
3619 3624 * README and manual updates.
3620 3625
3621 3626 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3622 3627 instead of StringType to catch Unicode strings.
3623 3628
3624 3629 * IPython/genutils.py (filefind): fixed bug for paths with
3625 3630 embedded spaces (very common in Windows).
3626 3631
3627 3632 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3628 3633 files under Windows, so that they get automatically associated
3629 3634 with a text editor. Windows makes it a pain to handle
3630 3635 extension-less files.
3631 3636
3632 3637 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3633 3638 warning about readline only occur for Posix. In Windows there's no
3634 3639 way to get readline, so why bother with the warning.
3635 3640
3636 3641 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3637 3642 for __str__ instead of dir(self), since dir() changed in 2.2.
3638 3643
3639 3644 * Ported to Windows! Tested on XP, I suspect it should work fine
3640 3645 on NT/2000, but I don't think it will work on 98 et al. That
3641 3646 series of Windows is such a piece of junk anyway that I won't try
3642 3647 porting it there. The XP port was straightforward, showed a few
3643 3648 bugs here and there (fixed all), in particular some string
3644 3649 handling stuff which required considering Unicode strings (which
3645 3650 Windows uses). This is good, but hasn't been too tested :) No
3646 3651 fancy installer yet, I'll put a note in the manual so people at
3647 3652 least make manually a shortcut.
3648 3653
3649 3654 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3650 3655 into a single one, "colors". This now controls both prompt and
3651 3656 exception color schemes, and can be changed both at startup
3652 3657 (either via command-line switches or via ipythonrc files) and at
3653 3658 runtime, with @colors.
3654 3659 (Magic.magic_run): renamed @prun to @run and removed the old
3655 3660 @run. The two were too similar to warrant keeping both.
3656 3661
3657 3662 2002-02-03 Fernando Perez <fperez@colorado.edu>
3658 3663
3659 3664 * IPython/iplib.py (install_first_time): Added comment on how to
3660 3665 configure the color options for first-time users. Put a <return>
3661 3666 request at the end so that small-terminal users get a chance to
3662 3667 read the startup info.
3663 3668
3664 3669 2002-01-23 Fernando Perez <fperez@colorado.edu>
3665 3670
3666 3671 * IPython/iplib.py (CachedOutput.update): Changed output memory
3667 3672 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3668 3673 input history we still use _i. Did this b/c these variable are
3669 3674 very commonly used in interactive work, so the less we need to
3670 3675 type the better off we are.
3671 3676 (Magic.magic_prun): updated @prun to better handle the namespaces
3672 3677 the file will run in, including a fix for __name__ not being set
3673 3678 before.
3674 3679
3675 3680 2002-01-20 Fernando Perez <fperez@colorado.edu>
3676 3681
3677 3682 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3678 3683 extra garbage for Python 2.2. Need to look more carefully into
3679 3684 this later.
3680 3685
3681 3686 2002-01-19 Fernando Perez <fperez@colorado.edu>
3682 3687
3683 3688 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3684 3689 display SyntaxError exceptions properly formatted when they occur
3685 3690 (they can be triggered by imported code).
3686 3691
3687 3692 2002-01-18 Fernando Perez <fperez@colorado.edu>
3688 3693
3689 3694 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3690 3695 SyntaxError exceptions are reported nicely formatted, instead of
3691 3696 spitting out only offset information as before.
3692 3697 (Magic.magic_prun): Added the @prun function for executing
3693 3698 programs with command line args inside IPython.
3694 3699
3695 3700 2002-01-16 Fernando Perez <fperez@colorado.edu>
3696 3701
3697 3702 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3698 3703 to *not* include the last item given in a range. This brings their
3699 3704 behavior in line with Python's slicing:
3700 3705 a[n1:n2] -> a[n1]...a[n2-1]
3701 3706 It may be a bit less convenient, but I prefer to stick to Python's
3702 3707 conventions *everywhere*, so users never have to wonder.
3703 3708 (Magic.magic_macro): Added @macro function to ease the creation of
3704 3709 macros.
3705 3710
3706 3711 2002-01-05 Fernando Perez <fperez@colorado.edu>
3707 3712
3708 3713 * Released 0.2.4.
3709 3714
3710 3715 * IPython/iplib.py (Magic.magic_pdef):
3711 3716 (InteractiveShell.safe_execfile): report magic lines and error
3712 3717 lines without line numbers so one can easily copy/paste them for
3713 3718 re-execution.
3714 3719
3715 3720 * Updated manual with recent changes.
3716 3721
3717 3722 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3718 3723 docstring printing when class? is called. Very handy for knowing
3719 3724 how to create class instances (as long as __init__ is well
3720 3725 documented, of course :)
3721 3726 (Magic.magic_doc): print both class and constructor docstrings.
3722 3727 (Magic.magic_pdef): give constructor info if passed a class and
3723 3728 __call__ info for callable object instances.
3724 3729
3725 3730 2002-01-04 Fernando Perez <fperez@colorado.edu>
3726 3731
3727 3732 * Made deep_reload() off by default. It doesn't always work
3728 3733 exactly as intended, so it's probably safer to have it off. It's
3729 3734 still available as dreload() anyway, so nothing is lost.
3730 3735
3731 3736 2002-01-02 Fernando Perez <fperez@colorado.edu>
3732 3737
3733 3738 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3734 3739 so I wanted an updated release).
3735 3740
3736 3741 2001-12-27 Fernando Perez <fperez@colorado.edu>
3737 3742
3738 3743 * IPython/iplib.py (InteractiveShell.interact): Added the original
3739 3744 code from 'code.py' for this module in order to change the
3740 3745 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3741 3746 the history cache would break when the user hit Ctrl-C, and
3742 3747 interact() offers no way to add any hooks to it.
3743 3748
3744 3749 2001-12-23 Fernando Perez <fperez@colorado.edu>
3745 3750
3746 3751 * setup.py: added check for 'MANIFEST' before trying to remove
3747 3752 it. Thanks to Sean Reifschneider.
3748 3753
3749 3754 2001-12-22 Fernando Perez <fperez@colorado.edu>
3750 3755
3751 3756 * Released 0.2.2.
3752 3757
3753 3758 * Finished (reasonably) writing the manual. Later will add the
3754 3759 python-standard navigation stylesheets, but for the time being
3755 3760 it's fairly complete. Distribution will include html and pdf
3756 3761 versions.
3757 3762
3758 3763 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3759 3764 (MayaVi author).
3760 3765
3761 3766 2001-12-21 Fernando Perez <fperez@colorado.edu>
3762 3767
3763 3768 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3764 3769 good public release, I think (with the manual and the distutils
3765 3770 installer). The manual can use some work, but that can go
3766 3771 slowly. Otherwise I think it's quite nice for end users. Next
3767 3772 summer, rewrite the guts of it...
3768 3773
3769 3774 * Changed format of ipythonrc files to use whitespace as the
3770 3775 separator instead of an explicit '='. Cleaner.
3771 3776
3772 3777 2001-12-20 Fernando Perez <fperez@colorado.edu>
3773 3778
3774 3779 * Started a manual in LyX. For now it's just a quick merge of the
3775 3780 various internal docstrings and READMEs. Later it may grow into a
3776 3781 nice, full-blown manual.
3777 3782
3778 3783 * Set up a distutils based installer. Installation should now be
3779 3784 trivially simple for end-users.
3780 3785
3781 3786 2001-12-11 Fernando Perez <fperez@colorado.edu>
3782 3787
3783 3788 * Released 0.2.0. First public release, announced it at
3784 3789 comp.lang.python. From now on, just bugfixes...
3785 3790
3786 3791 * Went through all the files, set copyright/license notices and
3787 3792 cleaned up things. Ready for release.
3788 3793
3789 3794 2001-12-10 Fernando Perez <fperez@colorado.edu>
3790 3795
3791 3796 * Changed the first-time installer not to use tarfiles. It's more
3792 3797 robust now and less unix-dependent. Also makes it easier for
3793 3798 people to later upgrade versions.
3794 3799
3795 3800 * Changed @exit to @abort to reflect the fact that it's pretty
3796 3801 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3797 3802 becomes significant only when IPyhton is embedded: in that case,
3798 3803 C-D closes IPython only, but @abort kills the enclosing program
3799 3804 too (unless it had called IPython inside a try catching
3800 3805 SystemExit).
3801 3806
3802 3807 * Created Shell module which exposes the actuall IPython Shell
3803 3808 classes, currently the normal and the embeddable one. This at
3804 3809 least offers a stable interface we won't need to change when
3805 3810 (later) the internals are rewritten. That rewrite will be confined
3806 3811 to iplib and ipmaker, but the Shell interface should remain as is.
3807 3812
3808 3813 * Added embed module which offers an embeddable IPShell object,
3809 3814 useful to fire up IPython *inside* a running program. Great for
3810 3815 debugging or dynamical data analysis.
3811 3816
3812 3817 2001-12-08 Fernando Perez <fperez@colorado.edu>
3813 3818
3814 3819 * Fixed small bug preventing seeing info from methods of defined
3815 3820 objects (incorrect namespace in _ofind()).
3816 3821
3817 3822 * Documentation cleanup. Moved the main usage docstrings to a
3818 3823 separate file, usage.py (cleaner to maintain, and hopefully in the
3819 3824 future some perlpod-like way of producing interactive, man and
3820 3825 html docs out of it will be found).
3821 3826
3822 3827 * Added @profile to see your profile at any time.
3823 3828
3824 3829 * Added @p as an alias for 'print'. It's especially convenient if
3825 3830 using automagic ('p x' prints x).
3826 3831
3827 3832 * Small cleanups and fixes after a pychecker run.
3828 3833
3829 3834 * Changed the @cd command to handle @cd - and @cd -<n> for
3830 3835 visiting any directory in _dh.
3831 3836
3832 3837 * Introduced _dh, a history of visited directories. @dhist prints
3833 3838 it out with numbers.
3834 3839
3835 3840 2001-12-07 Fernando Perez <fperez@colorado.edu>
3836 3841
3837 3842 * Released 0.1.22
3838 3843
3839 3844 * Made initialization a bit more robust against invalid color
3840 3845 options in user input (exit, not traceback-crash).
3841 3846
3842 3847 * Changed the bug crash reporter to write the report only in the
3843 3848 user's .ipython directory. That way IPython won't litter people's
3844 3849 hard disks with crash files all over the place. Also print on
3845 3850 screen the necessary mail command.
3846 3851
3847 3852 * With the new ultraTB, implemented LightBG color scheme for light
3848 3853 background terminals. A lot of people like white backgrounds, so I
3849 3854 guess we should at least give them something readable.
3850 3855
3851 3856 2001-12-06 Fernando Perez <fperez@colorado.edu>
3852 3857
3853 3858 * Modified the structure of ultraTB. Now there's a proper class
3854 3859 for tables of color schemes which allow adding schemes easily and
3855 3860 switching the active scheme without creating a new instance every
3856 3861 time (which was ridiculous). The syntax for creating new schemes
3857 3862 is also cleaner. I think ultraTB is finally done, with a clean
3858 3863 class structure. Names are also much cleaner (now there's proper
3859 3864 color tables, no need for every variable to also have 'color' in
3860 3865 its name).
3861 3866
3862 3867 * Broke down genutils into separate files. Now genutils only
3863 3868 contains utility functions, and classes have been moved to their
3864 3869 own files (they had enough independent functionality to warrant
3865 3870 it): ConfigLoader, OutputTrap, Struct.
3866 3871
3867 3872 2001-12-05 Fernando Perez <fperez@colorado.edu>
3868 3873
3869 3874 * IPython turns 21! Released version 0.1.21, as a candidate for
3870 3875 public consumption. If all goes well, release in a few days.
3871 3876
3872 3877 * Fixed path bug (files in Extensions/ directory wouldn't be found
3873 3878 unless IPython/ was explicitly in sys.path).
3874 3879
3875 3880 * Extended the FlexCompleter class as MagicCompleter to allow
3876 3881 completion of @-starting lines.
3877 3882
3878 3883 * Created __release__.py file as a central repository for release
3879 3884 info that other files can read from.
3880 3885
3881 3886 * Fixed small bug in logging: when logging was turned on in
3882 3887 mid-session, old lines with special meanings (!@?) were being
3883 3888 logged without the prepended comment, which is necessary since
3884 3889 they are not truly valid python syntax. This should make session
3885 3890 restores produce less errors.
3886 3891
3887 3892 * The namespace cleanup forced me to make a FlexCompleter class
3888 3893 which is nothing but a ripoff of rlcompleter, but with selectable
3889 3894 namespace (rlcompleter only works in __main__.__dict__). I'll try
3890 3895 to submit a note to the authors to see if this change can be
3891 3896 incorporated in future rlcompleter releases (Dec.6: done)
3892 3897
3893 3898 * More fixes to namespace handling. It was a mess! Now all
3894 3899 explicit references to __main__.__dict__ are gone (except when
3895 3900 really needed) and everything is handled through the namespace
3896 3901 dicts in the IPython instance. We seem to be getting somewhere
3897 3902 with this, finally...
3898 3903
3899 3904 * Small documentation updates.
3900 3905
3901 3906 * Created the Extensions directory under IPython (with an
3902 3907 __init__.py). Put the PhysicalQ stuff there. This directory should
3903 3908 be used for all special-purpose extensions.
3904 3909
3905 3910 * File renaming:
3906 3911 ipythonlib --> ipmaker
3907 3912 ipplib --> iplib
3908 3913 This makes a bit more sense in terms of what these files actually do.
3909 3914
3910 3915 * Moved all the classes and functions in ipythonlib to ipplib, so
3911 3916 now ipythonlib only has make_IPython(). This will ease up its
3912 3917 splitting in smaller functional chunks later.
3913 3918
3914 3919 * Cleaned up (done, I think) output of @whos. Better column
3915 3920 formatting, and now shows str(var) for as much as it can, which is
3916 3921 typically what one gets with a 'print var'.
3917 3922
3918 3923 2001-12-04 Fernando Perez <fperez@colorado.edu>
3919 3924
3920 3925 * Fixed namespace problems. Now builtin/IPyhton/user names get
3921 3926 properly reported in their namespace. Internal namespace handling
3922 3927 is finally getting decent (not perfect yet, but much better than
3923 3928 the ad-hoc mess we had).
3924 3929
3925 3930 * Removed -exit option. If people just want to run a python
3926 3931 script, that's what the normal interpreter is for. Less
3927 3932 unnecessary options, less chances for bugs.
3928 3933
3929 3934 * Added a crash handler which generates a complete post-mortem if
3930 3935 IPython crashes. This will help a lot in tracking bugs down the
3931 3936 road.
3932 3937
3933 3938 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
3934 3939 which were boud to functions being reassigned would bypass the
3935 3940 logger, breaking the sync of _il with the prompt counter. This
3936 3941 would then crash IPython later when a new line was logged.
3937 3942
3938 3943 2001-12-02 Fernando Perez <fperez@colorado.edu>
3939 3944
3940 3945 * Made IPython a package. This means people don't have to clutter
3941 3946 their sys.path with yet another directory. Changed the INSTALL
3942 3947 file accordingly.
3943 3948
3944 3949 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
3945 3950 sorts its output (so @who shows it sorted) and @whos formats the
3946 3951 table according to the width of the first column. Nicer, easier to
3947 3952 read. Todo: write a generic table_format() which takes a list of
3948 3953 lists and prints it nicely formatted, with optional row/column
3949 3954 separators and proper padding and justification.
3950 3955
3951 3956 * Released 0.1.20
3952 3957
3953 3958 * Fixed bug in @log which would reverse the inputcache list (a
3954 3959 copy operation was missing).
3955 3960
3956 3961 * Code cleanup. @config was changed to use page(). Better, since
3957 3962 its output is always quite long.
3958 3963
3959 3964 * Itpl is back as a dependency. I was having too many problems
3960 3965 getting the parametric aliases to work reliably, and it's just
3961 3966 easier to code weird string operations with it than playing %()s
3962 3967 games. It's only ~6k, so I don't think it's too big a deal.
3963 3968
3964 3969 * Found (and fixed) a very nasty bug with history. !lines weren't
3965 3970 getting cached, and the out of sync caches would crash
3966 3971 IPython. Fixed it by reorganizing the prefilter/handlers/logger
3967 3972 division of labor a bit better. Bug fixed, cleaner structure.
3968 3973
3969 3974 2001-12-01 Fernando Perez <fperez@colorado.edu>
3970 3975
3971 3976 * Released 0.1.19
3972 3977
3973 3978 * Added option -n to @hist to prevent line number printing. Much
3974 3979 easier to copy/paste code this way.
3975 3980
3976 3981 * Created global _il to hold the input list. Allows easy
3977 3982 re-execution of blocks of code by slicing it (inspired by Janko's
3978 3983 comment on 'macros').
3979 3984
3980 3985 * Small fixes and doc updates.
3981 3986
3982 3987 * Rewrote @history function (was @h). Renamed it to @hist, @h is
3983 3988 much too fragile with automagic. Handles properly multi-line
3984 3989 statements and takes parameters.
3985 3990
3986 3991 2001-11-30 Fernando Perez <fperez@colorado.edu>
3987 3992
3988 3993 * Version 0.1.18 released.
3989 3994
3990 3995 * Fixed nasty namespace bug in initial module imports.
3991 3996
3992 3997 * Added copyright/license notes to all code files (except
3993 3998 DPyGetOpt). For the time being, LGPL. That could change.
3994 3999
3995 4000 * Rewrote a much nicer README, updated INSTALL, cleaned up
3996 4001 ipythonrc-* samples.
3997 4002
3998 4003 * Overall code/documentation cleanup. Basically ready for
3999 4004 release. Only remaining thing: licence decision (LGPL?).
4000 4005
4001 4006 * Converted load_config to a class, ConfigLoader. Now recursion
4002 4007 control is better organized. Doesn't include the same file twice.
4003 4008
4004 4009 2001-11-29 Fernando Perez <fperez@colorado.edu>
4005 4010
4006 4011 * Got input history working. Changed output history variables from
4007 4012 _p to _o so that _i is for input and _o for output. Just cleaner
4008 4013 convention.
4009 4014
4010 4015 * Implemented parametric aliases. This pretty much allows the
4011 4016 alias system to offer full-blown shell convenience, I think.
4012 4017
4013 4018 * Version 0.1.17 released, 0.1.18 opened.
4014 4019
4015 4020 * dot_ipython/ipythonrc (alias): added documentation.
4016 4021 (xcolor): Fixed small bug (xcolors -> xcolor)
4017 4022
4018 4023 * Changed the alias system. Now alias is a magic command to define
4019 4024 aliases just like the shell. Rationale: the builtin magics should
4020 4025 be there for things deeply connected to IPython's
4021 4026 architecture. And this is a much lighter system for what I think
4022 4027 is the really important feature: allowing users to define quickly
4023 4028 magics that will do shell things for them, so they can customize
4024 4029 IPython easily to match their work habits. If someone is really
4025 4030 desperate to have another name for a builtin alias, they can
4026 4031 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4027 4032 works.
4028 4033
4029 4034 2001-11-28 Fernando Perez <fperez@colorado.edu>
4030 4035
4031 4036 * Changed @file so that it opens the source file at the proper
4032 4037 line. Since it uses less, if your EDITOR environment is
4033 4038 configured, typing v will immediately open your editor of choice
4034 4039 right at the line where the object is defined. Not as quick as
4035 4040 having a direct @edit command, but for all intents and purposes it
4036 4041 works. And I don't have to worry about writing @edit to deal with
4037 4042 all the editors, less does that.
4038 4043
4039 4044 * Version 0.1.16 released, 0.1.17 opened.
4040 4045
4041 4046 * Fixed some nasty bugs in the page/page_dumb combo that could
4042 4047 crash IPython.
4043 4048
4044 4049 2001-11-27 Fernando Perez <fperez@colorado.edu>
4045 4050
4046 4051 * Version 0.1.15 released, 0.1.16 opened.
4047 4052
4048 4053 * Finally got ? and ?? to work for undefined things: now it's
4049 4054 possible to type {}.get? and get information about the get method
4050 4055 of dicts, or os.path? even if only os is defined (so technically
4051 4056 os.path isn't). Works at any level. For example, after import os,
4052 4057 os?, os.path?, os.path.abspath? all work. This is great, took some
4053 4058 work in _ofind.
4054 4059
4055 4060 * Fixed more bugs with logging. The sanest way to do it was to add
4056 4061 to @log a 'mode' parameter. Killed two in one shot (this mode
4057 4062 option was a request of Janko's). I think it's finally clean
4058 4063 (famous last words).
4059 4064
4060 4065 * Added a page_dumb() pager which does a decent job of paging on
4061 4066 screen, if better things (like less) aren't available. One less
4062 4067 unix dependency (someday maybe somebody will port this to
4063 4068 windows).
4064 4069
4065 4070 * Fixed problem in magic_log: would lock of logging out if log
4066 4071 creation failed (because it would still think it had succeeded).
4067 4072
4068 4073 * Improved the page() function using curses to auto-detect screen
4069 4074 size. Now it can make a much better decision on whether to print
4070 4075 or page a string. Option screen_length was modified: a value 0
4071 4076 means auto-detect, and that's the default now.
4072 4077
4073 4078 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4074 4079 go out. I'll test it for a few days, then talk to Janko about
4075 4080 licences and announce it.
4076 4081
4077 4082 * Fixed the length of the auto-generated ---> prompt which appears
4078 4083 for auto-parens and auto-quotes. Getting this right isn't trivial,
4079 4084 with all the color escapes, different prompt types and optional
4080 4085 separators. But it seems to be working in all the combinations.
4081 4086
4082 4087 2001-11-26 Fernando Perez <fperez@colorado.edu>
4083 4088
4084 4089 * Wrote a regexp filter to get option types from the option names
4085 4090 string. This eliminates the need to manually keep two duplicate
4086 4091 lists.
4087 4092
4088 4093 * Removed the unneeded check_option_names. Now options are handled
4089 4094 in a much saner manner and it's easy to visually check that things
4090 4095 are ok.
4091 4096
4092 4097 * Updated version numbers on all files I modified to carry a
4093 4098 notice so Janko and Nathan have clear version markers.
4094 4099
4095 4100 * Updated docstring for ultraTB with my changes. I should send
4096 4101 this to Nathan.
4097 4102
4098 4103 * Lots of small fixes. Ran everything through pychecker again.
4099 4104
4100 4105 * Made loading of deep_reload an cmd line option. If it's not too
4101 4106 kosher, now people can just disable it. With -nodeep_reload it's
4102 4107 still available as dreload(), it just won't overwrite reload().
4103 4108
4104 4109 * Moved many options to the no| form (-opt and -noopt
4105 4110 accepted). Cleaner.
4106 4111
4107 4112 * Changed magic_log so that if called with no parameters, it uses
4108 4113 'rotate' mode. That way auto-generated logs aren't automatically
4109 4114 over-written. For normal logs, now a backup is made if it exists
4110 4115 (only 1 level of backups). A new 'backup' mode was added to the
4111 4116 Logger class to support this. This was a request by Janko.
4112 4117
4113 4118 * Added @logoff/@logon to stop/restart an active log.
4114 4119
4115 4120 * Fixed a lot of bugs in log saving/replay. It was pretty
4116 4121 broken. Now special lines (!@,/) appear properly in the command
4117 4122 history after a log replay.
4118 4123
4119 4124 * Tried and failed to implement full session saving via pickle. My
4120 4125 idea was to pickle __main__.__dict__, but modules can't be
4121 4126 pickled. This would be a better alternative to replaying logs, but
4122 4127 seems quite tricky to get to work. Changed -session to be called
4123 4128 -logplay, which more accurately reflects what it does. And if we
4124 4129 ever get real session saving working, -session is now available.
4125 4130
4126 4131 * Implemented color schemes for prompts also. As for tracebacks,
4127 4132 currently only NoColor and Linux are supported. But now the
4128 4133 infrastructure is in place, based on a generic ColorScheme
4129 4134 class. So writing and activating new schemes both for the prompts
4130 4135 and the tracebacks should be straightforward.
4131 4136
4132 4137 * Version 0.1.13 released, 0.1.14 opened.
4133 4138
4134 4139 * Changed handling of options for output cache. Now counter is
4135 4140 hardwired starting at 1 and one specifies the maximum number of
4136 4141 entries *in the outcache* (not the max prompt counter). This is
4137 4142 much better, since many statements won't increase the cache
4138 4143 count. It also eliminated some confusing options, now there's only
4139 4144 one: cache_size.
4140 4145
4141 4146 * Added 'alias' magic function and magic_alias option in the
4142 4147 ipythonrc file. Now the user can easily define whatever names he
4143 4148 wants for the magic functions without having to play weird
4144 4149 namespace games. This gives IPython a real shell-like feel.
4145 4150
4146 4151 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4147 4152 @ or not).
4148 4153
4149 4154 This was one of the last remaining 'visible' bugs (that I know
4150 4155 of). I think if I can clean up the session loading so it works
4151 4156 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4152 4157 about licensing).
4153 4158
4154 4159 2001-11-25 Fernando Perez <fperez@colorado.edu>
4155 4160
4156 4161 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4157 4162 there's a cleaner distinction between what ? and ?? show.
4158 4163
4159 4164 * Added screen_length option. Now the user can define his own
4160 4165 screen size for page() operations.
4161 4166
4162 4167 * Implemented magic shell-like functions with automatic code
4163 4168 generation. Now adding another function is just a matter of adding
4164 4169 an entry to a dict, and the function is dynamically generated at
4165 4170 run-time. Python has some really cool features!
4166 4171
4167 4172 * Renamed many options to cleanup conventions a little. Now all
4168 4173 are lowercase, and only underscores where needed. Also in the code
4169 4174 option name tables are clearer.
4170 4175
4171 4176 * Changed prompts a little. Now input is 'In [n]:' instead of
4172 4177 'In[n]:='. This allows it the numbers to be aligned with the
4173 4178 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4174 4179 Python (it was a Mathematica thing). The '...' continuation prompt
4175 4180 was also changed a little to align better.
4176 4181
4177 4182 * Fixed bug when flushing output cache. Not all _p<n> variables
4178 4183 exist, so their deletion needs to be wrapped in a try:
4179 4184
4180 4185 * Figured out how to properly use inspect.formatargspec() (it
4181 4186 requires the args preceded by *). So I removed all the code from
4182 4187 _get_pdef in Magic, which was just replicating that.
4183 4188
4184 4189 * Added test to prefilter to allow redefining magic function names
4185 4190 as variables. This is ok, since the @ form is always available,
4186 4191 but whe should allow the user to define a variable called 'ls' if
4187 4192 he needs it.
4188 4193
4189 4194 * Moved the ToDo information from README into a separate ToDo.
4190 4195
4191 4196 * General code cleanup and small bugfixes. I think it's close to a
4192 4197 state where it can be released, obviously with a big 'beta'
4193 4198 warning on it.
4194 4199
4195 4200 * Got the magic function split to work. Now all magics are defined
4196 4201 in a separate class. It just organizes things a bit, and now
4197 4202 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4198 4203 was too long).
4199 4204
4200 4205 * Changed @clear to @reset to avoid potential confusions with
4201 4206 the shell command clear. Also renamed @cl to @clear, which does
4202 4207 exactly what people expect it to from their shell experience.
4203 4208
4204 4209 Added a check to the @reset command (since it's so
4205 4210 destructive, it's probably a good idea to ask for confirmation).
4206 4211 But now reset only works for full namespace resetting. Since the
4207 4212 del keyword is already there for deleting a few specific
4208 4213 variables, I don't see the point of having a redundant magic
4209 4214 function for the same task.
4210 4215
4211 4216 2001-11-24 Fernando Perez <fperez@colorado.edu>
4212 4217
4213 4218 * Updated the builtin docs (esp. the ? ones).
4214 4219
4215 4220 * Ran all the code through pychecker. Not terribly impressed with
4216 4221 it: lots of spurious warnings and didn't really find anything of
4217 4222 substance (just a few modules being imported and not used).
4218 4223
4219 4224 * Implemented the new ultraTB functionality into IPython. New
4220 4225 option: xcolors. This chooses color scheme. xmode now only selects
4221 4226 between Plain and Verbose. Better orthogonality.
4222 4227
4223 4228 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4224 4229 mode and color scheme for the exception handlers. Now it's
4225 4230 possible to have the verbose traceback with no coloring.
4226 4231
4227 4232 2001-11-23 Fernando Perez <fperez@colorado.edu>
4228 4233
4229 4234 * Version 0.1.12 released, 0.1.13 opened.
4230 4235
4231 4236 * Removed option to set auto-quote and auto-paren escapes by
4232 4237 user. The chances of breaking valid syntax are just too high. If
4233 4238 someone *really* wants, they can always dig into the code.
4234 4239
4235 4240 * Made prompt separators configurable.
4236 4241
4237 4242 2001-11-22 Fernando Perez <fperez@colorado.edu>
4238 4243
4239 4244 * Small bugfixes in many places.
4240 4245
4241 4246 * Removed the MyCompleter class from ipplib. It seemed redundant
4242 4247 with the C-p,C-n history search functionality. Less code to
4243 4248 maintain.
4244 4249
4245 4250 * Moved all the original ipython.py code into ipythonlib.py. Right
4246 4251 now it's just one big dump into a function called make_IPython, so
4247 4252 no real modularity has been gained. But at least it makes the
4248 4253 wrapper script tiny, and since ipythonlib is a module, it gets
4249 4254 compiled and startup is much faster.
4250 4255
4251 4256 This is a reasobably 'deep' change, so we should test it for a
4252 4257 while without messing too much more with the code.
4253 4258
4254 4259 2001-11-21 Fernando Perez <fperez@colorado.edu>
4255 4260
4256 4261 * Version 0.1.11 released, 0.1.12 opened for further work.
4257 4262
4258 4263 * Removed dependency on Itpl. It was only needed in one place. It
4259 4264 would be nice if this became part of python, though. It makes life
4260 4265 *a lot* easier in some cases.
4261 4266
4262 4267 * Simplified the prefilter code a bit. Now all handlers are
4263 4268 expected to explicitly return a value (at least a blank string).
4264 4269
4265 4270 * Heavy edits in ipplib. Removed the help system altogether. Now
4266 4271 obj?/?? is used for inspecting objects, a magic @doc prints
4267 4272 docstrings, and full-blown Python help is accessed via the 'help'
4268 4273 keyword. This cleans up a lot of code (less to maintain) and does
4269 4274 the job. Since 'help' is now a standard Python component, might as
4270 4275 well use it and remove duplicate functionality.
4271 4276
4272 4277 Also removed the option to use ipplib as a standalone program. By
4273 4278 now it's too dependent on other parts of IPython to function alone.
4274 4279
4275 4280 * Fixed bug in genutils.pager. It would crash if the pager was
4276 4281 exited immediately after opening (broken pipe).
4277 4282
4278 4283 * Trimmed down the VerboseTB reporting a little. The header is
4279 4284 much shorter now and the repeated exception arguments at the end
4280 4285 have been removed. For interactive use the old header seemed a bit
4281 4286 excessive.
4282 4287
4283 4288 * Fixed small bug in output of @whos for variables with multi-word
4284 4289 types (only first word was displayed).
4285 4290
4286 4291 2001-11-17 Fernando Perez <fperez@colorado.edu>
4287 4292
4288 4293 * Version 0.1.10 released, 0.1.11 opened for further work.
4289 4294
4290 4295 * Modified dirs and friends. dirs now *returns* the stack (not
4291 4296 prints), so one can manipulate it as a variable. Convenient to
4292 4297 travel along many directories.
4293 4298
4294 4299 * Fixed bug in magic_pdef: would only work with functions with
4295 4300 arguments with default values.
4296 4301
4297 4302 2001-11-14 Fernando Perez <fperez@colorado.edu>
4298 4303
4299 4304 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4300 4305 example with IPython. Various other minor fixes and cleanups.
4301 4306
4302 4307 * Version 0.1.9 released, 0.1.10 opened for further work.
4303 4308
4304 4309 * Added sys.path to the list of directories searched in the
4305 4310 execfile= option. It used to be the current directory and the
4306 4311 user's IPYTHONDIR only.
4307 4312
4308 4313 2001-11-13 Fernando Perez <fperez@colorado.edu>
4309 4314
4310 4315 * Reinstated the raw_input/prefilter separation that Janko had
4311 4316 initially. This gives a more convenient setup for extending the
4312 4317 pre-processor from the outside: raw_input always gets a string,
4313 4318 and prefilter has to process it. We can then redefine prefilter
4314 4319 from the outside and implement extensions for special
4315 4320 purposes.
4316 4321
4317 4322 Today I got one for inputting PhysicalQuantity objects
4318 4323 (from Scientific) without needing any function calls at
4319 4324 all. Extremely convenient, and it's all done as a user-level
4320 4325 extension (no IPython code was touched). Now instead of:
4321 4326 a = PhysicalQuantity(4.2,'m/s**2')
4322 4327 one can simply say
4323 4328 a = 4.2 m/s**2
4324 4329 or even
4325 4330 a = 4.2 m/s^2
4326 4331
4327 4332 I use this, but it's also a proof of concept: IPython really is
4328 4333 fully user-extensible, even at the level of the parsing of the
4329 4334 command line. It's not trivial, but it's perfectly doable.
4330 4335
4331 4336 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4332 4337 the problem of modules being loaded in the inverse order in which
4333 4338 they were defined in
4334 4339
4335 4340 * Version 0.1.8 released, 0.1.9 opened for further work.
4336 4341
4337 4342 * Added magics pdef, source and file. They respectively show the
4338 4343 definition line ('prototype' in C), source code and full python
4339 4344 file for any callable object. The object inspector oinfo uses
4340 4345 these to show the same information.
4341 4346
4342 4347 * Version 0.1.7 released, 0.1.8 opened for further work.
4343 4348
4344 4349 * Separated all the magic functions into a class called Magic. The
4345 4350 InteractiveShell class was becoming too big for Xemacs to handle
4346 4351 (de-indenting a line would lock it up for 10 seconds while it
4347 4352 backtracked on the whole class!)
4348 4353
4349 4354 FIXME: didn't work. It can be done, but right now namespaces are
4350 4355 all messed up. Do it later (reverted it for now, so at least
4351 4356 everything works as before).
4352 4357
4353 4358 * Got the object introspection system (magic_oinfo) working! I
4354 4359 think this is pretty much ready for release to Janko, so he can
4355 4360 test it for a while and then announce it. Pretty much 100% of what
4356 4361 I wanted for the 'phase 1' release is ready. Happy, tired.
4357 4362
4358 4363 2001-11-12 Fernando Perez <fperez@colorado.edu>
4359 4364
4360 4365 * Version 0.1.6 released, 0.1.7 opened for further work.
4361 4366
4362 4367 * Fixed bug in printing: it used to test for truth before
4363 4368 printing, so 0 wouldn't print. Now checks for None.
4364 4369
4365 4370 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4366 4371 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4367 4372 reaches by hand into the outputcache. Think of a better way to do
4368 4373 this later.
4369 4374
4370 4375 * Various small fixes thanks to Nathan's comments.
4371 4376
4372 4377 * Changed magic_pprint to magic_Pprint. This way it doesn't
4373 4378 collide with pprint() and the name is consistent with the command
4374 4379 line option.
4375 4380
4376 4381 * Changed prompt counter behavior to be fully like
4377 4382 Mathematica's. That is, even input that doesn't return a result
4378 4383 raises the prompt counter. The old behavior was kind of confusing
4379 4384 (getting the same prompt number several times if the operation
4380 4385 didn't return a result).
4381 4386
4382 4387 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4383 4388
4384 4389 * Fixed -Classic mode (wasn't working anymore).
4385 4390
4386 4391 * Added colored prompts using Nathan's new code. Colors are
4387 4392 currently hardwired, they can be user-configurable. For
4388 4393 developers, they can be chosen in file ipythonlib.py, at the
4389 4394 beginning of the CachedOutput class def.
4390 4395
4391 4396 2001-11-11 Fernando Perez <fperez@colorado.edu>
4392 4397
4393 4398 * Version 0.1.5 released, 0.1.6 opened for further work.
4394 4399
4395 4400 * Changed magic_env to *return* the environment as a dict (not to
4396 4401 print it). This way it prints, but it can also be processed.
4397 4402
4398 4403 * Added Verbose exception reporting to interactive
4399 4404 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4400 4405 traceback. Had to make some changes to the ultraTB file. This is
4401 4406 probably the last 'big' thing in my mental todo list. This ties
4402 4407 in with the next entry:
4403 4408
4404 4409 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4405 4410 has to specify is Plain, Color or Verbose for all exception
4406 4411 handling.
4407 4412
4408 4413 * Removed ShellServices option. All this can really be done via
4409 4414 the magic system. It's easier to extend, cleaner and has automatic
4410 4415 namespace protection and documentation.
4411 4416
4412 4417 2001-11-09 Fernando Perez <fperez@colorado.edu>
4413 4418
4414 4419 * Fixed bug in output cache flushing (missing parameter to
4415 4420 __init__). Other small bugs fixed (found using pychecker).
4416 4421
4417 4422 * Version 0.1.4 opened for bugfixing.
4418 4423
4419 4424 2001-11-07 Fernando Perez <fperez@colorado.edu>
4420 4425
4421 4426 * Version 0.1.3 released, mainly because of the raw_input bug.
4422 4427
4423 4428 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4424 4429 and when testing for whether things were callable, a call could
4425 4430 actually be made to certain functions. They would get called again
4426 4431 once 'really' executed, with a resulting double call. A disaster
4427 4432 in many cases (list.reverse() would never work!).
4428 4433
4429 4434 * Removed prefilter() function, moved its code to raw_input (which
4430 4435 after all was just a near-empty caller for prefilter). This saves
4431 4436 a function call on every prompt, and simplifies the class a tiny bit.
4432 4437
4433 4438 * Fix _ip to __ip name in magic example file.
4434 4439
4435 4440 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4436 4441 work with non-gnu versions of tar.
4437 4442
4438 4443 2001-11-06 Fernando Perez <fperez@colorado.edu>
4439 4444
4440 4445 * Version 0.1.2. Just to keep track of the recent changes.
4441 4446
4442 4447 * Fixed nasty bug in output prompt routine. It used to check 'if
4443 4448 arg != None...'. Problem is, this fails if arg implements a
4444 4449 special comparison (__cmp__) which disallows comparing to
4445 4450 None. Found it when trying to use the PhysicalQuantity module from
4446 4451 ScientificPython.
4447 4452
4448 4453 2001-11-05 Fernando Perez <fperez@colorado.edu>
4449 4454
4450 4455 * Also added dirs. Now the pushd/popd/dirs family functions
4451 4456 basically like the shell, with the added convenience of going home
4452 4457 when called with no args.
4453 4458
4454 4459 * pushd/popd slightly modified to mimic shell behavior more
4455 4460 closely.
4456 4461
4457 4462 * Added env,pushd,popd from ShellServices as magic functions. I
4458 4463 think the cleanest will be to port all desired functions from
4459 4464 ShellServices as magics and remove ShellServices altogether. This
4460 4465 will provide a single, clean way of adding functionality
4461 4466 (shell-type or otherwise) to IP.
4462 4467
4463 4468 2001-11-04 Fernando Perez <fperez@colorado.edu>
4464 4469
4465 4470 * Added .ipython/ directory to sys.path. This way users can keep
4466 4471 customizations there and access them via import.
4467 4472
4468 4473 2001-11-03 Fernando Perez <fperez@colorado.edu>
4469 4474
4470 4475 * Opened version 0.1.1 for new changes.
4471 4476
4472 4477 * Changed version number to 0.1.0: first 'public' release, sent to
4473 4478 Nathan and Janko.
4474 4479
4475 4480 * Lots of small fixes and tweaks.
4476 4481
4477 4482 * Minor changes to whos format. Now strings are shown, snipped if
4478 4483 too long.
4479 4484
4480 4485 * Changed ShellServices to work on __main__ so they show up in @who
4481 4486
4482 4487 * Help also works with ? at the end of a line:
4483 4488 ?sin and sin?
4484 4489 both produce the same effect. This is nice, as often I use the
4485 4490 tab-complete to find the name of a method, but I used to then have
4486 4491 to go to the beginning of the line to put a ? if I wanted more
4487 4492 info. Now I can just add the ? and hit return. Convenient.
4488 4493
4489 4494 2001-11-02 Fernando Perez <fperez@colorado.edu>
4490 4495
4491 4496 * Python version check (>=2.1) added.
4492 4497
4493 4498 * Added LazyPython documentation. At this point the docs are quite
4494 4499 a mess. A cleanup is in order.
4495 4500
4496 4501 * Auto-installer created. For some bizarre reason, the zipfiles
4497 4502 module isn't working on my system. So I made a tar version
4498 4503 (hopefully the command line options in various systems won't kill
4499 4504 me).
4500 4505
4501 4506 * Fixes to Struct in genutils. Now all dictionary-like methods are
4502 4507 protected (reasonably).
4503 4508
4504 4509 * Added pager function to genutils and changed ? to print usage
4505 4510 note through it (it was too long).
4506 4511
4507 4512 * Added the LazyPython functionality. Works great! I changed the
4508 4513 auto-quote escape to ';', it's on home row and next to '. But
4509 4514 both auto-quote and auto-paren (still /) escapes are command-line
4510 4515 parameters.
4511 4516
4512 4517
4513 4518 2001-11-01 Fernando Perez <fperez@colorado.edu>
4514 4519
4515 4520 * Version changed to 0.0.7. Fairly large change: configuration now
4516 4521 is all stored in a directory, by default .ipython. There, all
4517 4522 config files have normal looking names (not .names)
4518 4523
4519 4524 * Version 0.0.6 Released first to Lucas and Archie as a test
4520 4525 run. Since it's the first 'semi-public' release, change version to
4521 4526 > 0.0.6 for any changes now.
4522 4527
4523 4528 * Stuff I had put in the ipplib.py changelog:
4524 4529
4525 4530 Changes to InteractiveShell:
4526 4531
4527 4532 - Made the usage message a parameter.
4528 4533
4529 4534 - Require the name of the shell variable to be given. It's a bit
4530 4535 of a hack, but allows the name 'shell' not to be hardwire in the
4531 4536 magic (@) handler, which is problematic b/c it requires
4532 4537 polluting the global namespace with 'shell'. This in turn is
4533 4538 fragile: if a user redefines a variable called shell, things
4534 4539 break.
4535 4540
4536 4541 - magic @: all functions available through @ need to be defined
4537 4542 as magic_<name>, even though they can be called simply as
4538 4543 @<name>. This allows the special command @magic to gather
4539 4544 information automatically about all existing magic functions,
4540 4545 even if they are run-time user extensions, by parsing the shell
4541 4546 instance __dict__ looking for special magic_ names.
4542 4547
4543 4548 - mainloop: added *two* local namespace parameters. This allows
4544 4549 the class to differentiate between parameters which were there
4545 4550 before and after command line initialization was processed. This
4546 4551 way, later @who can show things loaded at startup by the
4547 4552 user. This trick was necessary to make session saving/reloading
4548 4553 really work: ideally after saving/exiting/reloading a session,
4549 4554 *everythin* should look the same, including the output of @who. I
4550 4555 was only able to make this work with this double namespace
4551 4556 trick.
4552 4557
4553 4558 - added a header to the logfile which allows (almost) full
4554 4559 session restoring.
4555 4560
4556 4561 - prepend lines beginning with @ or !, with a and log
4557 4562 them. Why? !lines: may be useful to know what you did @lines:
4558 4563 they may affect session state. So when restoring a session, at
4559 4564 least inform the user of their presence. I couldn't quite get
4560 4565 them to properly re-execute, but at least the user is warned.
4561 4566
4562 4567 * Started ChangeLog.
@@ -1,392 +1,391 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 118 .B \-[no]autocall
119 119 Make IPython automatically call any callable object even if you didn't type
120 120 explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically.
121 121 .TP
122 122 .B \-[no]autoindent
123 123 Turn automatic indentation on/off.
124 124 .TP
125 125 .B \-[no]automagic
126 126 Make magic commands automatic (without needing their first character
127 to be @). Type @magic at the IPython prompt for more information.
127 to be %). Type %magic at the IPython prompt for more information.
128 128 .TP
129 .B \-[no]autoparens
130 Make IPython automatically call any callable object even if you didn't
131 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
132 automatically.
129 .B \-[no]autoedit_syntax
130 When a syntax error occurs after editing a file, automatically open the file
131 to the trouble causing line for convenient fixing.
133 132 .TP
134 133 .B \-[no]banner
135 134 Print the intial information banner (default on).
136 135 .TP
137 136 .B \-c <command>
138 137 Execute the given command string, and set sys.argv to ['c']. This is similar
139 138 to the \-c option in the normal Python interpreter.
140 139 .TP
141 140 .B \-cache_size|cs <n>
142 141 Size of the output cache (maximum number of entries to hold in
143 142 memory). The default is 1000, you can change it permanently in your
144 143 config file. Setting it to 0 completely disables the caching system,
145 144 and the minimum value accepted is 20 (if you provide a value less than
146 145 20, it is reset to 0 and a warning is issued). This limit is defined
147 146 because otherwise you'll spend more time re-flushing a too small cache
148 147 than working.
149 148 .TP
150 149 .B \-classic|cl
151 150 Gives IPython a similar feel to the classic Python prompt.
152 151 .TP
153 152 .B \-colors <scheme>
154 153 Color scheme for prompts and exception reporting. Currently
155 154 implemented: NoColor, Linux, and LightBG.
156 155 .TP
157 156 .B \-[no]color_info
158 157 IPython can display information about objects via a set of functions,
159 158 and optionally can use colors for this, syntax highlighting source
160 159 code and various other elements. However, because this information is
161 160 passed through a pager (like 'less') and many pagers get confused with
162 161 color codes, this option is off by default. You can test it and turn
163 162 it on permanently in your ipythonrc file if it works for you. As a
164 163 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
165 164 that in RedHat 7.2 doesn't.
166 165 .br
167 166 .sp 1
168 167 Test it and turn it on permanently if it works with your system. The
169 168 magic function @color_info allows you to toggle this interactively for
170 169 testing.
171 170 .TP
172 171 .B \-[no]confirm_exit
173 172 Set to confirm when you try to exit IPython with an EOF (Control-D in
174 173 Unix, Control-Z/Enter in Windows). Note that using the magic functions
175 174 @Exit or @Quit you can force a direct exit, bypassing any
176 175 confirmation.
177 176 .TP
178 177 .B \-[no]debug
179 178 Show information about the loading process. Very useful to pin down
180 179 problems with your configuration files or to get details about session
181 180 restores.
182 181 .TP
183 182 .B \-[no]deep_reload
184 183 IPython can use the deep_reload module which reloads changes in
185 184 modules recursively (it replaces the reload() function, so you don't
186 185 need to change anything to use it). deep_reload() forces a full reload
187 186 of modules whose code may have changed, which the default reload()
188 187 function does not.
189 188 .br
190 189 .sp 1
191 190 When deep_reload is off, IPython will use the normal reload(), but
192 191 deep_reload will still be available as dreload(). This feature is off
193 192 by default [which means that you have both normal reload() and
194 193 dreload()].
195 194 .TP
196 195 .B \-editor <name>
197 196 Which editor to use with the @edit command. By default, IPython will
198 197 honor your EDITOR environment variable (if not set, vi is the Unix
199 198 default and notepad the Windows one). Since this editor is invoked on
200 199 the fly by IPython and is meant for editing small code snippets, you
201 200 may want to use a small, lightweight editor here (in case your default
202 201 EDITOR is something like Emacs).
203 202 .TP
204 203 .B \-ipythondir <name>
205 204 The name of your IPython configuration directory IPYTHONDIR. This can
206 205 also be specified through the environment variable IPYTHONDIR.
207 206 .TP
208 207 .B \-log|l
209 208 Generate a log file of all input. The file is named ipython.log in
210 209 your current directory (which prevents logs from multiple IPython
211 210 sessions from trampling each other). You can use this to later restore
212 211 a session by loading your logfile as a file to be executed with option
213 212 -logplay (see below).
214 213 .TP
215 214 .B \-logfile|lf
216 215 Specifu the name of your logfile.
217 216 .TP
218 217 .B \-logplay|lp
219 218 Replay a previous log. For restoring a session as close as possible to
220 219 the state you left it in, use this option (don't just run the
221 220 logfile). With \-logplay, IPython will try to reconstruct the previous
222 221 working environment in full, not just execute the commands in the
223 222 logfile.
224 223 .br
225 224 .sh 1
226 225 When a session is restored, logging is automatically turned on again
227 226 with the name of the logfile it was invoked with (it is read from the
228 227 log header). So once you've turned logging on for a session, you can
229 228 quit IPython and reload it as many times as you want and it will
230 229 continue to log its history and restore from the beginning every time.
231 230 .br
232 231 .sp 1
233 232 Caveats: there are limitations in this option. The history variables
234 233 _i*,_* and _dh don't get restored properly. In the future we will try
235 234 to implement full session saving by writing and retrieving a
236 235 'snapshot' of the memory state of IPython. But our first attempts
237 236 failed because of inherent limitations of Python's Pickle module, so
238 237 this may have to wait.
239 238 .TP
240 239 .B \-[no]messages
241 240 Print messages which IPython collects about its startup process
242 241 (default on).
243 242 .TP
244 243 .B \-[no]pdb
245 244 Automatically call the pdb debugger after every uncaught exception. If
246 245 you are used to debugging using pdb, this puts you automatically
247 246 inside of it after any call (either in IPython or in code called by
248 247 it) which triggers an exception which goes uncaught.
249 248 .TP
250 249 .B \-[no]pprint
251 250 IPython can optionally use the pprint (pretty printer) module for
252 251 displaying results. pprint tends to give a nicer display of nested
253 252 data structures. If you like it, you can turn it on permanently in
254 253 your config file (default off).
255 254 .TP
256 255 .B \-profile|p <name>
257 256 Assume that your config file is ipythonrc-<name> (looks in current dir
258 257 first, then in IPYTHONDIR). This is a quick way to keep and load
259 258 multiple config files for different tasks, especially if you use the
260 259 include option of config files. You can keep a basic
261 260 IPYTHONDIR/ipythonrc file and then have other 'profiles' which include
262 261 this one and load extra things for particular tasks. For example:
263 262 .br
264 263 .sp 1
265 264 1) $HOME/.ipython/ipythonrc : load basic things you always want.
266 265 .br
267 266 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-related
268 267 modules.
269 268 .br
270 269 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
271 270 plotting modules.
272 271 .br
273 272 .sp 1
274 273 Since it is possible to create an endless loop by having circular file
275 274 inclusions, IPython will stop if it reaches 15 recursive inclusions.
276 275 .TP
277 276 .B \-prompt_in1|pi1 <string>
278 277 Specify the string used for input prompts. Note that if you are using
279 278 numbered prompts, the number is represented with a '\\#' in the
280 279 string. Don't forget to quote strings with spaces embedded in
281 280 them. Default: 'In [\\#]:'.
282 281 .br
283 282 .sp 1
284 283 Most bash-like escapes can be used to customize IPython's prompts, as well as
285 284 a few additional ones which are IPython-specific. All valid prompt escapes
286 285 are described in detail in the Customization section of the IPython HTML/PDF
287 286 manual.
288 287 .TP
289 288 .B \-prompt_in2|pi2 <string>
290 289 Similar to the previous option, but used for the continuation prompts. The
291 290 special sequence '\\D' is similar to '\\#', but with all digits replaced dots
292 291 (so you can have your continuation prompt aligned with your input
293 292 prompt). Default: ' .\\D.:' (note three spaces at the start for alignment
294 293 with 'In [\\#]').
295 294 .TP
296 295 .B \-prompt_out|po <string>
297 296 String used for output prompts, also uses numbers like prompt_in1.
298 297 Default: 'Out[\\#]:'.
299 298 .TP
300 299 .B \-quick
301 300 Start in bare bones mode (no config file loaded).
302 301 .TP
303 302 .B \-rcfile <name>
304 303 Name of your IPython resource configuration file. normally IPython
305 304 loads ipythonrc (from current directory) or IPYTHONDIR/ipythonrc. If
306 305 the loading of your config file fails, IPython starts with a bare
307 306 bones configuration (no modules loaded at all).
308 307 .TP
309 308 .B \-[no]readline
310 309 Use the readline library, which is needed to support name completion
311 310 and command history, among other things. It is enabled by default, but
312 311 may cause problems for users of X/Emacs in Python comint or shell
313 312 buffers.
314 313 .br
315 314 .sp 1
316 315 Note that emacs 'eterm' buffers (opened with M-x term) support
317 316 IPython's readline and syntax coloring fine, only 'emacs' (M-x shell
318 317 and C-c !) buffers do not.
319 318 .TP
320 319 .B \-screen_length|sl <n>
321 320 Number of lines of your screen. This is used to control printing of
322 321 very long strings. Strings longer than this number of lines will be
323 322 sent through a pager instead of directly printed.
324 323 .br
325 324 .sp 1
326 325 The default value for this is 0, which means IPython will auto-detect
327 326 your screen size every time it needs to print certain potentially long
328 327 strings (this doesn't change the behavior of the 'print' keyword, it's
329 328 only triggered internally). If for some reason this isn't working well
330 329 (it needs curses support), specify it yourself. Otherwise don't change
331 330 the default.
332 331 .TP
333 332 .B \-separate_in|si <string>
334 333 Separator before input prompts. Default '\n'.
335 334 .TP
336 335 .B \-separate_out|so <string>
337 336 Separator before output prompts. Default: 0 (nothing).
338 337 .TP
339 338 .B \-separate_out2|so2 <string>
340 339 Separator after output prompts. Default: 0 (nothing).
341 340 .TP
342 341 .B \-nosep
343 342 Shorthand for '\-separate_in 0 \-separate_out 0 \-separate_out2 0'.
344 343 Simply removes all input/output separators.
345 344 .TP
346 345 .B \-upgrade
347 346 Allows you to upgrade your IPYTHONDIR configuration when you install a
348 347 new version of IPython. Since new versions may include new command
349 348 lines options or example files, this copies updated ipythonrc-type
350 349 files. However, it backs up (with a .old extension) all files which
351 350 it overwrites so that you can merge back any custimizations you might
352 351 have in your personal files.
353 352 .TP
354 353 .B \-Version
355 354 Print version information and exit.
356 355 .TP
357 356 .B \-xmode <modename>
358 357 Mode for exception reporting. The valid modes are Plain, Context, and
359 358 Verbose.
360 359 .br
361 360 .sp 1
362 361 \- Plain: similar to python's normal traceback printing.
363 362 .br
364 363 .sp 1
365 364 \- Context: prints 5 lines of context source code around each line in the
366 365 traceback.
367 366 .br
368 367 .sp 1
369 368 \- Verbose: similar to Context, but additionally prints the variables
370 369 currently visible where the exception happened (shortening their strings if
371 370 too long). This can potentially be very slow, if you happen to have a huge
372 371 data structure whose string representation is complex to compute. Your
373 372 computer may appear to freeze for a while with cpu usage at 100%. If this
374 373 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than
375 374 once).
376 375 .
377 376 .SH EMBEDDING
378 377 It is possible to start an IPython instance inside your own Python
379 378 programs. In the documentation example files there are some
380 379 illustrations on how to do this.
381 380 .br
382 381 .sp 1
383 382 This feature allows you to evalutate dynamically the state of your
384 383 code, operate with your variables, analyze them, etc. Note however
385 384 that any changes you make to values while in the shell do NOT
386 385 propagate back to the running code, so it is safe to modify your
387 386 values because you won't break your code in bizarre ways by doing so.
388 387 .SH AUTHOR
389 388 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
390 389 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
391 390 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
392 391 <jack@xiph.org>, for the Debian project (but may be used by others).
@@ -1,9124 +1,9168 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 While you can use IPython under Windows with only a stock Python installation,
939 939 there is one extension,
940 940 \family typewriter
941 941 readline
942 942 \family default
943 943 , which will make the whole experience a lot more pleasant.
944 944 It is almost a requirement, since IPython will complain in its absence
945 945 (though it will function).
946 946
947 947 \layout Standard
948 948
949 949 The
950 950 \family typewriter
951 951 readline
952 952 \family default
953 953 extension needs two other libraries to work, so in all you need:
954 954 \layout Enumerate
955 955
956 956
957 957 \family typewriter
958 958 PyWin32
959 959 \family default
960 960 from
961 961 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
962 962
963 963 \end_inset
964 964
965 965 .
966 966 \layout Enumerate
967 967
968 968
969 969 \family typewriter
970 970 CTypes
971 971 \family default
972 972 from
973 973 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
974 974
975 975 \end_inset
976 976
977 977 (you
978 978 \emph on
979 979 must
980 980 \emph default
981 981 use version 0.9.1 or newer).
982 982 \layout Enumerate
983 983
984 984
985 985 \family typewriter
986 986 Readline
987 987 \family default
988 988 for Windows from
989 989 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
990 990
991 991 \end_inset
992 992
993 993 .
994 994 \layout Standard
995 995
996 996
997 997 \series bold
998 998 Warning about a broken readline-like library:
999 999 \series default
1000 1000 several users have reported problems stemming from using the pseudo-readline
1001 1001 library at
1002 1002 \begin_inset LatexCommand \htmlurl{http://newcenturycomputers.net/projects/readline.html}
1003 1003
1004 1004 \end_inset
1005 1005
1006 1006 .
1007 1007 This is a broken library which, while called readline, only implements
1008 1008 an incomplete subset of the readline API.
1009 1009 Since it is still called readline, it fools IPython's detection mechanisms
1010 1010 and causes unpredictable crashes later.
1011 1011 If you wish to use IPython under Windows, you must NOT use this library,
1012 1012 which for all purposes is (at least as of version 1.6) terminally broken.
1013 1013 \layout Subsubsection
1014 1014
1015 1015 Gary Bishop's readline and color support for Windows
1016 1016 \layout Standard
1017 1017
1018 1018 Some of IPython's very useful features are:
1019 1019 \layout Itemize
1020 1020
1021 1021 Integrated readline support (Tab-based file, object and attribute completion,
1022 1022 input history across sessions, editable command line, etc.)
1023 1023 \layout Itemize
1024 1024
1025 1025 Coloring of prompts, code and tracebacks.
1026 1026 \layout Standard
1027 1027
1028 1028 These, by default, are only available under Unix-like operating systems.
1029 1029 However, thanks to Gary Bishop's work, Windows XP/2k users can also benefit
1030 1030 from them.
1031 1031 His readline library implements both GNU readline functionality and color
1032 1032 support, so that IPython under Windows XP/2k can be as friendly and powerful
1033 1033 as under Unix-like environments.
1034 1034 \layout Standard
1035 1035
1036 1036 You can find Gary's tools at
1037 1037 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
1038 1038
1039 1039 \end_inset
1040 1040
1041 1041 ; Gary's
1042 1042 \family typewriter
1043 1043 readline
1044 1044 \family default
1045 1045 requires in turn the
1046 1046 \family typewriter
1047 1047 ctypes
1048 1048 \family default
1049 1049 library by Thomas Heller, available at
1050 1050 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
1051 1051
1052 1052 \end_inset
1053 1053
1054 1054 , and Mark Hammond's
1055 1055 \family typewriter
1056 1056 PyWin32
1057 1057 \family default
1058 1058 from
1059 1059 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
1060 1060
1061 1061 \end_inset
1062 1062
1063 1063 (
1064 1064 \family typewriter
1065 1065 PyWin32
1066 1066 \family default
1067 1067 is great for anything Windows-related anyway, so you might as well get
1068 1068 it).
1069 1069 \layout Standard
1070 1070
1071 1071 Under MS\SpecialChar ~
1072 1072 Windows, IPython will complain if it can not find this
1073 1073 \family typewriter
1074 1074 readline
1075 1075 \family default
1076 1076 library at startup and any time the
1077 1077 \family typewriter
1078 1078 %colors
1079 1079 \family default
1080 1080 command is issued, so you can consider it to be a quasi-requirement.
1081 1081 \layout Subsubsection
1082 1082
1083 1083 Installation procedure
1084 1084 \layout Standard
1085 1085
1086 1086 Once you have the above installed, from the IPython download directory grab
1087 1087 the
1088 1088 \family typewriter
1089 1089 ipython-XXX.win32.exe
1090 1090 \family default
1091 1091 file, where
1092 1092 \family typewriter
1093 1093 XXX
1094 1094 \family default
1095 1095 represents the version number.
1096 1096 This is a regular windows executable installer, which you can simply double-cli
1097 1097 ck to install.
1098 1098 It will add an entry for IPython to your Start Menu, as well as registering
1099 1099 IPython in the Windows list of applications, so you can later uninstall
1100 1100 it from the Control Panel.
1101 1101
1102 1102 \layout Standard
1103 1103
1104 1104 IPython tries to install the configuration information in a directory named
1105 1105
1106 1106 \family typewriter
1107 1107 .ipython
1108 1108 \family default
1109 1109 (
1110 1110 \family typewriter
1111 1111 _ipython
1112 1112 \family default
1113 1113 under Windows) located in your `home' directory.
1114 1114 IPython sets this directory by looking for a
1115 1115 \family typewriter
1116 1116 HOME
1117 1117 \family default
1118 1118 environment variable; if such a variable does not exist, it uses
1119 1119 \family typewriter
1120 1120 HOMEDRIVE
1121 1121 \backslash
1122 1122 HOMEPATH
1123 1123 \family default
1124 1124 (these are always defined by Windows).
1125 1125 This typically gives something like
1126 1126 \family typewriter
1127 1127 C:
1128 1128 \backslash
1129 1129 Documents and Settings
1130 1130 \backslash
1131 1131 YourUserName
1132 1132 \family default
1133 1133 , but your local details may vary.
1134 1134 In this directory you will find all the files that configure IPython's
1135 1135 defaults, and you can put there your profiles and extensions.
1136 1136 This directory is automatically added by IPython to
1137 1137 \family typewriter
1138 1138 sys.path
1139 1139 \family default
1140 1140 , so anything you place there can be found by
1141 1141 \family typewriter
1142 1142 import
1143 1143 \family default
1144 1144 statements.
1145 1145 \layout Paragraph
1146 1146
1147 1147 Upgrading
1148 1148 \layout Standard
1149 1149
1150 1150 For an IPython upgrade, you should first uninstall the previous version.
1151 1151 This will ensure that all files and directories (such as the documentation)
1152 1152 which carry embedded version strings in their names are properly removed.
1153 1153 \layout Paragraph
1154 1154
1155 1155 Manual installation under Win32
1156 1156 \layout Standard
1157 1157
1158 1158 In case the automatic installer does not work for some reason, you can download
1159 1159 the
1160 1160 \family typewriter
1161 1161 ipython-XXX.tar.gz
1162 1162 \family default
1163 1163 file, which contains the full IPython source distribution (the popular
1164 1164 WinZip can read
1165 1165 \family typewriter
1166 1166 .tar.gz
1167 1167 \family default
1168 1168 files).
1169 1169 After uncompressing the archive, you can install it at a command terminal
1170 1170 just like any other Python module, by using
1171 1171 \family typewriter
1172 1172 `python setup.py install'
1173 1173 \family default
1174 1174 .
1175 1175
1176 1176 \layout Standard
1177 1177
1178 1178 After the installation, run the supplied
1179 1179 \family typewriter
1180 1180 win32_manual_post_install.py
1181 1181 \family default
1182 1182 script, which creates the necessary Start Menu shortcuts for you.
1183 1183 \layout Subsection
1184 1184
1185 1185
1186 1186 \begin_inset LatexCommand \label{sec:upgrade}
1187 1187
1188 1188 \end_inset
1189 1189
1190 1190 Upgrading from a previous version
1191 1191 \layout Standard
1192 1192
1193 1193 If you are upgrading from a previous version of IPython, after doing the
1194 1194 routine installation described above, you should call IPython with the
1195 1195
1196 1196 \family typewriter
1197 1197 -upgrade
1198 1198 \family default
1199 1199 option the first time you run your new copy.
1200 1200 This will automatically update your configuration directory while preserving
1201 1201 copies of your old files.
1202 1202 You can then later merge back any personal customizations you may have
1203 1203 made into the new files.
1204 1204 It is a good idea to do this as there may be new options available in the
1205 1205 new configuration files which you will not have.
1206 1206 \layout Standard
1207 1207
1208 1208 Under Windows, if you don't know how to call python scripts with arguments
1209 1209 from a command line, simply delete the old config directory and IPython
1210 1210 will make a new one.
1211 1211 Win2k and WinXP users will find it in
1212 1212 \family typewriter
1213 1213 C:
1214 1214 \backslash
1215 1215 Documents and Settings
1216 1216 \backslash
1217 1217 YourUserName
1218 1218 \backslash
1219 1219 _ipython
1220 1220 \family default
1221 1221 , and Win 9x users under
1222 1222 \family typewriter
1223 1223 C:
1224 1224 \backslash
1225 1225 Program Files
1226 1226 \backslash
1227 1227 IPython
1228 1228 \backslash
1229 1229 _ipython.
1230 1230 \layout Section
1231 1231
1232 1232
1233 1233 \begin_inset LatexCommand \label{sec:good_config}
1234 1234
1235 1235 \end_inset
1236 1236
1237 1237
1238 1238 \begin_inset OptArg
1239 1239 collapsed true
1240 1240
1241 1241 \layout Standard
1242 1242
1243 1243 Initial configuration
1244 1244 \begin_inset ERT
1245 1245 status Collapsed
1246 1246
1247 1247 \layout Standard
1248 1248
1249 1249 \backslash
1250 1250 ldots
1251 1251 \end_inset
1252 1252
1253 1253
1254 1254 \end_inset
1255 1255
1256 1256 Initial configuration of your environment
1257 1257 \layout Standard
1258 1258
1259 1259 This section will help you set various things in your environment for your
1260 1260 IPython sessions to be as efficient as possible.
1261 1261 All of IPython's configuration information, along with several example
1262 1262 files, is stored in a directory named by default
1263 1263 \family typewriter
1264 1264 $HOME/.ipython
1265 1265 \family default
1266 1266 .
1267 1267 You can change this by defining the environment variable
1268 1268 \family typewriter
1269 1269 IPYTHONDIR
1270 1270 \family default
1271 1271 , or at runtime with the command line option
1272 1272 \family typewriter
1273 1273 -ipythondir
1274 1274 \family default
1275 1275 .
1276 1276 \layout Standard
1277 1277
1278 1278 If all goes well, the first time you run IPython it should automatically
1279 1279 create a user copy of the config directory for you, based on its builtin
1280 1280 defaults.
1281 1281 You can look at the files it creates to learn more about configuring the
1282 1282 system.
1283 1283 The main file you will modify to configure IPython's behavior is called
1284 1284
1285 1285 \family typewriter
1286 1286 ipythonrc
1287 1287 \family default
1288 1288 (with a
1289 1289 \family typewriter
1290 1290 .ini
1291 1291 \family default
1292 1292 extension under Windows), included for reference in Sec.
1293 1293
1294 1294 \begin_inset LatexCommand \ref{sec:ipytonrc-sample}
1295 1295
1296 1296 \end_inset
1297 1297
1298 1298 .
1299 1299 This file is very commented and has many variables you can change to suit
1300 1300 your taste, you can find more details in Sec.
1301 1301
1302 1302 \begin_inset LatexCommand \ref{sec:customization}
1303 1303
1304 1304 \end_inset
1305 1305
1306 1306 .
1307 1307 Here we discuss the basic things you will want to make sure things are
1308 1308 working properly from the beginning.
1309 1309 \layout Subsection
1310 1310
1311 1311
1312 1312 \begin_inset LatexCommand \label{sec:help-access}
1313 1313
1314 1314 \end_inset
1315 1315
1316 1316 Access to the Python help system
1317 1317 \layout Standard
1318 1318
1319 1319 This is true for Python in general (not just for IPython): you should have
1320 1320 an environment variable called
1321 1321 \family typewriter
1322 1322 PYTHONDOCS
1323 1323 \family default
1324 1324 pointing to the directory where your HTML Python documentation lives.
1325 1325 In my system it's
1326 1326 \family typewriter
1327 1327 /usr/share/doc/python-docs-2.3.4/html
1328 1328 \family default
1329 1329 , check your local details or ask your systems administrator.
1330 1330
1331 1331 \layout Standard
1332 1332
1333 1333 This is the directory which holds the HTML version of the Python manuals.
1334 1334 Unfortunately it seems that different Linux distributions package these
1335 1335 files differently, so you may have to look around a bit.
1336 1336 Below I show the contents of this directory on my system for reference:
1337 1337 \layout Standard
1338 1338
1339 1339
1340 1340 \family typewriter
1341 1341 [html]> ls
1342 1342 \newline
1343 1343 about.dat acks.html dist/ ext/ index.html lib/ modindex.html stdabout.dat tut/
1344 1344 about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
1345 1345 \layout Standard
1346 1346
1347 1347 You should really make sure this variable is correctly set so that Python's
1348 1348 pydoc-based help system works.
1349 1349 It is a powerful and convenient system with full access to the Python manuals
1350 1350 and all modules accessible to you.
1351 1351 \layout Standard
1352 1352
1353 1353 Under Windows it seems that pydoc finds the documentation automatically,
1354 1354 so no extra setup appears necessary.
1355 1355 \layout Subsection
1356 1356
1357 1357 Editor
1358 1358 \layout Standard
1359 1359
1360 1360 The
1361 1361 \family typewriter
1362 1362 %edit
1363 1363 \family default
1364 1364 command (and its alias
1365 1365 \family typewriter
1366 1366 %ed
1367 1367 \family default
1368 1368 ) will invoke the editor set in your environment as
1369 1369 \family typewriter
1370 1370 EDITOR
1371 1371 \family default
1372 1372 .
1373 1373 If this variable is not set, it will default to
1374 1374 \family typewriter
1375 1375 vi
1376 1376 \family default
1377 1377 under Linux/Unix and to
1378 1378 \family typewriter
1379 1379 notepad
1380 1380 \family default
1381 1381 under Windows.
1382 1382 You may want to set this variable properly and to a lightweight editor
1383 1383 which doesn't take too long to start (that is, something other than a new
1384 1384 instance of
1385 1385 \family typewriter
1386 1386 Emacs
1387 1387 \family default
1388 1388 ).
1389 1389 This way you can edit multi-line code quickly and with the power of a real
1390 1390 editor right inside IPython.
1391 1391
1392 1392 \layout Standard
1393 1393
1394 1394 If you are a dedicated
1395 1395 \family typewriter
1396 1396 Emacs
1397 1397 \family default
1398 1398 user, you should set up the
1399 1399 \family typewriter
1400 1400 Emacs
1401 1401 \family default
1402 1402 server so that new requests are handled by the original process.
1403 1403 This means that almost no time is spent in handling the request (assuming
1404 1404 an
1405 1405 \family typewriter
1406 1406 Emacs
1407 1407 \family default
1408 1408 process is already running).
1409 1409 For this to work, you need to set your
1410 1410 \family typewriter
1411 1411 EDITOR
1412 1412 \family default
1413 1413 environment variable to
1414 1414 \family typewriter
1415 1415 'emacsclient'
1416 1416 \family default
1417 1417 .
1418 1418
1419 1419 \family typewriter
1420 1420
1421 1421 \family default
1422 1422 The code below, supplied by Francois Pinard, can then be used in your
1423 1423 \family typewriter
1424 1424 .emacs
1425 1425 \family default
1426 1426 file to enable the server:
1427 1427 \layout Standard
1428 1428
1429 1429
1430 1430 \family typewriter
1431 1431 (defvar server-buffer-clients)
1432 1432 \newline
1433 1433 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
1434 1434 \newline
1435 1435
1436 1436 \begin_inset ERT
1437 1437 status Collapsed
1438 1438
1439 1439 \layout Standard
1440 1440
1441 1441 \backslash
1442 1442 hspace*{0mm}
1443 1443 \end_inset
1444 1444
1445 1445 \SpecialChar ~
1446 1446 \SpecialChar ~
1447 1447 (server-start)
1448 1448 \newline
1449 1449
1450 1450 \begin_inset ERT
1451 1451 status Collapsed
1452 1452
1453 1453 \layout Standard
1454 1454
1455 1455 \backslash
1456 1456 hspace*{0mm}
1457 1457 \end_inset
1458 1458
1459 1459 \SpecialChar ~
1460 1460 \SpecialChar ~
1461 1461 (defun fp-kill-server-with-buffer-routine ()
1462 1462 \newline
1463 1463
1464 1464 \begin_inset ERT
1465 1465 status Collapsed
1466 1466
1467 1467 \layout Standard
1468 1468
1469 1469 \backslash
1470 1470 hspace*{0mm}
1471 1471 \end_inset
1472 1472
1473 1473 \SpecialChar ~
1474 1474 \SpecialChar ~
1475 1475 \SpecialChar ~
1476 1476 \SpecialChar ~
1477 1477 (and server-buffer-clients (server-done)))
1478 1478 \newline
1479 1479
1480 1480 \begin_inset ERT
1481 1481 status Collapsed
1482 1482
1483 1483 \layout Standard
1484 1484
1485 1485 \backslash
1486 1486 hspace*{0mm}
1487 1487 \end_inset
1488 1488
1489 1489 \SpecialChar ~
1490 1490 \SpecialChar ~
1491 1491 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
1492 1492 \layout Standard
1493 1493
1494 1494 You can also set the value of this editor via the commmand-line option '-
1495 1495 \family typewriter
1496 1496 editor'
1497 1497 \family default
1498 1498 or in your
1499 1499 \family typewriter
1500 1500 ipythonrc
1501 1501 \family default
1502 1502 file.
1503 1503 This is useful if you wish to use specifically for IPython an editor different
1504 1504 from your typical default (and for Windows users who tend to use fewer
1505 1505 environment variables).
1506 1506 \layout Subsection
1507 1507
1508 1508 Color
1509 1509 \layout Standard
1510 1510
1511 1511 The default IPython configuration has most bells and whistles turned on
1512 1512 (they're pretty safe).
1513 1513 But there's one that
1514 1514 \emph on
1515 1515 may
1516 1516 \emph default
1517 1517 cause problems on some systems: the use of color on screen for displaying
1518 1518 information.
1519 1519 This is very useful, since IPython can show prompts and exception tracebacks
1520 1520 with various colors, display syntax-highlighted source code, and in general
1521 1521 make it easier to visually parse information.
1522 1522 \layout Standard
1523 1523
1524 1524 The following terminals seem to handle the color sequences fine:
1525 1525 \layout Itemize
1526 1526
1527 1527 Linux main text console, KDE Konsole, Gnome Terminal, E-term, rxvt, xterm.
1528 1528 \layout Itemize
1529 1529
1530 1530 CDE terminal (tested under Solaris).
1531 1531 This one boldfaces light colors.
1532 1532 \layout Itemize
1533 1533
1534 1534 (X)Emacs buffers.
1535 1535 See sec.
1536 1536 \begin_inset LatexCommand \ref{sec:emacs}
1537 1537
1538 1538 \end_inset
1539 1539
1540 1540 for more details on using IPython with (X)Emacs.
1541 1541 \layout Itemize
1542 1542
1543 1543 A Windows (XP/2k) command prompt
1544 1544 \emph on
1545 1545 with Gary Bishop's support extensions
1546 1546 \emph default
1547 1547 .
1548 1548 Gary's extensions are discussed in Sec.\SpecialChar ~
1549 1549
1550 1550 \begin_inset LatexCommand \ref{sub:Under-Windows}
1551 1551
1552 1552 \end_inset
1553 1553
1554 1554 .
1555 1555 \layout Itemize
1556 1556
1557 1557 A Windows (XP/2k) CygWin shell.
1558 1558 Although some users have reported problems; it is not clear whether there
1559 1559 is an issue for everyone or only under specific configurations.
1560 1560 If you have full color support under cygwin, please post to the IPython
1561 1561 mailing list so this issue can be resolved for all users.
1562 1562 \layout Standard
1563 1563
1564 1564 These have shown problems:
1565 1565 \layout Itemize
1566 1566
1567 1567 Windows command prompt in WinXP/2k logged into a Linux machine via telnet
1568 1568 or ssh.
1569 1569 \layout Itemize
1570 1570
1571 1571 Windows native command prompt in WinXP/2k,
1572 1572 \emph on
1573 1573 without
1574 1574 \emph default
1575 1575 Gary Bishop's extensions.
1576 1576 Once Gary's readline library is installed, the normal WinXP/2k command
1577 1577 prompt works perfectly.
1578 1578 \layout Standard
1579 1579
1580 1580 Currently the following color schemes are available:
1581 1581 \layout Itemize
1582 1582
1583 1583
1584 1584 \family typewriter
1585 1585 NoColor
1586 1586 \family default
1587 1587 : uses no color escapes at all (all escapes are empty
1588 1588 \begin_inset Quotes eld
1589 1589 \end_inset
1590 1590
1591 1591
1592 1592 \begin_inset Quotes eld
1593 1593 \end_inset
1594 1594
1595 1595 strings).
1596 1596 This 'scheme' is thus fully safe to use in any terminal.
1597 1597 \layout Itemize
1598 1598
1599 1599
1600 1600 \family typewriter
1601 1601 Linux
1602 1602 \family default
1603 1603 : works well in Linux console type environments: dark background with light
1604 1604 fonts.
1605 1605 It uses bright colors for information, so it is difficult to read if you
1606 1606 have a light colored background.
1607 1607 \layout Itemize
1608 1608
1609 1609
1610 1610 \family typewriter
1611 1611 LightBG
1612 1612 \family default
1613 1613 : the basic colors are similar to those in the
1614 1614 \family typewriter
1615 1615 Linux
1616 1616 \family default
1617 1617 scheme but darker.
1618 1618 It is easy to read in terminals with light backgrounds.
1619 1619 \layout Standard
1620 1620
1621 1621 IPython uses colors for two main groups of things: prompts and tracebacks
1622 1622 which are directly printed to the terminal, and the object introspection
1623 1623 system which passes large sets of data through a pager.
1624 1624 \layout Subsubsection
1625 1625
1626 1626 Input/Output prompts and exception tracebacks
1627 1627 \layout Standard
1628 1628
1629 1629 You can test whether the colored prompts and tracebacks work on your system
1630 1630 interactively by typing
1631 1631 \family typewriter
1632 1632 '%colors Linux'
1633 1633 \family default
1634 1634 at the prompt (use '
1635 1635 \family typewriter
1636 1636 %colors LightBG'
1637 1637 \family default
1638 1638 if your terminal has a light background).
1639 1639 If the input prompt shows garbage like:
1640 1640 \newline
1641 1641
1642 1642 \family typewriter
1643 1643 [0;32mIn [[1;32m1[0;32m]: [0;00m
1644 1644 \family default
1645 1645
1646 1646 \newline
1647 1647 instead of (in color) something like:
1648 1648 \newline
1649 1649
1650 1650 \family typewriter
1651 1651 In [1]:
1652 1652 \family default
1653 1653
1654 1654 \newline
1655 1655 this means that your terminal doesn't properly handle color escape sequences.
1656 1656 You can go to a 'no color' mode by typing '
1657 1657 \family typewriter
1658 1658 %colors NoColor
1659 1659 \family default
1660 1660 '.
1661 1661
1662 1662 \layout Standard
1663 1663
1664 1664 You can try using a different terminal emulator program.
1665 1665 To permanently set your color preferences, edit the file
1666 1666 \family typewriter
1667 1667 $HOME/.ipython/ipythonrc
1668 1668 \family default
1669 1669 and set the
1670 1670 \family typewriter
1671 1671 colors
1672 1672 \family default
1673 1673 option to the desired value.
1674 1674 \layout Subsubsection
1675 1675
1676 1676 Object details (types, docstrings, source code, etc.)
1677 1677 \layout Standard
1678 1678
1679 1679 IPython has a set of special functions for studying the objects you are
1680 1680 working with, discussed in detail in Sec.
1681 1681
1682 1682 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1683 1683
1684 1684 \end_inset
1685 1685
1686 1686 .
1687 1687 But this system relies on passing information which is longer than your
1688 1688 screen through a data pager, such as the common Unix
1689 1689 \family typewriter
1690 1690 less
1691 1691 \family default
1692 1692 and
1693 1693 \family typewriter
1694 1694 more
1695 1695 \family default
1696 1696 programs.
1697 1697 In order to be able to see this information in color, your pager needs
1698 1698 to be properly configured.
1699 1699 I strongly recommend using
1700 1700 \family typewriter
1701 1701 less
1702 1702 \family default
1703 1703 instead of
1704 1704 \family typewriter
1705 1705 more
1706 1706 \family default
1707 1707 , as it seems that
1708 1708 \family typewriter
1709 1709 more
1710 1710 \family default
1711 1711 simply can not understand colored text correctly.
1712 1712 \layout Standard
1713 1713
1714 1714 In order to configure
1715 1715 \family typewriter
1716 1716 less
1717 1717 \family default
1718 1718 as your default pager, do the following:
1719 1719 \layout Enumerate
1720 1720
1721 1721 Set the environment
1722 1722 \family typewriter
1723 1723 PAGER
1724 1724 \family default
1725 1725 variable to
1726 1726 \family typewriter
1727 1727 less
1728 1728 \family default
1729 1729 .
1730 1730 \layout Enumerate
1731 1731
1732 1732 Set the environment
1733 1733 \family typewriter
1734 1734 LESS
1735 1735 \family default
1736 1736 variable to
1737 1737 \family typewriter
1738 1738 -r
1739 1739 \family default
1740 1740 (plus any other options you always want to pass to
1741 1741 \family typewriter
1742 1742 less
1743 1743 \family default
1744 1744 by default).
1745 1745 This tells
1746 1746 \family typewriter
1747 1747 less
1748 1748 \family default
1749 1749 to properly interpret control sequences, which is how color information
1750 1750 is given to your terminal.
1751 1751 \layout Standard
1752 1752
1753 1753 For the
1754 1754 \family typewriter
1755 1755 csh
1756 1756 \family default
1757 1757 or
1758 1758 \family typewriter
1759 1759 tcsh
1760 1760 \family default
1761 1761 shells, add to your
1762 1762 \family typewriter
1763 1763 ~/.cshrc
1764 1764 \family default
1765 1765 file the lines:
1766 1766 \layout Standard
1767 1767
1768 1768
1769 1769 \family typewriter
1770 1770 setenv PAGER less
1771 1771 \newline
1772 1772 setenv LESS -r
1773 1773 \layout Standard
1774 1774
1775 1775 There is similar syntax for other Unix shells, look at your system documentation
1776 1776 for details.
1777 1777 \layout Standard
1778 1778
1779 1779 If you are on a system which lacks proper data pagers (such as Windows),
1780 1780 IPython will use a very limited builtin pager.
1781 1781 \layout Subsection
1782 1782
1783 1783
1784 1784 \begin_inset LatexCommand \label{sec:emacs}
1785 1785
1786 1786 \end_inset
1787 1787
1788 1788 (X)Emacs configuration
1789 1789 \layout Standard
1790 1790
1791 1791 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, currently
1792 1792 (X)Emacs and IPython get along very well.
1793 1793
1794 1794 \layout Standard
1795 1795
1796 1796
1797 1797 \series bold
1798 1798 Important note:
1799 1799 \series default
1800 1800 You will need to use a recent enough version of
1801 1801 \family typewriter
1802 1802 python-mode.el
1803 1803 \family default
1804 1804 , along with the file
1805 1805 \family typewriter
1806 1806 ipython.el
1807 1807 \family default
1808 1808 .
1809 1809 You can check that the version you have of
1810 1810 \family typewriter
1811 1811 python-mode.el
1812 1812 \family default
1813 1813 is new enough by either looking at the revision number in the file itself,
1814 1814 or asking for it in (X)Emacs via
1815 1815 \family typewriter
1816 1816 M-x py-version
1817 1817 \family default
1818 1818 .
1819 1819 Versions 4.68 and newer contain the necessary fixes for proper IPython support.
1820 1820 \layout Standard
1821 1821
1822 1822 The file
1823 1823 \family typewriter
1824 1824 ipython.el
1825 1825 \family default
1826 1826 is included with the IPython distribution, in the documentation directory
1827 1827 (where this manual resides in PDF and HTML formats).
1828 1828 \layout Standard
1829 1829
1830 1830 Once you put these files in your Emacs path, all you need in your
1831 1831 \family typewriter
1832 1832 .emacs
1833 1833 \family default
1834 1834 file is:
1835 1835 \layout Standard
1836 1836
1837 1837
1838 1838 \family typewriter
1839 1839 (require 'ipython)
1840 1840 \layout Standard
1841 1841
1842 1842 This should give you full support for executing code snippets via IPython,
1843 1843 opening IPython as your Python shell via
1844 1844 \family typewriter
1845 1845 C-c\SpecialChar ~
1846 1846 !
1847 1847 \family default
1848 1848 , etc.
1849 1849
1850 1850 \layout Subsubsection*
1851 1851
1852 1852 Notes
1853 1853 \layout Itemize
1854 1854
1855 1855 There is one caveat you should be aware of: you must start the IPython shell
1856 1856
1857 1857 \emph on
1858 1858 before
1859 1859 \emph default
1860 1860 attempting to execute any code regions via
1861 1861 \family typewriter
1862 1862 C-c\SpecialChar ~
1863 1863 |
1864 1864 \family default
1865 1865 .
1866 1866 Simply type
1867 1867 \family typewriter
1868 1868 C-c\SpecialChar ~
1869 1869 !
1870 1870 \family default
1871 1871 to start IPython before passing any code regions to the interpreter, and
1872 1872 you shouldn't experience any problems.
1873 1873 \newline
1874 1874 This is due to a bug in Python itself, which has been fixed for Python 2.3,
1875 1875 but exists as of Python 2.2.2 (reported as SF bug [ 737947 ]).
1876 1876 \layout Itemize
1877 1877
1878 1878 The (X)Emacs support is maintained by Alexander Schmolck, so all comments/reques
1879 1879 ts should be directed to him through the IPython mailing lists.
1880 1880
1881 1881 \layout Itemize
1882 1882
1883 1883 This code is still somewhat experimental so it's a bit rough around the
1884 1884 edges (although in practice, it works quite well).
1885 1885 \layout Itemize
1886 1886
1887 1887 Be aware that if you customize
1888 1888 \family typewriter
1889 1889 py-python-command
1890 1890 \family default
1891 1891 previously, this value will override what
1892 1892 \family typewriter
1893 1893 ipython.el
1894 1894 \family default
1895 1895 does (because loading the customization variables comes later).
1896 1896 \layout Section
1897 1897
1898 1898
1899 1899 \begin_inset LatexCommand \label{sec:quick_tips}
1900 1900
1901 1901 \end_inset
1902 1902
1903 1903 Quick tips
1904 1904 \layout Standard
1905 1905
1906 1906 IPython can be used as an improved replacement for the Python prompt, and
1907 1907 for that you don't really need to read any more of this manual.
1908 1908 But in this section we'll try to summarize a few tips on how to make the
1909 1909 most effective use of it for everyday Python development, highlighting
1910 1910 things you might miss in the rest of the manual (which is getting long).
1911 1911 We'll give references to parts in the manual which provide more detail
1912 1912 when appropriate.
1913 1913 \layout Standard
1914 1914
1915 1915 The following article by Jeremy Jones provides an introductory tutorial
1916 1916 about IPython:
1917 1917 \newline
1918 1918
1919 1919 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html}
1920 1920
1921 1921 \end_inset
1922 1922
1923 1923
1924 1924 \layout Itemize
1925 1925
1926 1926 The TAB key.
1927 1927 TAB-completion, especially for attributes, is a convenient way to explore
1928 1928 the structure of any object you're dealing with.
1929 1929 Simply type
1930 1930 \family typewriter
1931 1931 object_name.<TAB>
1932 1932 \family default
1933 1933 and a list of the object's attributes will be printed (see sec.
1934 1934
1935 1935 \begin_inset LatexCommand \ref{sec:readline}
1936 1936
1937 1937 \end_inset
1938 1938
1939 1939 for more).
1940 1940 Tab completion also works on file and directory names, which combined with
1941 1941 IPython's alias system allows you to do from within IPython many of the
1942 1942 things you normally would need the system shell for.
1943 1943
1944 1944 \layout Itemize
1945 1945
1946 1946 Explore your objects.
1947 1947 Typing
1948 1948 \family typewriter
1949 1949 object_name?
1950 1950 \family default
1951 1951 will print all sorts of details about any object, including docstrings,
1952 1952 function definition lines (for call arguments) and constructor details
1953 1953 for classes.
1954 1954 The magic commands
1955 1955 \family typewriter
1956 1956 %pdoc
1957 1957 \family default
1958 1958 ,
1959 1959 \family typewriter
1960 1960 %pdef
1961 1961 \family default
1962 1962 ,
1963 1963 \family typewriter
1964 1964 %psource
1965 1965 \family default
1966 1966 and
1967 1967 \family typewriter
1968 1968 %pfile
1969 1969 \family default
1970 1970 will respectively print the docstring, function definition line, full source
1971 1971 code and the complete file for any object (when they can be found).
1972 1972 If automagic is on (it is by default), you don't need to type the '
1973 1973 \family typewriter
1974 1974 %
1975 1975 \family default
1976 1976 ' explicitly.
1977 1977 See sec.
1978 1978
1979 1979 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1980 1980
1981 1981 \end_inset
1982 1982
1983 1983 for more.
1984 1984 \layout Itemize
1985 1985
1986 1986 The
1987 1987 \family typewriter
1988 1988 %run
1989 1989 \family default
1990 1990 magic command allows you to run any python script and load all of its data
1991 1991 directly into the interactive namespace.
1992 1992 Since the file is re-read from disk each time, changes you make to it are
1993 1993 reflected immediately (in contrast to the behavior of
1994 1994 \family typewriter
1995 1995 import
1996 1996 \family default
1997 1997 ).
1998 1998 I rarely use
1999 1999 \family typewriter
2000 2000 import
2001 2001 \family default
2002 2002 for code I am testing, relying on
2003 2003 \family typewriter
2004 2004 %run
2005 2005 \family default
2006 2006 instead.
2007 2007 See sec.
2008 2008
2009 2009 \begin_inset LatexCommand \ref{sec:magic}
2010 2010
2011 2011 \end_inset
2012 2012
2013 2013 for more on this and other magic commands, or type the name of any magic
2014 2014 command and ? to get details on it.
2015 2015 See also sec.
2016 2016
2017 2017 \begin_inset LatexCommand \ref{sec:dreload}
2018 2018
2019 2019 \end_inset
2020 2020
2021 2021 for a recursive reload command.
2022 2022 \newline
2023 2023
2024 2024 \family typewriter
2025 2025 %run
2026 2026 \family default
2027 2027 also has special flags for timing the execution of your scripts (
2028 2028 \family typewriter
2029 2029 -t
2030 2030 \family default
2031 2031 ) and for executing them under the control of either Python's
2032 2032 \family typewriter
2033 2033 pdb
2034 2034 \family default
2035 2035 debugger (
2036 2036 \family typewriter
2037 2037 -d
2038 2038 \family default
2039 2039 ) or profiler (
2040 2040 \family typewriter
2041 2041 -p
2042 2042 \family default
2043 2043 ).
2044 2044 With all of these,
2045 2045 \family typewriter
2046 2046 %run
2047 2047 \family default
2048 2048 can be used as the main tool for efficient interactive development of code
2049 2049 which you write in your editor of choice.
2050 2050 \layout Itemize
2051 2051
2052 2052 Use the Python debugger,
2053 2053 \family typewriter
2054 2054 pdb
2055 2055 \family default
2056 2056
2057 2057 \begin_inset Foot
2058 2058 collapsed true
2059 2059
2060 2060 \layout Standard
2061 2061
2062 2062 Thanks to Christian Hart and Matthew Arnison for the suggestions leading
2063 2063 to IPython's improved debugger and profiler support.
2064 2064 \end_inset
2065 2065
2066 2066 .
2067 2067 The
2068 2068 \family typewriter
2069 2069 %pdb
2070 2070 \family default
2071 2071 command allows you to toggle on and off the automatic invocation of an
2072 2072 IPython-enhanced
2073 2073 \family typewriter
2074 2074 pdb
2075 2075 \family default
2076 2076 debugger (with coloring, tab completion and more) at any uncaught exception.
2077 2077 The advantage of this is that
2078 2078 \family typewriter
2079 2079 pdb
2080 2080 \family default
2081 2081 starts
2082 2082 \emph on
2083 2083 inside
2084 2084 \emph default
2085 2085 the function where the exception occurred, with all data still available.
2086 2086 You can print variables, see code, execute statements and even walk up
2087 2087 and down the call stack to track down the true source of the problem (which
2088 2088 often is many layers in the stack above where the exception gets triggered).
2089 2089 \newline
2090 2090 Running programs with
2091 2091 \family typewriter
2092 2092 %run
2093 2093 \family default
2094 2094 and pdb active can be an efficient to develop and debug code, in many cases
2095 2095 eliminating the need for
2096 2096 \family typewriter
2097 2097 print
2098 2098 \family default
2099 2099 statements or external debugging tools.
2100 2100 I often simply put a
2101 2101 \family typewriter
2102 2102 1/0
2103 2103 \family default
2104 2104 in a place where I want to take a look so that pdb gets called, quickly
2105 2105 view whatever variables I need to or test various pieces of code and then
2106 2106 remove the
2107 2107 \family typewriter
2108 2108 1/0
2109 2109 \family default
2110 2110 .
2111 2111 \newline
2112 2112 Note also that `
2113 2113 \family typewriter
2114 2114 %run -d
2115 2115 \family default
2116 2116 ' activates
2117 2117 \family typewriter
2118 2118 pdb
2119 2119 \family default
2120 2120 and automatically sets initial breakpoints for you to step through your
2121 2121 code, watch variables, etc.
2122 2122 See Sec.\SpecialChar ~
2123 2123
2124 2124 \begin_inset LatexCommand \ref{sec:cache_output}
2125 2125
2126 2126 \end_inset
2127 2127
2128 2128 for details.
2129 2129 \layout Itemize
2130 2130
2131 2131 Use the output cache.
2132 2132 All output results are automatically stored in a global dictionary named
2133 2133
2134 2134 \family typewriter
2135 2135 Out
2136 2136 \family default
2137 2137 and variables named
2138 2138 \family typewriter
2139 2139 _1
2140 2140 \family default
2141 2141 ,
2142 2142 \family typewriter
2143 2143 _2
2144 2144 \family default
2145 2145 , etc.
2146 2146 alias them.
2147 2147 For example, the result of input line 4 is available either as
2148 2148 \family typewriter
2149 2149 Out[4]
2150 2150 \family default
2151 2151 or as
2152 2152 \family typewriter
2153 2153 _4
2154 2154 \family default
2155 2155 .
2156 2156 Additionally, three variables named
2157 2157 \family typewriter
2158 2158 _
2159 2159 \family default
2160 2160 ,
2161 2161 \family typewriter
2162 2162 __
2163 2163 \family default
2164 2164 and
2165 2165 \family typewriter
2166 2166 ___
2167 2167 \family default
2168 2168 are always kept updated with the for the last three results.
2169 2169 This allows you to recall any previous result and further use it for new
2170 2170 calculations.
2171 2171 See Sec.\SpecialChar ~
2172 2172
2173 2173 \begin_inset LatexCommand \ref{sec:cache_output}
2174 2174
2175 2175 \end_inset
2176 2176
2177 2177 for more.
2178 2178 \layout Itemize
2179 2179
2180 2180 Put a '
2181 2181 \family typewriter
2182 2182 ;
2183 2183 \family default
2184 2184 ' at the end of a line to supress the printing of output.
2185 2185 This is useful when doing calculations which generate long output you are
2186 2186 not interested in seeing.
2187 2187 The
2188 2188 \family typewriter
2189 2189 _*
2190 2190 \family default
2191 2191 variables and the
2192 2192 \family typewriter
2193 2193 Out[]
2194 2194 \family default
2195 2195 list do get updated with the contents of the output, even if it is not
2196 2196 printed.
2197 2197 You can thus still access the generated results this way for further processing.
2198 2198 \layout Itemize
2199 2199
2200 2200 A similar system exists for caching input.
2201 2201 All input is stored in a global list called
2202 2202 \family typewriter
2203 2203 In
2204 2204 \family default
2205 2205 , so you can re-execute lines 22 through 28 plus line 34 by typing
2206 2206 \family typewriter
2207 2207 'exec In[22:29]+In[34]'
2208 2208 \family default
2209 2209 (using Python slicing notation).
2210 2210 If you need to execute the same set of lines often, you can assign them
2211 2211 to a macro with the
2212 2212 \family typewriter
2213 2213 %macro
2214 2214 \family default
2215 2215
2216 2216 \family typewriter
2217 2217 function.
2218 2218
2219 2219 \family default
2220 2220 See sec.
2221 2221
2222 2222 \begin_inset LatexCommand \ref{sec:cache_input}
2223 2223
2224 2224 \end_inset
2225 2225
2226 2226 for more.
2227 2227 \layout Itemize
2228 2228
2229 2229 Use your input history.
2230 2230 The
2231 2231 \family typewriter
2232 2232 %hist
2233 2233 \family default
2234 2234 command can show you all previous input, without line numbers if desired
2235 2235 (option
2236 2236 \family typewriter
2237 2237 -n
2238 2238 \family default
2239 2239 ) so you can directly copy and paste code either back in IPython or in a
2240 2240 text editor.
2241 2241 You can also save all your history by turning on logging via
2242 2242 \family typewriter
2243 2243 %logstart
2244 2244 \family default
2245 2245 ; these logs can later be either reloaded as IPython sessions or used as
2246 2246 code for your programs.
2247 2247 \layout Itemize
2248 2248
2249 2249 Define your own macros with
2250 2250 \family typewriter
2251 2251 %macro
2252 2252 \family default
2253 2253 .
2254 2254 This can be useful for automating sequences of expressions when working
2255 2255 interactively.
2256 2256 \layout Itemize
2257 2257
2258 2258 Define your own system aliases.
2259 2259 Even though IPython gives you access to your system shell via the
2260 2260 \family typewriter
2261 2261 !
2262 2262 \family default
2263 2263 prefix, it is convenient to have aliases to the system commands you use
2264 2264 most often.
2265 2265 This allows you to work seamlessly from inside IPython with the same commands
2266 2266 you are used to in your system shell.
2267 2267 \newline
2268 2268 IPython comes with some pre-defined aliases and a complete system for changing
2269 2269 directories, both via a stack (see
2270 2270 \family typewriter
2271 2271 %pushd
2272 2272 \family default
2273 2273 ,
2274 2274 \family typewriter
2275 2275 %popd
2276 2276 \family default
2277 2277 and
2278 2278 \family typewriter
2279 2279 %ds
2280 2280 \family default
2281 2281 ) and via direct
2282 2282 \family typewriter
2283 2283 %cd
2284 2284 \family default
2285 2285 .
2286 2286 The latter keeps a history of visited directories and allows you to go
2287 2287 to any previously visited one.
2288 2288 \layout Itemize
2289 2289
2290 2290 Use Python to manipulate the results of system commands.
2291 2291 The `
2292 2292 \family typewriter
2293 2293 !!
2294 2294 \family default
2295 2295 ' special syntax, and the
2296 2296 \family typewriter
2297 2297 %sc
2298 2298 \family default
2299 2299 and
2300 2300 \family typewriter
2301 2301 %sx
2302 2302 \family default
2303 2303 magic commands allow you to capture system output into Python variables.
2304 2304 \layout Itemize
2305 2305
2306 2306 Expand python variables when calling the shell (either via
2307 2307 \family typewriter
2308 2308 `!'
2309 2309 \family default
2310 2310 and
2311 2311 \family typewriter
2312 2312 `!!'
2313 2313 \family default
2314 2314 or via aliases) by prepending a
2315 2315 \family typewriter
2316 2316 $
2317 2317 \family default
2318 2318 in front of them.
2319 2319 You can also expand complete python expressions.
2320 2320 See sec.\SpecialChar ~
2321 2321
2322 2322 \begin_inset LatexCommand \ref{sub:System-shell-access}
2323 2323
2324 2324 \end_inset
2325 2325
2326 2326 for more.
2327 2327 \layout Itemize
2328 2328
2329 2329 Use profiles to maintain different configurations (modules to load, function
2330 2330 definitions, option settings) for particular tasks.
2331 2331 You can then have customized versions of IPython for specific purposes.
2332 2332 See sec.\SpecialChar ~
2333 2333
2334 2334 \begin_inset LatexCommand \ref{sec:profiles}
2335 2335
2336 2336 \end_inset
2337 2337
2338 2338 for more.
2339 2339 \layout Itemize
2340 2340
2341 2341 Embed IPython in your programs.
2342 2342 A few lines of code are enough to load a complete IPython inside your own
2343 2343 programs, giving you the ability to work with your data interactively after
2344 2344 automatic processing has been completed.
2345 2345 See sec.\SpecialChar ~
2346 2346
2347 2347 \begin_inset LatexCommand \ref{sec:embed}
2348 2348
2349 2349 \end_inset
2350 2350
2351 2351 for more.
2352 2352 \layout Itemize
2353 2353
2354 2354 Use the Python profiler.
2355 2355 When dealing with performance issues, the
2356 2356 \family typewriter
2357 2357 %run
2358 2358 \family default
2359 2359 command with a
2360 2360 \family typewriter
2361 2361 -p
2362 2362 \family default
2363 2363 option allows you to run complete programs under the control of the Python
2364 2364 profiler.
2365 2365 The
2366 2366 \family typewriter
2367 2367 %prun
2368 2368 \family default
2369 2369 command does a similar job for single Python expressions (like function
2370 2370 calls).
2371 2371 \layout Itemize
2372 2372
2373 2373 Use
2374 2374 \family typewriter
2375 2375 %edit
2376 2376 \family default
2377 2377 to have almost multiline editing.
2378 2378 While IPython doesn't support true multiline editing, this command allows
2379 2379 you to call an editor on the spot, and IPython will execute the code you
2380 2380 type in there as if it were typed interactively.
2381 2381 \layout Itemize
2382 2382
2383 2383 Use the IPython.demo.Demo class to load any Python script as an interactive
2384 2384 demo.
2385 2385 With a minimal amount of simple markup, you can control the execution of
2386 2386 the script, stopping as needed.
2387 2387 See sec.\SpecialChar ~
2388 2388
2389 2389 \begin_inset LatexCommand \ref{sec:interactive-demos}
2390 2390
2391 2391 \end_inset
2392 2392
2393 2393 for more.
2394 2394 \layout Standard
2395 2395
2396 2396 If you have your own favorite tip on using IPython efficiently for a certain
2397 2397 task (especially things which can't be done in the normal Python interpreter),
2398 2398 don't hesitate to send it!
2399 2399 \layout Section
2400 2400
2401 2401 Command-line use
2402 2402 \layout Standard
2403 2403
2404 2404 You start IPython with the command:
2405 2405 \layout Standard
2406 2406
2407 2407
2408 2408 \family typewriter
2409 2409 $ ipython [options] files
2410 2410 \layout Standard
2411 2411
2412 2412 If invoked with no options, it executes all the files listed in sequence
2413 2413 and drops you into the interpreter while still acknowledging any options
2414 2414 you may have set in your ipythonrc file.
2415 2415 This behavior is different from standard Python, which when called as
2416 2416 \family typewriter
2417 2417 python -i
2418 2418 \family default
2419 2419 will only execute one file and ignore your configuration setup.
2420 2420 \layout Standard
2421 2421
2422 2422 Please note that some of the configuration options are not available at
2423 2423 the command line, simply because they are not practical here.
2424 2424 Look into your ipythonrc configuration file for details on those.
2425 2425 This file typically installed in the
2426 2426 \family typewriter
2427 2427 $HOME/.ipython
2428 2428 \family default
2429 2429 directory.
2430 2430 For Windows users,
2431 2431 \family typewriter
2432 2432 $HOME
2433 2433 \family default
2434 2434 resolves to
2435 2435 \family typewriter
2436 2436 C:
2437 2437 \backslash
2438 2438
2439 2439 \backslash
2440 2440 Documents and Settings
2441 2441 \backslash
2442 2442
2443 2443 \backslash
2444 2444 YourUserName
2445 2445 \family default
2446 2446 in most instances.
2447 2447 In the rest of this text, we will refer to this directory as
2448 2448 \family typewriter
2449 2449 IPYTHONDIR
2450 2450 \family default
2451 2451 .
2452 2452 \layout Subsection
2453 2453
2454 2454
2455 2455 \begin_inset LatexCommand \label{sec:threading-opts}
2456 2456
2457 2457 \end_inset
2458 2458
2459 2459 Special Threading Options
2460 2460 \layout Standard
2461 2461
2462 2462 The following special options are ONLY valid at the beginning of the command
2463 2463 line, and not later.
2464 2464 This is because they control the initial- ization of ipython itself, before
2465 2465 the normal option-handling mechanism is active.
2466 2466 \layout List
2467 2467 \labelwidthstring 00.00.0000
2468 2468
2469 2469
2470 2470 \family typewriter
2471 2471 \series bold
2472 2472 -gthread,\SpecialChar ~
2473 2473 -qthread,\SpecialChar ~
2474 2474 -wthread,\SpecialChar ~
2475 2475 -pylab:
2476 2476 \family default
2477 2477 \series default
2478 2478 Only
2479 2479 \emph on
2480 2480 one
2481 2481 \emph default
2482 2482 of these can be given, and it can only be given as the first option passed
2483 2483 to IPython (it will have no effect in any other position).
2484 2484 They provide threading support for the GTK Qt and WXPython toolkits, and
2485 2485 for the matplotlib library.
2486 2486 \layout List
2487 2487 \labelwidthstring 00.00.0000
2488 2488
2489 2489 \SpecialChar ~
2490 2490 With any of the first three options, IPython starts running a separate
2491 2491 thread for the graphical toolkit's operation, so that you can open and
2492 2492 control graphical elements from within an IPython command line, without
2493 2493 blocking.
2494 2494 All three provide essentially the same functionality, respectively for
2495 2495 GTK, QT and WXWidgets (via their Python interfaces).
2496 2496 \layout List
2497 2497 \labelwidthstring 00.00.0000
2498 2498
2499 2499 \SpecialChar ~
2500 2500 If
2501 2501 \family typewriter
2502 2502 -pylab
2503 2503 \family default
2504 2504 is given, IPython loads special support for the mat plotlib library (
2505 2505 \begin_inset LatexCommand \htmlurl{http://matplotlib.sourceforge.net}
2506 2506
2507 2507 \end_inset
2508 2508
2509 2509 ), allowing interactive usage of any of its backends as defined in the user's
2510 2510
2511 2511 \family typewriter
2512 2512 ~/.matplotlib/matplotlibrc
2513 2513 \family default
2514 2514 file.
2515 2515 It automatically activates GTK, Qt or WX threading for IPyhton if the choice
2516 2516 of matplotlib backend requires it.
2517 2517 It also modifies the
2518 2518 \family typewriter
2519 2519 %run
2520 2520 \family default
2521 2521 command to correctly execute (without blocking) any matplotlib-based script
2522 2522 which calls
2523 2523 \family typewriter
2524 2524 show()
2525 2525 \family default
2526 2526 at the end.
2527 2527
2528 2528 \layout List
2529 2529 \labelwidthstring 00.00.0000
2530 2530
2531 2531
2532 2532 \family typewriter
2533 2533 \series bold
2534 2534 -tk
2535 2535 \family default
2536 2536 \series default
2537 2537 The
2538 2538 \family typewriter
2539 2539 -g/q/wthread
2540 2540 \family default
2541 2541 options, and
2542 2542 \family typewriter
2543 2543 -pylab
2544 2544 \family default
2545 2545 (if matplotlib is configured to use GTK, Qt or WX), will normally block
2546 2546 Tk graphical interfaces.
2547 2547 This means that when either GTK, Qt or WX threading is active, any attempt
2548 2548 to open a Tk GUI will result in a dead window, and possibly cause the Python
2549 2549 interpreter to crash.
2550 2550 An extra option,
2551 2551 \family typewriter
2552 2552 -tk
2553 2553 \family default
2554 2554 , is available to address this issue.
2555 2555 It can
2556 2556 \emph on
2557 2557 only
2558 2558 \emph default
2559 2559 be given as a
2560 2560 \emph on
2561 2561 second
2562 2562 \emph default
2563 2563 option after any of the above (
2564 2564 \family typewriter
2565 2565 -gthread
2566 2566 \family default
2567 2567 ,
2568 2568 \family typewriter
2569 2569 -wthread
2570 2570 \family default
2571 2571 or
2572 2572 \family typewriter
2573 2573 -pylab
2574 2574 \family default
2575 2575 ).
2576 2576 \layout List
2577 2577 \labelwidthstring 00.00.0000
2578 2578
2579 2579 \SpecialChar ~
2580 2580 If
2581 2581 \family typewriter
2582 2582 -tk
2583 2583 \family default
2584 2584 is given, IPython will try to coordinate Tk threading with GTK, Qt or WX.
2585 2585 This is however potentially unreliable, and you will have to test on your
2586 2586 platform and Python configuration to determine whether it works for you.
2587 2587 Debian users have reported success, apparently due to the fact that Debian
2588 2588 builds all of Tcl, Tk, Tkinter and Python with pthreads support.
2589 2589 Under other Linux environments (such as Fedora Core 2/3), this option has
2590 2590 caused random crashes and lockups of the Python interpreter.
2591 2591 Under other operating systems (Mac OSX and Windows), you'll need to try
2592 2592 it to find out, since currently no user reports are available.
2593 2593 \layout List
2594 2594 \labelwidthstring 00.00.0000
2595 2595
2596 2596 \SpecialChar ~
2597 2597 There is unfortunately no way for IPython to determine at run time whether
2598 2598
2599 2599 \family typewriter
2600 2600 -tk
2601 2601 \family default
2602 2602 will work reliably or not, so you will need to do some experiments before
2603 2603 relying on it for regular work.
2604 2604
2605 2605 \layout Subsection
2606 2606
2607 2607
2608 2608 \begin_inset LatexCommand \label{sec:cmd-line-opts}
2609 2609
2610 2610 \end_inset
2611 2611
2612 2612 Regular Options
2613 2613 \layout Standard
2614 2614
2615 2615 After the above threading options have been given, regular options can follow
2616 2616 in any order.
2617 2617 All options can be abbreviated to their shortest non-ambiguous form and
2618 2618 are case-sensitive.
2619 2619 One or two dashes can be used.
2620 2620 Some options have an alternate short form, indicated after a
2621 2621 \family typewriter
2622 2622 |
2623 2623 \family default
2624 2624 .
2625 2625 \layout Standard
2626 2626
2627 2627 Most options can also be set from your ipythonrc configuration file.
2628 2628 See the provided example for more details on what the options do.
2629 2629 Options given at the command line override the values set in the ipythonrc
2630 2630 file.
2631 2631 \layout Standard
2632 2632
2633 2633 All options with a
2634 2634 \family typewriter
2635 2635 [no]
2636 2636 \family default
2637 2637 prepended can be specified in negated form (
2638 2638 \family typewriter
2639 2639 -nooption
2640 2640 \family default
2641 2641 instead of
2642 2642 \family typewriter
2643 2643 -option
2644 2644 \family default
2645 2645 ) to turn the feature off.
2646 2646 \layout List
2647 2647 \labelwidthstring 00.00.0000
2648 2648
2649 2649
2650 2650 \family typewriter
2651 2651 \series bold
2652 2652 -help
2653 2653 \family default
2654 2654 \series default
2655 2655 : print a help message and exit.
2656 2656 \layout List
2657 2657 \labelwidthstring 00.00.0000
2658 2658
2659 2659
2660 2660 \family typewriter
2661 2661 \series bold
2662 2662 -pylab:
2663 2663 \family default
2664 2664 \series default
2665 2665 this can
2666 2666 \emph on
2667 2667 only
2668 2668 \emph default
2669 2669 be given as the
2670 2670 \emph on
2671 2671 first
2672 2672 \emph default
2673 2673 option passed to IPython (it will have no effect in any other position).
2674 2674 It adds special support for the matplotlib library (
2675 2675 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
2676 2676
2677 2677 \end_inset
2678 2678
2679 2679 ), allowing interactive usage of any of its backends as defined in the user's
2680 2680
2681 2681 \family typewriter
2682 2682 .matplotlibrc
2683 2683 \family default
2684 2684 file.
2685 2685 It automatically activates GTK or WX threading for IPyhton if the choice
2686 2686 of matplotlib backend requires it.
2687 2687 It also modifies the
2688 2688 \family typewriter
2689 2689 %run
2690 2690 \family default
2691 2691 command to correctly execute (without blocking) any matplotlib-based script
2692 2692 which calls
2693 2693 \family typewriter
2694 2694 show()
2695 2695 \family default
2696 2696 at the end.
2697 2697 See Sec.\SpecialChar ~
2698 2698
2699 2699 \begin_inset LatexCommand \ref{sec:matplotlib-support}
2700 2700
2701 2701 \end_inset
2702 2702
2703 2703 for more details.
2704 2704 \layout List
2705 2705 \labelwidthstring 00.00.0000
2706 2706
2707 2707
2708 2708 \family typewriter
2709 2709 \series bold
2710 -[no]autocall:
2711 \family default
2712 \series default
2713 Make IPython automatically call any callable object even if you didn't
2714 type explicit parentheses.
2715 For example, `str 43' becomes `str(43)' automatically.
2716 \layout List
2717 \labelwidthstring 00.00.0000
2718
2719
2720 \family typewriter
2721 \series bold
2722 -[no]autoindent:
2723 \family default
2724 \series default
2725 Turn automatic indentation on/off.
2726 \layout List
2727 \labelwidthstring 00.00.0000
2728
2729
2730 \family typewriter
2731 \series bold
2710 2732 -[no]automagic
2711 2733 \series default
2712 2734 :
2713 2735 \family default
2714 2736 make magic commands automatic (without needing their first character to
2715 2737 be
2716 2738 \family typewriter
2717 2739 %
2718 2740 \family default
2719 2741 ).
2720 2742 Type
2721 2743 \family typewriter
2722 2744 %magic
2723 2745 \family default
2724 2746 at the IPython prompt for more information.
2725 2747 \layout List
2726 2748 \labelwidthstring 00.00.0000
2727 2749
2728 2750
2729 2751 \family typewriter
2730 2752 \series bold
2753 -[no]autoedit_syntax:
2754 \family default
2755 \series default
2756 When a syntax error occurs after editing a file, automatically open the
2757 file to the trouble causing line for convenient fixing.
2758
2759 \layout List
2760 \labelwidthstring 00.00.0000
2761
2762
2763 \family typewriter
2764 \series bold
2731 2765 -[no]banner
2732 2766 \series default
2733 2767 :
2734 2768 \family default
2735 2769 Print the initial information banner (default on).
2736 2770 \layout List
2737 2771 \labelwidthstring 00.00.0000
2738 2772
2739 2773
2740 2774 \family typewriter
2741 2775 \series bold
2742 2776 -c\SpecialChar ~
2743 2777 <command>:
2744 2778 \family default
2745 2779 \series default
2746 2780 execute the given command string, and set sys.argv to
2747 2781 \family typewriter
2748 2782 ['c']
2749 2783 \family default
2750 2784 .
2751 2785 This is similar to the
2752 2786 \family typewriter
2753 2787 -c
2754 2788 \family default
2755 2789 option in the normal Python interpreter.
2756 2790
2757 2791 \layout List
2758 2792 \labelwidthstring 00.00.0000
2759 2793
2760 2794
2761 2795 \family typewriter
2762 2796 \series bold
2763 2797 -cache_size|cs\SpecialChar ~
2764 2798 <n>
2765 2799 \series default
2766 2800 :
2767 2801 \family default
2768 2802 size of the output cache (maximum number of entries to hold in memory).
2769 2803 The default is 1000, you can change it permanently in your config file.
2770 2804 Setting it to 0 completely disables the caching system, and the minimum
2771 2805 value accepted is 20 (if you provide a value less than 20, it is reset
2772 2806 to 0 and a warning is issued) This limit is defined because otherwise you'll
2773 2807 spend more time re-flushing a too small cache than working.
2774 2808 \layout List
2775 2809 \labelwidthstring 00.00.0000
2776 2810
2777 2811
2778 2812 \family typewriter
2779 2813 \series bold
2780 2814 -classic|cl
2781 2815 \series default
2782 2816 :
2783 2817 \family default
2784 2818 Gives IPython a similar feel to the classic Python prompt.
2785 2819 \layout List
2786 2820 \labelwidthstring 00.00.0000
2787 2821
2788 2822
2789 2823 \family typewriter
2790 2824 \series bold
2791 2825 -colors\SpecialChar ~
2792 2826 <scheme>:
2793 2827 \family default
2794 2828 \series default
2795 2829 Color scheme for prompts and exception reporting.
2796 2830 Currently implemented: NoColor, Linux and LightBG.
2797 2831 \layout List
2798 2832 \labelwidthstring 00.00.0000
2799 2833
2800 2834
2801 2835 \family typewriter
2802 2836 \series bold
2803 2837 -[no]color_info:
2804 2838 \family default
2805 2839 \series default
2806 2840 IPython can display information about objects via a set of functions, and
2807 2841 optionally can use colors for this, syntax highlighting source code and
2808 2842 various other elements.
2809 2843 However, because this information is passed through a pager (like 'less')
2810 2844 and many pagers get confused with color codes, this option is off by default.
2811 2845 You can test it and turn it on permanently in your ipythonrc file if it
2812 2846 works for you.
2813 2847 As a reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
2814 2848 that in RedHat 7.2 doesn't.
2815 2849 \layout List
2816 2850 \labelwidthstring 00.00.0000
2817 2851
2818 2852 \SpecialChar ~
2819 2853 Test it and turn it on permanently if it works with your system.
2820 2854 The magic function
2821 2855 \family typewriter
2822 2856 %color_info
2823 2857 \family default
2824 2858 allows you to toggle this interactively for testing.
2825 2859 \layout List
2826 2860 \labelwidthstring 00.00.0000
2827 2861
2828 2862
2829 2863 \family typewriter
2830 2864 \series bold
2831 2865 -[no]debug
2832 2866 \family default
2833 2867 \series default
2834 2868 : Show information about the loading process.
2835 2869 Very useful to pin down problems with your configuration files or to get
2836 2870 details about session restores.
2837 2871 \layout List
2838 2872 \labelwidthstring 00.00.0000
2839 2873
2840 2874
2841 2875 \family typewriter
2842 2876 \series bold
2843 2877 -[no]deep_reload
2844 2878 \series default
2845 2879 :
2846 2880 \family default
2847 2881 IPython can use the
2848 2882 \family typewriter
2849 2883 deep_reload
2850 2884 \family default
2851 2885 module which reloads changes in modules recursively (it replaces the
2852 2886 \family typewriter
2853 2887 reload()
2854 2888 \family default
2855 2889 function, so you don't need to change anything to use it).
2856 2890
2857 2891 \family typewriter
2858 2892 deep_reload()
2859 2893 \family default
2860 2894 forces a full reload of modules whose code may have changed, which the
2861 2895 default
2862 2896 \family typewriter
2863 2897 reload()
2864 2898 \family default
2865 2899 function does not.
2866 2900 \layout List
2867 2901 \labelwidthstring 00.00.0000
2868 2902
2869 2903 \SpecialChar ~
2870 2904 When deep_reload is off, IPython will use the normal
2871 2905 \family typewriter
2872 2906 reload()
2873 2907 \family default
2874 2908 , but deep_reload will still be available as
2875 2909 \family typewriter
2876 2910 dreload()
2877 2911 \family default
2878 2912 .
2879 2913 This feature is off by default [which means that you have both normal
2880 2914 \family typewriter
2881 2915 reload()
2882 2916 \family default
2883 2917 and
2884 2918 \family typewriter
2885 2919 dreload()
2886 2920 \family default
2887 2921 ].
2888 2922 \layout List
2889 2923 \labelwidthstring 00.00.0000
2890 2924
2891 2925
2892 2926 \family typewriter
2893 2927 \series bold
2894 2928 -editor\SpecialChar ~
2895 2929 <name>
2896 2930 \family default
2897 2931 \series default
2898 2932 : Which editor to use with the
2899 2933 \family typewriter
2900 2934 %edit
2901 2935 \family default
2902 2936 command.
2903 2937 By default, IPython will honor your
2904 2938 \family typewriter
2905 2939 EDITOR
2906 2940 \family default
2907 2941 environment variable (if not set, vi is the Unix default and notepad the
2908 2942 Windows one).
2909 2943 Since this editor is invoked on the fly by IPython and is meant for editing
2910 2944 small code snippets, you may want to use a small, lightweight editor here
2911 2945 (in case your default
2912 2946 \family typewriter
2913 2947 EDITOR
2914 2948 \family default
2915 2949 is something like Emacs).
2916 2950 \layout List
2917 2951 \labelwidthstring 00.00.0000
2918 2952
2919 2953
2920 2954 \family typewriter
2921 2955 \series bold
2922 2956 -ipythondir\SpecialChar ~
2923 2957 <name>
2924 2958 \series default
2925 2959 :
2926 2960 \family default
2927 2961 name of your IPython configuration directory
2928 2962 \family typewriter
2929 2963 IPYTHONDIR
2930 2964 \family default
2931 2965 .
2932 2966 This can also be specified through the environment variable
2933 2967 \family typewriter
2934 2968 IPYTHONDIR
2935 2969 \family default
2936 2970 .
2937 2971 \layout List
2938 2972 \labelwidthstring 00.00.0000
2939 2973
2940 2974
2941 2975 \family typewriter
2942 2976 \series bold
2943 2977 -log|l
2944 2978 \family default
2945 2979 \series default
2946 2980 : generate a log file of all input.
2947 2981 Defaults to
2948 2982 \family typewriter
2949 2983 $IPYTHONDIR/log
2950 2984 \family default
2951 2985 .
2952 2986 You can use this to later restore a session by loading your logfile as
2953 2987 a file to be executed with option
2954 2988 \family typewriter
2955 2989 -logplay
2956 2990 \family default
2957 2991 (see below).
2958 2992 \layout List
2959 2993 \labelwidthstring 00.00.0000
2960 2994
2961 2995
2962 2996 \family typewriter
2963 2997 \series bold
2964 2998 -logfile|lf\SpecialChar ~
2965 2999 <name>
2966 3000 \series default
2967 3001 :
2968 3002 \family default
2969 3003 specify the name of your logfile.
2970 3004 \layout List
2971 3005 \labelwidthstring 00.00.0000
2972 3006
2973 3007
2974 3008 \family typewriter
2975 3009 \series bold
2976 3010 -logplay|lp\SpecialChar ~
2977 3011 <name>
2978 3012 \series default
2979 3013 :
2980 3014 \family default
2981 3015 you can replay a previous log.
2982 3016 For restoring a session as close as possible to the state you left it in,
2983 3017 use this option (don't just run the logfile).
2984 3018 With
2985 3019 \family typewriter
2986 3020 -logplay
2987 3021 \family default
2988 3022 , IPython will try to reconstruct the previous working environment in full,
2989 3023 not just execute the commands in the logfile.
2990 3024 \layout List
2991 3025 \labelwidthstring 00.00.0000
2992 3026
2993 3027 \SpecialChar ~
2994 3028 When a session is restored, logging is automatically turned on again with
2995 3029 the name of the logfile it was invoked with (it is read from the log header).
2996 3030 So once you've turned logging on for a session, you can quit IPython and
2997 3031 reload it as many times as you want and it will continue to log its history
2998 3032 and restore from the beginning every time.
2999 3033 \layout List
3000 3034 \labelwidthstring 00.00.0000
3001 3035
3002 3036 \SpecialChar ~
3003 3037 Caveats: there are limitations in this option.
3004 3038 The history variables
3005 3039 \family typewriter
3006 3040 _i*
3007 3041 \family default
3008 3042 ,
3009 3043 \family typewriter
3010 3044 _*
3011 3045 \family default
3012 3046 and
3013 3047 \family typewriter
3014 3048 _dh
3015 3049 \family default
3016 3050 don't get restored properly.
3017 3051 In the future we will try to implement full session saving by writing and
3018 3052 retrieving a 'snapshot' of the memory state of IPython.
3019 3053 But our first attempts failed because of inherent limitations of Python's
3020 3054 Pickle module, so this may have to wait.
3021 3055 \layout List
3022 3056 \labelwidthstring 00.00.0000
3023 3057
3024 3058
3025 3059 \family typewriter
3026 3060 \series bold
3027 3061 -[no]messages
3028 3062 \series default
3029 3063 :
3030 3064 \family default
3031 3065 Print messages which IPython collects about its startup process (default
3032 3066 on).
3033 3067 \layout List
3034 3068 \labelwidthstring 00.00.0000
3035 3069
3036 3070
3037 3071 \family typewriter
3038 3072 \series bold
3039 3073 -[no]pdb
3040 3074 \family default
3041 3075 \series default
3042 3076 : Automatically call the pdb debugger after every uncaught exception.
3043 3077 If you are used to debugging using pdb, this puts you automatically inside
3044 3078 of it after any call (either in IPython or in code called by it) which
3045 3079 triggers an exception which goes uncaught.
3046 3080 \layout List
3047 3081 \labelwidthstring 00.00.0000
3048 3082
3049 3083
3050 3084 \family typewriter
3051 3085 \series bold
3052 3086 -[no]pprint
3053 3087 \series default
3054 3088 :
3055 3089 \family default
3056 3090 ipython can optionally use the pprint (pretty printer) module for displaying
3057 3091 results.
3058 3092 pprint tends to give a nicer display of nested data structures.
3059 3093 If you like it, you can turn it on permanently in your config file (default
3060 3094 off).
3061 3095 \layout List
3062 3096 \labelwidthstring 00.00.0000
3063 3097
3064 3098
3065 3099 \family typewriter
3066 3100 \series bold
3067 3101 -profile|p <name>
3068 3102 \series default
3069 3103 :
3070 3104 \family default
3071 3105 assume that your config file is
3072 3106 \family typewriter
3073 3107 ipythonrc-<name>
3074 3108 \family default
3075 3109 (looks in current dir first, then in
3076 3110 \family typewriter
3077 3111 IPYTHONDIR
3078 3112 \family default
3079 3113 ).
3080 3114 This is a quick way to keep and load multiple config files for different
3081 3115 tasks, especially if you use the include option of config files.
3082 3116 You can keep a basic
3083 3117 \family typewriter
3084 3118 IPYTHONDIR/ipythonrc
3085 3119 \family default
3086 3120 file and then have other 'profiles' which include this one and load extra
3087 3121 things for particular tasks.
3088 3122 For example:
3089 3123 \layout List
3090 3124 \labelwidthstring 00.00.0000
3091 3125
3092 3126
3093 3127 \family typewriter
3094 3128 \SpecialChar ~
3095 3129
3096 3130 \family default
3097 3131 1.
3098 3132
3099 3133 \family typewriter
3100 3134 $HOME/.ipython/ipythonrc
3101 3135 \family default
3102 3136 : load basic things you always want.
3103 3137 \layout List
3104 3138 \labelwidthstring 00.00.0000
3105 3139
3106 3140
3107 3141 \family typewriter
3108 3142 \SpecialChar ~
3109 3143
3110 3144 \family default
3111 3145 2.
3112 3146
3113 3147 \family typewriter
3114 3148 $HOME/.ipython/ipythonrc-math
3115 3149 \family default
3116 3150 : load (1) and basic math-related modules.
3117 3151
3118 3152 \layout List
3119 3153 \labelwidthstring 00.00.0000
3120 3154
3121 3155
3122 3156 \family typewriter
3123 3157 \SpecialChar ~
3124 3158
3125 3159 \family default
3126 3160 3.
3127 3161
3128 3162 \family typewriter
3129 3163 $HOME/.ipython/ipythonrc-numeric
3130 3164 \family default
3131 3165 : load (1) and Numeric and plotting modules.
3132 3166 \layout List
3133 3167 \labelwidthstring 00.00.0000
3134 3168
3135 3169 \SpecialChar ~
3136 3170 Since it is possible to create an endless loop by having circular file
3137 3171 inclusions, IPython will stop if it reaches 15 recursive inclusions.
3138 3172 \layout List
3139 3173 \labelwidthstring 00.00.0000
3140 3174
3141 3175
3142 3176 \family typewriter
3143 3177 \series bold
3144 3178 -prompt_in1|pi1\SpecialChar ~
3145 3179 <string>:
3146 3180 \family default
3147 3181 \series default
3148 3182 Specify the string used for input prompts.
3149 3183 Note that if you are using numbered prompts, the number is represented
3150 3184 with a '
3151 3185 \backslash
3152 3186 #' in the string.
3153 3187 Don't forget to quote strings with spaces embedded in them.
3154 3188 Default: '
3155 3189 \family typewriter
3156 3190 In\SpecialChar ~
3157 3191 [
3158 3192 \backslash
3159 3193 #]:
3160 3194 \family default
3161 3195 '.
3162 3196 Sec.\SpecialChar ~
3163 3197
3164 3198 \begin_inset LatexCommand \ref{sec:prompts}
3165 3199
3166 3200 \end_inset
3167 3201
3168 3202 discusses in detail all the available escapes to customize your prompts.
3169 3203 \layout List
3170 3204 \labelwidthstring 00.00.0000
3171 3205
3172 3206
3173 3207 \family typewriter
3174 3208 \series bold
3175 3209 -prompt_in2|pi2\SpecialChar ~
3176 3210 <string>:
3177 3211 \family default
3178 3212 \series default
3179 3213 Similar to the previous option, but used for the continuation prompts.
3180 3214 The special sequence '
3181 3215 \family typewriter
3182 3216
3183 3217 \backslash
3184 3218 D
3185 3219 \family default
3186 3220 ' is similar to '
3187 3221 \family typewriter
3188 3222
3189 3223 \backslash
3190 3224 #
3191 3225 \family default
3192 3226 ', but with all digits replaced dots (so you can have your continuation
3193 3227 prompt aligned with your input prompt).
3194 3228 Default: '
3195 3229 \family typewriter
3196 3230 \SpecialChar ~
3197 3231 \SpecialChar ~
3198 3232 \SpecialChar ~
3199 3233 .
3200 3234 \backslash
3201 3235 D.:
3202 3236 \family default
3203 3237 ' (note three spaces at the start for alignment with '
3204 3238 \family typewriter
3205 3239 In\SpecialChar ~
3206 3240 [
3207 3241 \backslash
3208 3242 #]
3209 3243 \family default
3210 3244 ').
3211 3245 \layout List
3212 3246 \labelwidthstring 00.00.0000
3213 3247
3214 3248
3215 3249 \family typewriter
3216 3250 \series bold
3217 3251 -prompt_out|po\SpecialChar ~
3218 3252 <string>:
3219 3253 \family default
3220 3254 \series default
3221 3255 String used for output prompts, also uses numbers like
3222 3256 \family typewriter
3223 3257 prompt_in1
3224 3258 \family default
3225 3259 .
3226 3260 Default: '
3227 3261 \family typewriter
3228 3262 Out[
3229 3263 \backslash
3230 3264 #]:
3231 3265 \family default
3232 3266 '
3233 3267 \layout List
3234 3268 \labelwidthstring 00.00.0000
3235 3269
3236 3270
3237 3271 \family typewriter
3238 3272 \series bold
3239 3273 -quick
3240 3274 \family default
3241 3275 \series default
3242 3276 : start in bare bones mode (no config file loaded).
3243 3277 \layout List
3244 3278 \labelwidthstring 00.00.0000
3245 3279
3246 3280
3247 3281 \family typewriter
3248 3282 \series bold
3249 3283 -rcfile\SpecialChar ~
3250 3284 <name>
3251 3285 \series default
3252 3286 :
3253 3287 \family default
3254 3288 name of your IPython resource configuration file.
3255 3289 Normally IPython loads ipythonrc (from current directory) or
3256 3290 \family typewriter
3257 3291 IPYTHONDIR/ipythonrc
3258 3292 \family default
3259 3293 .
3260 3294 \layout List
3261 3295 \labelwidthstring 00.00.0000
3262 3296
3263 3297 \SpecialChar ~
3264 3298 If the loading of your config file fails, IPython starts with a bare bones
3265 3299 configuration (no modules loaded at all).
3266 3300 \layout List
3267 3301 \labelwidthstring 00.00.0000
3268 3302
3269 3303
3270 3304 \family typewriter
3271 3305 \series bold
3272 3306 -[no]readline
3273 3307 \family default
3274 3308 \series default
3275 3309 : use the readline library, which is needed to support name completion and
3276 3310 command history, among other things.
3277 3311 It is enabled by default, but may cause problems for users of X/Emacs in
3278 3312 Python comint or shell buffers.
3279 3313 \layout List
3280 3314 \labelwidthstring 00.00.0000
3281 3315
3282 3316 \SpecialChar ~
3283 3317 Note that X/Emacs 'eterm' buffers (opened with
3284 3318 \family typewriter
3285 3319 M-x\SpecialChar ~
3286 3320 term
3287 3321 \family default
3288 3322 ) support IPython's readline and syntax coloring fine, only 'emacs' (
3289 3323 \family typewriter
3290 3324 M-x\SpecialChar ~
3291 3325 shell
3292 3326 \family default
3293 3327 and
3294 3328 \family typewriter
3295 3329 C-c\SpecialChar ~
3296 3330 !
3297 3331 \family default
3298 3332 ) buffers do not.
3299 3333 \layout List
3300 3334 \labelwidthstring 00.00.0000
3301 3335
3302 3336
3303 3337 \family typewriter
3304 3338 \series bold
3305 3339 -screen_length|sl\SpecialChar ~
3306 3340 <n>
3307 3341 \series default
3308 3342 :
3309 3343 \family default
3310 3344 number of lines of your screen.
3311 3345 This is used to control printing of very long strings.
3312 3346 Strings longer than this number of lines will be sent through a pager instead
3313 3347 of directly printed.
3314 3348 \layout List
3315 3349 \labelwidthstring 00.00.0000
3316 3350
3317 3351 \SpecialChar ~
3318 3352 The default value for this is 0, which means IPython will auto-detect your
3319 3353 screen size every time it needs to print certain potentially long strings
3320 3354 (this doesn't change the behavior of the 'print' keyword, it's only triggered
3321 3355 internally).
3322 3356 If for some reason this isn't working well (it needs curses support), specify
3323 3357 it yourself.
3324 3358 Otherwise don't change the default.
3325 3359 \layout List
3326 3360 \labelwidthstring 00.00.0000
3327 3361
3328 3362
3329 3363 \family typewriter
3330 3364 \series bold
3331 3365 -separate_in|si\SpecialChar ~
3332 3366 <string>
3333 3367 \series default
3334 3368 :
3335 3369 \family default
3336 3370 separator before input prompts.
3337 3371 Default: '
3338 3372 \family typewriter
3339 3373
3340 3374 \backslash
3341 3375 n
3342 3376 \family default
3343 3377 '
3344 3378 \layout List
3345 3379 \labelwidthstring 00.00.0000
3346 3380
3347 3381
3348 3382 \family typewriter
3349 3383 \series bold
3350 3384 -separate_out|so\SpecialChar ~
3351 3385 <string>
3352 3386 \family default
3353 3387 \series default
3354 3388 : separator before output prompts.
3355 3389 Default: nothing.
3356 3390 \layout List
3357 3391 \labelwidthstring 00.00.0000
3358 3392
3359 3393
3360 3394 \family typewriter
3361 3395 \series bold
3362 3396 -separate_out2|so2\SpecialChar ~
3363 3397 <string>
3364 3398 \series default
3365 3399 :
3366 3400 \family default
3367 3401 separator after output prompts.
3368 3402 Default: nothing.
3369 3403 \layout List
3370 3404 \labelwidthstring 00.00.0000
3371 3405
3372 3406 \SpecialChar ~
3373 3407 For these three options, use the value 0 to specify no separator.
3374 3408 \layout List
3375 3409 \labelwidthstring 00.00.0000
3376 3410
3377 3411
3378 3412 \family typewriter
3379 3413 \series bold
3380 3414 -nosep
3381 3415 \series default
3382 3416 :
3383 3417 \family default
3384 3418 shorthand for
3385 3419 \family typewriter
3386 3420 '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'
3387 3421 \family default
3388 3422 .
3389 3423 Simply removes all input/output separators.
3390 3424 \layout List
3391 3425 \labelwidthstring 00.00.0000
3392 3426
3393 3427
3394 3428 \family typewriter
3395 3429 \series bold
3396 3430 -upgrade
3397 3431 \family default
3398 3432 \series default
3399 3433 : allows you to upgrade your
3400 3434 \family typewriter
3401 3435 IPYTHONDIR
3402 3436 \family default
3403 3437 configuration when you install a new version of IPython.
3404 3438 Since new versions may include new command line options or example files,
3405 3439 this copies updated ipythonrc-type files.
3406 3440 However, it backs up (with a
3407 3441 \family typewriter
3408 3442 .old
3409 3443 \family default
3410 3444 extension) all files which it overwrites so that you can merge back any
3411 3445 customizations you might have in your personal files.
3412 3446 \layout List
3413 3447 \labelwidthstring 00.00.0000
3414 3448
3415 3449
3416 3450 \family typewriter
3417 3451 \series bold
3418 3452 -Version
3419 3453 \series default
3420 3454 :
3421 3455 \family default
3422 3456 print version information and exit.
3423 3457 \layout List
3424 3458 \labelwidthstring 00.00.0000
3425 3459
3426 3460
3427 3461 \family typewriter
3428 3462 \series bold
3429 3463 -xmode <modename>
3430 3464 \series default
3431 3465 :
3432 3466 \family default
3433 3467 Mode for exception reporting.
3434 3468 \layout List
3435 3469 \labelwidthstring 00.00.0000
3436 3470
3437 3471 \SpecialChar ~
3438 3472 Valid modes: Plain, Context and Verbose.
3439 3473 \layout List
3440 3474 \labelwidthstring 00.00.0000
3441 3475
3442 3476 \SpecialChar ~
3443 3477 Plain: similar to python's normal traceback printing.
3444 3478 \layout List
3445 3479 \labelwidthstring 00.00.0000
3446 3480
3447 3481 \SpecialChar ~
3448 3482 Context: prints 5 lines of context source code around each line in the
3449 3483 traceback.
3450 3484 \layout List
3451 3485 \labelwidthstring 00.00.0000
3452 3486
3453 3487 \SpecialChar ~
3454 3488 Verbose: similar to Context, but additionally prints the variables currently
3455 3489 visible where the exception happened (shortening their strings if too long).
3456 3490 This can potentially be very slow, if you happen to have a huge data structure
3457 3491 whose string representation is complex to compute.
3458 3492 Your computer may appear to freeze for a while with cpu usage at 100%.
3459 3493 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
3460 3494 it more than once).
3461 3495 \layout Section
3462 3496
3463 3497 Interactive use
3464 3498 \layout Standard
3465 3499
3466 3500
3467 3501 \series bold
3468 3502 Warning
3469 3503 \series default
3470 3504 : IPython relies on the existence of a global variable called
3471 3505 \family typewriter
3472 3506 __IP
3473 3507 \family default
3474 3508 which controls the shell itself.
3475 3509 If you redefine
3476 3510 \family typewriter
3477 3511 __IP
3478 3512 \family default
3479 3513 to anything, bizarre behavior will quickly occur.
3480 3514 \layout Standard
3481 3515
3482 3516 Other than the above warning, IPython is meant to work as a drop-in replacement
3483 3517 for the standard interactive interpreter.
3484 3518 As such, any code which is valid python should execute normally under IPython
3485 3519 (cases where this is not true should be reported as bugs).
3486 3520 It does, however, offer many features which are not available at a standard
3487 3521 python prompt.
3488 3522 What follows is a list of these.
3489 3523 \layout Subsection
3490 3524
3491 3525 Caution for Windows users
3492 3526 \layout Standard
3493 3527
3494 3528 Windows, unfortunately, uses the `
3495 3529 \family typewriter
3496 3530
3497 3531 \backslash
3498 3532
3499 3533 \family default
3500 3534 ' character as a path separator.
3501 3535 This is a terrible choice, because `
3502 3536 \family typewriter
3503 3537
3504 3538 \backslash
3505 3539
3506 3540 \family default
3507 3541 ' also represents the escape character in most modern programming languages,
3508 3542 including Python.
3509 3543 For this reason, issuing many of the commands discussed below (especially
3510 3544 magics which affect the filesystem) with `
3511 3545 \family typewriter
3512 3546
3513 3547 \backslash
3514 3548
3515 3549 \family default
3516 3550 ' in them will cause strange errors.
3517 3551 \layout Standard
3518 3552
3519 3553 A partial solution is to use instead the `
3520 3554 \family typewriter
3521 3555 /
3522 3556 \family default
3523 3557 ' character as a path separator, which Windows recognizes in
3524 3558 \emph on
3525 3559 most
3526 3560 \emph default
3527 3561 situations.
3528 3562 However, in Windows commands `
3529 3563 \family typewriter
3530 3564 /
3531 3565 \family default
3532 3566 ' flags options, so you can not use it for the root directory.
3533 3567 This means that paths beginning at the root must be typed in a contrived
3534 3568 manner like:
3535 3569 \newline
3536 3570
3537 3571 \family typewriter
3538 3572 %copy
3539 3573 \backslash
3540 3574 opt/foo/bar.txt
3541 3575 \backslash
3542 3576 tmp
3543 3577 \layout Standard
3544 3578
3545 3579 There is no sensible thing IPython can do to truly work around this flaw
3546 3580 in Windows
3547 3581 \begin_inset Foot
3548 3582 collapsed true
3549 3583
3550 3584 \layout Standard
3551 3585
3552 3586 If anyone comes up with a
3553 3587 \emph on
3554 3588 clean
3555 3589 \emph default
3556 3590 solution which works consistently and does not negatively impact other
3557 3591 platforms at all, I'll gladly accept a patch.
3558 3592 \end_inset
3559 3593
3560 3594 .
3561 3595 \layout Subsection
3562 3596
3563 3597
3564 3598 \begin_inset LatexCommand \label{sec:magic}
3565 3599
3566 3600 \end_inset
3567 3601
3568 3602 Magic command system
3569 3603 \layout Standard
3570 3604
3571 3605 IPython will treat any line whose first character is a
3572 3606 \family typewriter
3573 3607 %
3574 3608 \family default
3575 3609 as a special call to a 'magic' function.
3576 3610 These allow you to control the behavior of IPython itself, plus a lot of
3577 3611 system-type features.
3578 3612 They are all prefixed with a
3579 3613 \family typewriter
3580 3614 %
3581 3615 \family default
3582 3616 character, but parameters are given without parentheses or quotes.
3583 3617 \layout Standard
3584 3618
3585 3619 Example: typing
3586 3620 \family typewriter
3587 3621 '%cd mydir'
3588 3622 \family default
3589 3623 (without the quotes) changes you working directory to
3590 3624 \family typewriter
3591 3625 'mydir'
3592 3626 \family default
3593 3627 , if it exists.
3594 3628 \layout Standard
3595 3629
3596 3630 If you have 'automagic' enabled (in your
3597 3631 \family typewriter
3598 3632 ipythonrc
3599 3633 \family default
3600 3634 file, via the command line option
3601 3635 \family typewriter
3602 3636 -automagic
3603 3637 \family default
3604 3638 or with the
3605 3639 \family typewriter
3606 3640 %automagic
3607 3641 \family default
3608 3642 function), you don't need to type in the
3609 3643 \family typewriter
3610 3644 %
3611 3645 \family default
3612 3646 explicitly.
3613 3647 IPython will scan its internal list of magic functions and call one if
3614 3648 it exists.
3615 3649 With automagic on you can then just type '
3616 3650 \family typewriter
3617 3651 cd mydir
3618 3652 \family default
3619 3653 ' to go to directory '
3620 3654 \family typewriter
3621 3655 mydir
3622 3656 \family default
3623 3657 '.
3624 3658 The automagic system has the lowest possible precedence in name searches,
3625 3659 so defining an identifier with the same name as an existing magic function
3626 3660 will shadow it for automagic use.
3627 3661 You can still access the shadowed magic function by explicitly using the
3628 3662
3629 3663 \family typewriter
3630 3664 %
3631 3665 \family default
3632 3666 character at the beginning of the line.
3633 3667 \layout Standard
3634 3668
3635 3669 An example (with automagic on) should clarify all this:
3636 3670 \layout LyX-Code
3637 3671
3638 3672 In [1]: cd ipython # %cd is called by automagic
3639 3673 \layout LyX-Code
3640 3674
3641 3675 /home/fperez/ipython
3642 3676 \layout LyX-Code
3643 3677
3644 3678 In [2]: cd=1 # now cd is just a variable
3645 3679 \layout LyX-Code
3646 3680
3647 3681 In [3]: cd ..
3648 3682 # and doesn't work as a function anymore
3649 3683 \layout LyX-Code
3650 3684
3651 3685 ------------------------------------------------------------
3652 3686 \layout LyX-Code
3653 3687
3654 3688 File "<console>", line 1
3655 3689 \layout LyX-Code
3656 3690
3657 3691 cd ..
3658 3692 \layout LyX-Code
3659 3693
3660 3694 ^
3661 3695 \layout LyX-Code
3662 3696
3663 3697 SyntaxError: invalid syntax
3664 3698 \layout LyX-Code
3665 3699
3666 3700 \layout LyX-Code
3667 3701
3668 3702 In [4]: %cd ..
3669 3703 # but %cd always works
3670 3704 \layout LyX-Code
3671 3705
3672 3706 /home/fperez
3673 3707 \layout LyX-Code
3674 3708
3675 3709 In [5]: del cd # if you remove the cd variable
3676 3710 \layout LyX-Code
3677 3711
3678 3712 In [6]: cd ipython # automagic can work again
3679 3713 \layout LyX-Code
3680 3714
3681 3715 /home/fperez/ipython
3682 3716 \layout Standard
3683 3717
3684 3718 You can define your own magic functions to extend the system.
3685 3719 The following is a snippet of code which shows how to do it.
3686 3720 It is provided as file
3687 3721 \family typewriter
3688 3722 example-magic.py
3689 3723 \family default
3690 3724 in the examples directory:
3691 3725 \layout Standard
3692 3726
3693 3727
3694 3728 \begin_inset ERT
3695 3729 status Open
3696 3730
3697 3731 \layout Standard
3698 3732
3699 3733 \backslash
3700 3734 codelist{examples/example-magic.py}
3701 3735 \end_inset
3702 3736
3703 3737
3704 3738 \layout Standard
3705 3739
3706 3740 You can also define your own aliased names for magic functions.
3707 3741 In your
3708 3742 \family typewriter
3709 3743 ipythonrc
3710 3744 \family default
3711 3745 file, placing a line like:
3712 3746 \layout Standard
3713 3747
3714 3748
3715 3749 \family typewriter
3716 3750 execute __IP.magic_cl = __IP.magic_clear
3717 3751 \layout Standard
3718 3752
3719 3753 will define
3720 3754 \family typewriter
3721 3755 %cl
3722 3756 \family default
3723 3757 as a new name for
3724 3758 \family typewriter
3725 3759 %clear
3726 3760 \family default
3727 3761 .
3728 3762 \layout Standard
3729 3763
3730 3764 Type
3731 3765 \family typewriter
3732 3766 %magic
3733 3767 \family default
3734 3768 for more information, including a list of all available magic functions
3735 3769 at any time and their docstrings.
3736 3770 You can also type
3737 3771 \family typewriter
3738 3772 %magic_function_name?
3739 3773 \family default
3740 3774 (see sec.
3741 3775
3742 3776 \begin_inset LatexCommand \ref{sec:dyn-object-info}
3743 3777
3744 3778 \end_inset
3745 3779
3746 3780 for information on the
3747 3781 \family typewriter
3748 3782 '?'
3749 3783 \family default
3750 3784 system) to get information about any particular magic function you are
3751 3785 interested in.
3752 3786 \layout Subsubsection
3753 3787
3754 3788 Magic commands
3755 3789 \layout Standard
3756 3790
3757 3791 The rest of this section is automatically generated for each release from
3758 3792 the docstrings in the IPython code.
3759 3793 Therefore the formatting is somewhat minimal, but this method has the advantage
3760 3794 of having information always in sync with the code.
3761 3795 \layout Standard
3762 3796
3763 3797 A list of all the magic commands available in IPython's
3764 3798 \emph on
3765 3799 default
3766 3800 \emph default
3767 3801 installation follows.
3768 3802 This is similar to what you'll see by simply typing
3769 3803 \family typewriter
3770 3804 %magic
3771 3805 \family default
3772 3806 at the prompt, but that will also give you information about magic commands
3773 3807 you may have added as part of your personal customizations.
3774 3808 \layout Standard
3775 3809
3776 3810
3777 3811 \begin_inset Include \input{magic.tex}
3778 3812 preview false
3779 3813
3780 3814 \end_inset
3781 3815
3782 3816
3783 3817 \layout Subsection
3784 3818
3785 3819 Access to the standard Python help
3786 3820 \layout Standard
3787 3821
3788 3822 As of Python 2.1, a help system is available with access to object docstrings
3789 3823 and the Python manuals.
3790 3824 Simply type
3791 3825 \family typewriter
3792 3826 'help'
3793 3827 \family default
3794 3828 (no quotes) to access it.
3795 3829 You can also type
3796 3830 \family typewriter
3797 3831 help(object)
3798 3832 \family default
3799 3833 to obtain information about a given object, and
3800 3834 \family typewriter
3801 3835 help('keyword')
3802 3836 \family default
3803 3837 for information on a keyword.
3804 3838 As noted in sec.
3805 3839
3806 3840 \begin_inset LatexCommand \ref{sec:help-access}
3807 3841
3808 3842 \end_inset
3809 3843
3810 3844 , you need to properly configure your environment variable
3811 3845 \family typewriter
3812 3846 PYTHONDOCS
3813 3847 \family default
3814 3848 for this feature to work correctly.
3815 3849 \layout Subsection
3816 3850
3817 3851
3818 3852 \begin_inset LatexCommand \label{sec:dyn-object-info}
3819 3853
3820 3854 \end_inset
3821 3855
3822 3856 Dynamic object information
3823 3857 \layout Standard
3824 3858
3825 3859 Typing
3826 3860 \family typewriter
3827 3861 ?word
3828 3862 \family default
3829 3863 or
3830 3864 \family typewriter
3831 3865 word?
3832 3866 \family default
3833 3867 prints detailed information about an object.
3834 3868 If certain strings in the object are too long (docstrings, code, etc.) they
3835 3869 get snipped in the center for brevity.
3836 3870 This system gives access variable types and values, full source code for
3837 3871 any object (if available), function prototypes and other useful information.
3838 3872 \layout Standard
3839 3873
3840 3874 Typing
3841 3875 \family typewriter
3842 3876 ??word
3843 3877 \family default
3844 3878 or
3845 3879 \family typewriter
3846 3880 word??
3847 3881 \family default
3848 3882 gives access to the full information without snipping long strings.
3849 3883 Long strings are sent to the screen through the
3850 3884 \family typewriter
3851 3885 less
3852 3886 \family default
3853 3887 pager if longer than the screen and printed otherwise.
3854 3888 On systems lacking the
3855 3889 \family typewriter
3856 3890 less
3857 3891 \family default
3858 3892 command, IPython uses a very basic internal pager.
3859 3893 \layout Standard
3860 3894
3861 3895 The following magic functions are particularly useful for gathering information
3862 3896 about your working environment.
3863 3897 You can get more details by typing
3864 3898 \family typewriter
3865 3899 %magic
3866 3900 \family default
3867 3901 or querying them individually (use
3868 3902 \family typewriter
3869 3903 %function_name?
3870 3904 \family default
3871 3905 with or without the
3872 3906 \family typewriter
3873 3907 %
3874 3908 \family default
3875 3909 ), this is just a summary:
3876 3910 \layout List
3877 3911 \labelwidthstring 00.00.0000
3878 3912
3879 3913
3880 3914 \family typewriter
3881 3915 \series bold
3882 3916 %pdoc\SpecialChar ~
3883 3917 <object>
3884 3918 \family default
3885 3919 \series default
3886 3920 : Print (or run through a pager if too long) the docstring for an object.
3887 3921 If the given object is a class, it will print both the class and the constructo
3888 3922 r docstrings.
3889 3923 \layout List
3890 3924 \labelwidthstring 00.00.0000
3891 3925
3892 3926
3893 3927 \family typewriter
3894 3928 \series bold
3895 3929 %pdef\SpecialChar ~
3896 3930 <object>
3897 3931 \family default
3898 3932 \series default
3899 3933 : Print the definition header for any callable object.
3900 3934 If the object is a class, print the constructor information.
3901 3935 \layout List
3902 3936 \labelwidthstring 00.00.0000
3903 3937
3904 3938
3905 3939 \family typewriter
3906 3940 \series bold
3907 3941 %psource\SpecialChar ~
3908 3942 <object>
3909 3943 \family default
3910 3944 \series default
3911 3945 : Print (or run through a pager if too long) the source code for an object.
3912 3946 \layout List
3913 3947 \labelwidthstring 00.00.0000
3914 3948
3915 3949
3916 3950 \family typewriter
3917 3951 \series bold
3918 3952 %pfile\SpecialChar ~
3919 3953 <object>
3920 3954 \family default
3921 3955 \series default
3922 3956 : Show the entire source file where an object was defined via a pager, opening
3923 3957 it at the line where the object definition begins.
3924 3958 \layout List
3925 3959 \labelwidthstring 00.00.0000
3926 3960
3927 3961
3928 3962 \family typewriter
3929 3963 \series bold
3930 3964 %who/%whos
3931 3965 \family default
3932 3966 \series default
3933 3967 : These functions give information about identifiers you have defined interactiv
3934 3968 ely (not things you loaded or defined in your configuration files).
3935 3969
3936 3970 \family typewriter
3937 3971 %who
3938 3972 \family default
3939 3973 just prints a list of identifiers and
3940 3974 \family typewriter
3941 3975 %whos
3942 3976 \family default
3943 3977 prints a table with some basic details about each identifier.
3944 3978 \layout Standard
3945 3979
3946 3980 Note that the dynamic object information functions (
3947 3981 \family typewriter
3948 3982 ?/??, %pdoc, %pfile, %pdef, %psource
3949 3983 \family default
3950 3984 ) give you access to documentation even on things which are not really defined
3951 3985 as separate identifiers.
3952 3986 Try for example typing
3953 3987 \family typewriter
3954 3988 {}.get?
3955 3989 \family default
3956 3990 or after doing
3957 3991 \family typewriter
3958 3992 import os
3959 3993 \family default
3960 3994 , type
3961 3995 \family typewriter
3962 3996 os.path.abspath??
3963 3997 \family default
3964 3998 .
3965 3999 \layout Subsection
3966 4000
3967 4001
3968 4002 \begin_inset LatexCommand \label{sec:readline}
3969 4003
3970 4004 \end_inset
3971 4005
3972 4006 Readline-based features
3973 4007 \layout Standard
3974 4008
3975 4009 These features require the GNU readline library, so they won't work if your
3976 4010 Python installation lacks readline support.
3977 4011 We will first describe the default behavior IPython uses, and then how
3978 4012 to change it to suit your preferences.
3979 4013 \layout Subsubsection
3980 4014
3981 4015 Command line completion
3982 4016 \layout Standard
3983 4017
3984 4018 At any time, hitting TAB will complete any available python commands or
3985 4019 variable names, and show you a list of the possible completions if there's
3986 4020 no unambiguous one.
3987 4021 It will also complete filenames in the current directory if no python names
3988 4022 match what you've typed so far.
3989 4023 \layout Subsubsection
3990 4024
3991 4025 Search command history
3992 4026 \layout Standard
3993 4027
3994 4028 IPython provides two ways for searching through previous input and thus
3995 4029 reduce the need for repetitive typing:
3996 4030 \layout Enumerate
3997 4031
3998 4032 Start typing, and then use
3999 4033 \family typewriter
4000 4034 Ctrl-p
4001 4035 \family default
4002 4036 (previous,up) and
4003 4037 \family typewriter
4004 4038 Ctrl-n
4005 4039 \family default
4006 4040 (next,down) to search through only the history items that match what you've
4007 4041 typed so far.
4008 4042 If you use
4009 4043 \family typewriter
4010 4044 Ctrl-p/Ctrl-n
4011 4045 \family default
4012 4046 at a blank prompt, they just behave like normal arrow keys.
4013 4047 \layout Enumerate
4014 4048
4015 4049 Hit
4016 4050 \family typewriter
4017 4051 Ctrl-r
4018 4052 \family default
4019 4053 : opens a search prompt.
4020 4054 Begin typing and the system searches your history for lines that contain
4021 4055 what you've typed so far, completing as much as it can.
4022 4056 \layout Subsubsection
4023 4057
4024 4058 Persistent command history across sessions
4025 4059 \layout Standard
4026 4060
4027 4061 IPython will save your input history when it leaves and reload it next time
4028 4062 you restart it.
4029 4063 By default, the history file is named
4030 4064 \family typewriter
4031 4065 $IPYTHONDIR/history
4032 4066 \family default
4033 4067 , but if you've loaded a named profile, '
4034 4068 \family typewriter
4035 4069 -PROFILE_NAME
4036 4070 \family default
4037 4071 ' is appended to the name.
4038 4072 This allows you to keep separate histories related to various tasks: commands
4039 4073 related to numerical work will not be clobbered by a system shell history,
4040 4074 for example.
4041 4075 \layout Subsubsection
4042 4076
4043 4077 Autoindent
4044 4078 \layout Standard
4045 4079
4046 4080 IPython can recognize lines ending in ':' and indent the next line, while
4047 4081 also un-indenting automatically after 'raise' or 'return'.
4048 4082
4049 4083 \layout Standard
4050 4084
4051 4085 This feature uses the readline library, so it will honor your
4052 4086 \family typewriter
4053 4087 ~/.inputrc
4054 4088 \family default
4055 4089 configuration (or whatever file your
4056 4090 \family typewriter
4057 4091 INPUTRC
4058 4092 \family default
4059 4093 variable points to).
4060 4094 Adding the following lines to your
4061 4095 \family typewriter
4062 4096 .inputrc
4063 4097 \family default
4064 4098 file can make indenting/unindenting more convenient (
4065 4099 \family typewriter
4066 4100 M-i
4067 4101 \family default
4068 4102 indents,
4069 4103 \family typewriter
4070 4104 M-u
4071 4105 \family default
4072 4106 unindents):
4073 4107 \layout Standard
4074 4108
4075 4109
4076 4110 \family typewriter
4077 4111 $if Python
4078 4112 \newline
4079 4113 "
4080 4114 \backslash
4081 4115 M-i": "\SpecialChar ~
4082 4116 \SpecialChar ~
4083 4117 \SpecialChar ~
4084 4118 \SpecialChar ~
4085 4119 "
4086 4120 \newline
4087 4121 "
4088 4122 \backslash
4089 4123 M-u": "
4090 4124 \backslash
4091 4125 d
4092 4126 \backslash
4093 4127 d
4094 4128 \backslash
4095 4129 d
4096 4130 \backslash
4097 4131 d"
4098 4132 \newline
4099 4133 $endif
4100 4134 \layout Standard
4101 4135
4102 4136 Note that there are 4 spaces between the quote marks after
4103 4137 \family typewriter
4104 4138 "M-i"
4105 4139 \family default
4106 4140 above.
4107 4141 \layout Standard
4108 4142
4109 4143
4110 4144 \series bold
4111 4145 Warning:
4112 4146 \series default
4113 4147 this feature is ON by default, but it can cause problems with the pasting
4114 4148 of multi-line indented code (the pasted code gets re-indented on each line).
4115 4149 A magic function
4116 4150 \family typewriter
4117 4151 %autoindent
4118 4152 \family default
4119 4153 allows you to toggle it on/off at runtime.
4120 4154 You can also disable it permanently on in your
4121 4155 \family typewriter
4122 4156 ipythonrc
4123 4157 \family default
4124 4158 file (set
4125 4159 \family typewriter
4126 4160 autoindent 0
4127 4161 \family default
4128 4162 ).
4129 4163 \layout Subsubsection
4130 4164
4131 4165 Customizing readline behavior
4132 4166 \layout Standard
4133 4167
4134 4168 All these features are based on the GNU readline library, which has an extremely
4135 4169 customizable interface.
4136 4170 Normally, readline is configured via a file which defines the behavior
4137 4171 of the library; the details of the syntax for this can be found in the
4138 4172 readline documentation available with your system or on the Internet.
4139 4173 IPython doesn't read this file (if it exists) directly, but it does support
4140 4174 passing to readline valid options via a simple interface.
4141 4175 In brief, you can customize readline by setting the following options in
4142 4176 your
4143 4177 \family typewriter
4144 4178 ipythonrc
4145 4179 \family default
4146 4180 configuration file (note that these options can
4147 4181 \emph on
4148 4182 not
4149 4183 \emph default
4150 4184 be specified at the command line):
4151 4185 \layout List
4152 4186 \labelwidthstring 00.00.0000
4153 4187
4154 4188
4155 4189 \family typewriter
4156 4190 \series bold
4157 4191 readline_parse_and_bind:
4158 4192 \family default
4159 4193 \series default
4160 4194 this option can appear as many times as you want, each time defining a
4161 4195 string to be executed via a
4162 4196 \family typewriter
4163 4197 readline.parse_and_bind()
4164 4198 \family default
4165 4199 command.
4166 4200 The syntax for valid commands of this kind can be found by reading the
4167 4201 documentation for the GNU readline library, as these commands are of the
4168 4202 kind which readline accepts in its configuration file.
4169 4203 \layout List
4170 4204 \labelwidthstring 00.00.0000
4171 4205
4172 4206
4173 4207 \family typewriter
4174 4208 \series bold
4175 4209 readline_remove_delims:
4176 4210 \family default
4177 4211 \series default
4178 4212 a string of characters to be removed from the default word-delimiters list
4179 4213 used by readline, so that completions may be performed on strings which
4180 4214 contain them.
4181 4215 Do not change the default value unless you know what you're doing.
4182 4216 \layout List
4183 4217 \labelwidthstring 00.00.0000
4184 4218
4185 4219
4186 4220 \family typewriter
4187 4221 \series bold
4188 4222 readline_omit__names
4189 4223 \family default
4190 4224 \series default
4191 4225 : when tab-completion is enabled, hitting
4192 4226 \family typewriter
4193 4227 <tab>
4194 4228 \family default
4195 4229 after a '
4196 4230 \family typewriter
4197 4231 .
4198 4232 \family default
4199 4233 ' in a name will complete all attributes of an object, including all the
4200 4234 special methods whose names include double underscores (like
4201 4235 \family typewriter
4202 4236 __getitem__
4203 4237 \family default
4204 4238 or
4205 4239 \family typewriter
4206 4240 __class__
4207 4241 \family default
4208 4242 ).
4209 4243 If you'd rather not see these names by default, you can set this option
4210 4244 to 1.
4211 4245 Note that even when this option is set, you can still see those names by
4212 4246 explicitly typing a
4213 4247 \family typewriter
4214 4248 _
4215 4249 \family default
4216 4250 after the period and hitting
4217 4251 \family typewriter
4218 4252 <tab>
4219 4253 \family default
4220 4254 : '
4221 4255 \family typewriter
4222 4256 name._<tab>
4223 4257 \family default
4224 4258 ' will always complete attribute names starting with '
4225 4259 \family typewriter
4226 4260 _
4227 4261 \family default
4228 4262 '.
4229 4263 \layout List
4230 4264 \labelwidthstring 00.00.0000
4231 4265
4232 4266 \SpecialChar ~
4233 4267 This option is off by default so that new users see all attributes of any
4234 4268 objects they are dealing with.
4235 4269 \layout Standard
4236 4270
4237 4271 You will find the default values along with a corresponding detailed explanation
4238 4272 in your
4239 4273 \family typewriter
4240 4274 ipythonrc
4241 4275 \family default
4242 4276 file.
4243 4277 \layout Subsection
4244 4278
4245 4279 Session logging and restoring
4246 4280 \layout Standard
4247 4281
4248 4282 You can log all input from a session either by starting IPython with the
4249 4283 command line switches
4250 4284 \family typewriter
4251 4285 -log
4252 4286 \family default
4253 4287 or
4254 4288 \family typewriter
4255 4289 -logfile
4256 4290 \family default
4257 4291 (see sec.
4258 4292
4259 4293 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
4260 4294
4261 4295 \end_inset
4262 4296
4263 4297 )or by activating the logging at any moment with the magic function
4264 4298 \family typewriter
4265 4299 %logstart
4266 4300 \family default
4267 4301 .
4268 4302
4269 4303 \layout Standard
4270 4304
4271 4305 Log files can later be reloaded with the
4272 4306 \family typewriter
4273 4307 -logplay
4274 4308 \family default
4275 4309 option and IPython will attempt to 'replay' the log by executing all the
4276 4310 lines in it, thus restoring the state of a previous session.
4277 4311 This feature is not quite perfect, but can still be useful in many cases.
4278 4312 \layout Standard
4279 4313
4280 4314 The log files can also be used as a way to have a permanent record of any
4281 4315 code you wrote while experimenting.
4282 4316 Log files are regular text files which you can later open in your favorite
4283 4317 text editor to extract code or to 'clean them up' before using them to
4284 4318 replay a session.
4285 4319 \layout Standard
4286 4320
4287 4321 The
4288 4322 \family typewriter
4289 4323 %logstart
4290 4324 \family default
4291 4325 function for activating logging in mid-session is used as follows:
4292 4326 \layout Standard
4293 4327
4294 4328
4295 4329 \family typewriter
4296 4330 %logstart [log_name [log_mode]]
4297 4331 \layout Standard
4298 4332
4299 4333 If no name is given, it defaults to a file named
4300 4334 \family typewriter
4301 4335 'log'
4302 4336 \family default
4303 4337 in your IPYTHONDIR directory, in
4304 4338 \family typewriter
4305 4339 'rotate'
4306 4340 \family default
4307 4341 mode (see below).
4308 4342 \layout Standard
4309 4343
4310 4344 '
4311 4345 \family typewriter
4312 4346 %logstart name
4313 4347 \family default
4314 4348 ' saves to file
4315 4349 \family typewriter
4316 4350 'name'
4317 4351 \family default
4318 4352 in
4319 4353 \family typewriter
4320 4354 'backup'
4321 4355 \family default
4322 4356 mode.
4323 4357 It saves your history up to that point and then continues logging.
4324 4358 \layout Standard
4325 4359
4326 4360
4327 4361 \family typewriter
4328 4362 %logstart
4329 4363 \family default
4330 4364 takes a second optional parameter: logging mode.
4331 4365 This can be one of (note that the modes are given unquoted):
4332 4366 \layout List
4333 4367 \labelwidthstring 00.00.0000
4334 4368
4335 4369
4336 4370 \family typewriter
4337 4371 over
4338 4372 \family default
4339 4373 : overwrite existing
4340 4374 \family typewriter
4341 4375 log_name
4342 4376 \family default
4343 4377 .
4344 4378 \layout List
4345 4379 \labelwidthstring 00.00.0000
4346 4380
4347 4381
4348 4382 \family typewriter
4349 4383 backup
4350 4384 \family default
4351 4385 : rename (if exists) to
4352 4386 \family typewriter
4353 4387 log_name~
4354 4388 \family default
4355 4389 and start
4356 4390 \family typewriter
4357 4391 log_name
4358 4392 \family default
4359 4393 .
4360 4394 \layout List
4361 4395 \labelwidthstring 00.00.0000
4362 4396
4363 4397
4364 4398 \family typewriter
4365 4399 append
4366 4400 \family default
4367 4401 : well, that says it.
4368 4402 \layout List
4369 4403 \labelwidthstring 00.00.0000
4370 4404
4371 4405
4372 4406 \family typewriter
4373 4407 rotate
4374 4408 \family default
4375 4409 : create rotating logs
4376 4410 \family typewriter
4377 4411 log_name
4378 4412 \family default
4379 4413 .
4380 4414 \family typewriter
4381 4415 1~
4382 4416 \family default
4383 4417 ,
4384 4418 \family typewriter
4385 4419 log_name.2~
4386 4420 \family default
4387 4421 , etc.
4388 4422 \layout Standard
4389 4423
4390 4424 The
4391 4425 \family typewriter
4392 4426 %logoff
4393 4427 \family default
4394 4428 and
4395 4429 \family typewriter
4396 4430 %logon
4397 4431 \family default
4398 4432 functions allow you to temporarily stop and resume logging to a file which
4399 4433 had previously been started with
4400 4434 \family typewriter
4401 4435 %logstart
4402 4436 \family default
4403 4437 .
4404 4438 They will fail (with an explanation) if you try to use them before logging
4405 4439 has been started.
4406 4440 \layout Subsection
4407 4441
4408 4442
4409 4443 \begin_inset LatexCommand \label{sub:System-shell-access}
4410 4444
4411 4445 \end_inset
4412 4446
4413 4447 System shell access
4414 4448 \layout Standard
4415 4449
4416 4450 Any input line beginning with a
4417 4451 \family typewriter
4418 4452 !
4419 4453 \family default
4420 4454 character is passed verbatim (minus the
4421 4455 \family typewriter
4422 4456 !
4423 4457 \family default
4424 4458 , of course) to the underlying operating system.
4425 4459 For example, typing
4426 4460 \family typewriter
4427 4461 !ls
4428 4462 \family default
4429 4463 will run
4430 4464 \family typewriter
4431 4465 'ls'
4432 4466 \family default
4433 4467 in the current directory.
4434 4468 \layout Subsubsection
4435 4469
4436 4470 Manual capture of command output
4437 4471 \layout Standard
4438 4472
4439 4473 If the input line begins with
4440 4474 \emph on
4441 4475 two
4442 4476 \emph default
4443 4477 exclamation marks,
4444 4478 \family typewriter
4445 4479 !!
4446 4480 \family default
4447 4481 , the command is executed but its output is captured and returned as a python
4448 4482 list, split on newlines.
4449 4483 Any output sent by the subprocess to standard error is printed separately,
4450 4484 so that the resulting list only captures standard output.
4451 4485 The
4452 4486 \family typewriter
4453 4487 !!
4454 4488 \family default
4455 4489 syntax is a shorthand for the
4456 4490 \family typewriter
4457 4491 %sx
4458 4492 \family default
4459 4493 magic command.
4460 4494 \layout Standard
4461 4495
4462 4496 Finally, the
4463 4497 \family typewriter
4464 4498 %sc
4465 4499 \family default
4466 4500 magic (short for `shell capture') is similar to
4467 4501 \family typewriter
4468 4502 %sx
4469 4503 \family default
4470 4504 , but allowing more fine-grained control of the capture details, and storing
4471 4505 the result directly into a named variable.
4472 4506 \layout Standard
4473 4507
4474 4508 See Sec.\SpecialChar ~
4475 4509
4476 4510 \begin_inset LatexCommand \ref{sec:magic}
4477 4511
4478 4512 \end_inset
4479 4513
4480 4514 for details on the magics
4481 4515 \family typewriter
4482 4516 %sc
4483 4517 \family default
4484 4518 and
4485 4519 \family typewriter
4486 4520 %sx
4487 4521 \family default
4488 4522 , or use IPython's own help (
4489 4523 \family typewriter
4490 4524 sc?
4491 4525 \family default
4492 4526 and
4493 4527 \family typewriter
4494 4528 sx?
4495 4529 \family default
4496 4530 ) for further details.
4497 4531 \layout Standard
4498 4532
4499 4533 IPython also allows you to expand the value of python variables when making
4500 4534 system calls.
4501 4535 Any python variable or expression which you prepend with
4502 4536 \family typewriter
4503 4537 $
4504 4538 \family default
4505 4539 will get expanded before the system call is made.
4506 4540
4507 4541 \layout Standard
4508 4542
4509 4543
4510 4544 \family typewriter
4511 4545 In [1]: pyvar='Hello world'
4512 4546 \newline
4513 4547 In [2]: !echo "A python variable: $pyvar"
4514 4548 \newline
4515 4549 A python variable: Hello world
4516 4550 \layout Standard
4517 4551
4518 4552 If you want the shell to actually see a literal
4519 4553 \family typewriter
4520 4554 $
4521 4555 \family default
4522 4556 , you need to type it twice:
4523 4557 \layout Standard
4524 4558
4525 4559
4526 4560 \family typewriter
4527 4561 In [3]: !echo "A system variable: $$HOME"
4528 4562 \newline
4529 4563 A system variable: /home/fperez
4530 4564 \layout Standard
4531 4565
4532 4566 You can pass arbitrary expressions, though you'll need to delimit them with
4533 4567
4534 4568 \family typewriter
4535 4569 {}
4536 4570 \family default
4537 4571 if there is ambiguity as to the extent of the expression:
4538 4572 \layout Standard
4539 4573
4540 4574
4541 4575 \family typewriter
4542 4576 In [5]: x=10
4543 4577 \newline
4544 4578 In [6]: y=20
4545 4579 \newline
4546 4580 In [13]: !echo $x+y
4547 4581 \newline
4548 4582 10+y
4549 4583 \newline
4550 4584 In [7]: !echo ${x+y}
4551 4585 \newline
4552 4586 30
4553 4587 \layout Standard
4554 4588
4555 4589 Even object attributes can be expanded:
4556 4590 \layout Standard
4557 4591
4558 4592
4559 4593 \family typewriter
4560 4594 In [12]: !echo $sys.argv
4561 4595 \newline
4562 4596 [/home/fperez/usr/bin/ipython]
4563 4597 \layout Subsection
4564 4598
4565 4599 System command aliases
4566 4600 \layout Standard
4567 4601
4568 4602 The
4569 4603 \family typewriter
4570 4604 %alias
4571 4605 \family default
4572 4606 magic function and the
4573 4607 \family typewriter
4574 4608 alias
4575 4609 \family default
4576 4610 option in the
4577 4611 \family typewriter
4578 4612 ipythonrc
4579 4613 \family default
4580 4614 configuration file allow you to define magic functions which are in fact
4581 4615 system shell commands.
4582 4616 These aliases can have parameters.
4583 4617
4584 4618 \layout Standard
4585 4619
4586 4620 '
4587 4621 \family typewriter
4588 4622 %alias alias_name cmd
4589 4623 \family default
4590 4624 ' defines '
4591 4625 \family typewriter
4592 4626 alias_name
4593 4627 \family default
4594 4628 ' as an alias for '
4595 4629 \family typewriter
4596 4630 cmd
4597 4631 \family default
4598 4632 '
4599 4633 \layout Standard
4600 4634
4601 4635 Then, typing '
4602 4636 \family typewriter
4603 4637 %alias_name params
4604 4638 \family default
4605 4639 ' will execute the system command '
4606 4640 \family typewriter
4607 4641 cmd params
4608 4642 \family default
4609 4643 ' (from your underlying operating system).
4610 4644
4611 4645 \layout Standard
4612 4646
4613 4647 You can also define aliases with parameters using
4614 4648 \family typewriter
4615 4649 %s
4616 4650 \family default
4617 4651 specifiers (one per parameter).
4618 4652 The following example defines the
4619 4653 \family typewriter
4620 4654 %parts
4621 4655 \family default
4622 4656 function as an alias to the command '
4623 4657 \family typewriter
4624 4658 echo first %s second %s
4625 4659 \family default
4626 4660 ' where each
4627 4661 \family typewriter
4628 4662 %s
4629 4663 \family default
4630 4664 will be replaced by a positional parameter to the call to
4631 4665 \family typewriter
4632 4666 %parts:
4633 4667 \layout Standard
4634 4668
4635 4669
4636 4670 \family typewriter
4637 4671 In [1]: alias parts echo first %s second %s
4638 4672 \newline
4639 4673 In [2]: %parts A B
4640 4674 \newline
4641 4675 first A second B
4642 4676 \newline
4643 4677 In [3]: %parts A
4644 4678 \newline
4645 4679 Incorrect number of arguments: 2 expected.
4646 4680
4647 4681 \newline
4648 4682 parts is an alias to: 'echo first %s second %s'
4649 4683 \layout Standard
4650 4684
4651 4685 If called with no parameters,
4652 4686 \family typewriter
4653 4687 %alias
4654 4688 \family default
4655 4689 prints the table of currently defined aliases.
4656 4690 \layout Standard
4657 4691
4658 4692 The
4659 4693 \family typewriter
4660 4694 %rehash/rehashx
4661 4695 \family default
4662 4696 magics allow you to load your entire
4663 4697 \family typewriter
4664 4698 $PATH
4665 4699 \family default
4666 4700 as ipython aliases.
4667 4701 See their respective docstrings (or sec.\SpecialChar ~
4668 4702
4669 4703 \begin_inset LatexCommand \ref{sec:magic}
4670 4704
4671 4705 \end_inset
4672 4706
4673 4707 for further details).
4674 4708 \layout Subsection
4675 4709
4676 4710
4677 4711 \begin_inset LatexCommand \label{sec:dreload}
4678 4712
4679 4713 \end_inset
4680 4714
4681 4715 Recursive reload
4682 4716 \layout Standard
4683 4717
4684 4718 The
4685 4719 \family typewriter
4686 4720 %dreload
4687 4721 \family default
4688 4722 command does a recursive reload of a module: changes made to the module
4689 4723 since you imported will actually be available without having to exit.
4690 4724 \layout Subsection
4691 4725
4692 4726 Verbose and colored exception traceback printouts
4693 4727 \layout Standard
4694 4728
4695 4729 IPython provides the option to see very detailed exception tracebacks, which
4696 4730 can be especially useful when debugging large programs.
4697 4731 You can run any Python file with the
4698 4732 \family typewriter
4699 4733 %run
4700 4734 \family default
4701 4735 function to benefit from these detailed tracebacks.
4702 4736 Furthermore, both normal and verbose tracebacks can be colored (if your
4703 4737 terminal supports it) which makes them much easier to parse visually.
4704 4738 \layout Standard
4705 4739
4706 4740 See the magic
4707 4741 \family typewriter
4708 4742 xmode
4709 4743 \family default
4710 4744 and
4711 4745 \family typewriter
4712 4746 colors
4713 4747 \family default
4714 4748 functions for details (just type
4715 4749 \family typewriter
4716 4750 %magic
4717 4751 \family default
4718 4752 ).
4719 4753 \layout Standard
4720 4754
4721 4755 These features are basically a terminal version of Ka-Ping Yee's
4722 4756 \family typewriter
4723 4757 cgitb
4724 4758 \family default
4725 4759 module, now part of the standard Python library.
4726 4760 \layout Subsection
4727 4761
4728 4762
4729 4763 \begin_inset LatexCommand \label{sec:cache_input}
4730 4764
4731 4765 \end_inset
4732 4766
4733 4767 Input caching system
4734 4768 \layout Standard
4735 4769
4736 4770 IPython offers numbered prompts (In/Out) with input and output caching.
4737 4771 All input is saved and can be retrieved as variables (besides the usual
4738 4772 arrow key recall).
4739 4773 \layout Standard
4740 4774
4741 4775 The following GLOBAL variables always exist (so don't overwrite them!):
4742 4776
4743 4777 \family typewriter
4744 4778 _i
4745 4779 \family default
4746 4780 : stores previous input.
4747 4781
4748 4782 \family typewriter
4749 4783 _ii
4750 4784 \family default
4751 4785 : next previous.
4752 4786
4753 4787 \family typewriter
4754 4788 _iii
4755 4789 \family default
4756 4790 : next-next previous.
4757 4791
4758 4792 \family typewriter
4759 4793 _ih
4760 4794 \family default
4761 4795 : a list of all input
4762 4796 \family typewriter
4763 4797 _ih[n]
4764 4798 \family default
4765 4799 is the input from line
4766 4800 \family typewriter
4767 4801 n
4768 4802 \family default
4769 4803 and this list is aliased to the global variable
4770 4804 \family typewriter
4771 4805 In
4772 4806 \family default
4773 4807 .
4774 4808 If you overwrite
4775 4809 \family typewriter
4776 4810 In
4777 4811 \family default
4778 4812 with a variable of your own, you can remake the assignment to the internal
4779 4813 list with a simple
4780 4814 \family typewriter
4781 4815 'In=_ih'
4782 4816 \family default
4783 4817 .
4784 4818 \layout Standard
4785 4819
4786 4820 Additionally, global variables named
4787 4821 \family typewriter
4788 4822 _i<n>
4789 4823 \family default
4790 4824 are dynamically created (
4791 4825 \family typewriter
4792 4826 <n>
4793 4827 \family default
4794 4828 being the prompt counter), such that
4795 4829 \newline
4796 4830
4797 4831 \family typewriter
4798 4832 _i<n> == _ih[<n>] == In[<n>].
4799 4833 \layout Standard
4800 4834
4801 4835 For example, what you typed at prompt 14 is available as
4802 4836 \family typewriter
4803 4837 _i14,
4804 4838 \family default
4805 4839
4806 4840 \family typewriter
4807 4841 _ih[14]
4808 4842 \family default
4809 4843 and
4810 4844 \family typewriter
4811 4845 In[14]
4812 4846 \family default
4813 4847 .
4814 4848 \layout Standard
4815 4849
4816 4850 This allows you to easily cut and paste multi line interactive prompts by
4817 4851 printing them out: they print like a clean string, without prompt characters.
4818 4852 You can also manipulate them like regular variables (they are strings),
4819 4853 modify or exec them (typing
4820 4854 \family typewriter
4821 4855 'exec _i9'
4822 4856 \family default
4823 4857 will re-execute the contents of input prompt 9, '
4824 4858 \family typewriter
4825 4859 exec In[9:14]+In[18]
4826 4860 \family default
4827 4861 ' will re-execute lines 9 through 13 and line 18).
4828 4862 \layout Standard
4829 4863
4830 4864 You can also re-execute multiple lines of input easily by using the magic
4831 4865
4832 4866 \family typewriter
4833 4867 %macro
4834 4868 \family default
4835 4869 function (which automates the process and allows re-execution without having
4836 4870 to type '
4837 4871 \family typewriter
4838 4872 exec
4839 4873 \family default
4840 4874 ' every time).
4841 4875 The macro system also allows you to re-execute previous lines which include
4842 4876 magic function calls (which require special processing).
4843 4877 Type
4844 4878 \family typewriter
4845 4879 %macro?
4846 4880 \family default
4847 4881 or see sec.
4848 4882
4849 4883 \begin_inset LatexCommand \ref{sec:magic}
4850 4884
4851 4885 \end_inset
4852 4886
4853 4887 for more details on the macro system.
4854 4888 \layout Standard
4855 4889
4856 4890 A history function
4857 4891 \family typewriter
4858 4892 %hist
4859 4893 \family default
4860 4894 allows you to see any part of your input history by printing a range of
4861 4895 the
4862 4896 \family typewriter
4863 4897 _i
4864 4898 \family default
4865 4899 variables.
4866 4900 \layout Subsection
4867 4901
4868 4902
4869 4903 \begin_inset LatexCommand \label{sec:cache_output}
4870 4904
4871 4905 \end_inset
4872 4906
4873 4907 Output caching system
4874 4908 \layout Standard
4875 4909
4876 4910 For output that is returned from actions, a system similar to the input
4877 4911 cache exists but using
4878 4912 \family typewriter
4879 4913 _
4880 4914 \family default
4881 4915 instead of
4882 4916 \family typewriter
4883 4917 _i
4884 4918 \family default
4885 4919 .
4886 4920 Only actions that produce a result (NOT assignments, for example) are cached.
4887 4921 If you are familiar with Mathematica, IPython's
4888 4922 \family typewriter
4889 4923 _
4890 4924 \family default
4891 4925 variables behave exactly like Mathematica's
4892 4926 \family typewriter
4893 4927 %
4894 4928 \family default
4895 4929 variables.
4896 4930 \layout Standard
4897 4931
4898 4932 The following GLOBAL variables always exist (so don't overwrite them!):
4899 4933
4900 4934 \layout List
4901 4935 \labelwidthstring 00.00.0000
4902 4936
4903 4937
4904 4938 \family typewriter
4905 4939 \series bold
4906 4940 _
4907 4941 \family default
4908 4942 \series default
4909 4943 (a
4910 4944 \emph on
4911 4945 single
4912 4946 \emph default
4913 4947 underscore) : stores previous output, like Python's default interpreter.
4914 4948 \layout List
4915 4949 \labelwidthstring 00.00.0000
4916 4950
4917 4951
4918 4952 \family typewriter
4919 4953 \series bold
4920 4954 __
4921 4955 \family default
4922 4956 \series default
4923 4957 (two underscores): next previous.
4924 4958 \layout List
4925 4959 \labelwidthstring 00.00.0000
4926 4960
4927 4961
4928 4962 \family typewriter
4929 4963 \series bold
4930 4964 ___
4931 4965 \family default
4932 4966 \series default
4933 4967 (three underscores): next-next previous.
4934 4968 \layout Standard
4935 4969
4936 4970 Additionally, global variables named
4937 4971 \family typewriter
4938 4972 _<n>
4939 4973 \family default
4940 4974 are dynamically created (
4941 4975 \family typewriter
4942 4976 <n>
4943 4977 \family default
4944 4978 being the prompt counter), such that the result of output
4945 4979 \family typewriter
4946 4980 <n>
4947 4981 \family default
4948 4982 is always available as
4949 4983 \family typewriter
4950 4984 _<n>
4951 4985 \family default
4952 4986 (don't use the angle brackets, just the number, e.g.
4953 4987
4954 4988 \family typewriter
4955 4989 _21
4956 4990 \family default
4957 4991 ).
4958 4992 \layout Standard
4959 4993
4960 4994 These global variables are all stored in a global dictionary (not a list,
4961 4995 since it only has entries for lines which returned a result) available
4962 4996 under the names
4963 4997 \family typewriter
4964 4998 _oh
4965 4999 \family default
4966 5000 and
4967 5001 \family typewriter
4968 5002 Out
4969 5003 \family default
4970 5004 (similar to
4971 5005 \family typewriter
4972 5006 _ih
4973 5007 \family default
4974 5008 and
4975 5009 \family typewriter
4976 5010 In
4977 5011 \family default
4978 5012 ).
4979 5013 So the output from line 12 can be obtained as
4980 5014 \family typewriter
4981 5015 _12
4982 5016 \family default
4983 5017 ,
4984 5018 \family typewriter
4985 5019 Out[12]
4986 5020 \family default
4987 5021 or
4988 5022 \family typewriter
4989 5023 _oh[12]
4990 5024 \family default
4991 5025 .
4992 5026 If you accidentally overwrite the
4993 5027 \family typewriter
4994 5028 Out
4995 5029 \family default
4996 5030 variable you can recover it by typing
4997 5031 \family typewriter
4998 5032 'Out=_oh
4999 5033 \family default
5000 5034 ' at the prompt.
5001 5035 \layout Standard
5002 5036
5003 5037 This system obviously can potentially put heavy memory demands on your system,
5004 5038 since it prevents Python's garbage collector from removing any previously
5005 5039 computed results.
5006 5040 You can control how many results are kept in memory with the option (at
5007 5041 the command line or in your
5008 5042 \family typewriter
5009 5043 ipythonrc
5010 5044 \family default
5011 5045 file)
5012 5046 \family typewriter
5013 5047 cache_size
5014 5048 \family default
5015 5049 .
5016 5050 If you set it to 0, the whole system is completely disabled and the prompts
5017 5051 revert to the classic
5018 5052 \family typewriter
5019 5053 '>>>'
5020 5054 \family default
5021 5055 of normal Python.
5022 5056 \layout Subsection
5023 5057
5024 5058 Directory history
5025 5059 \layout Standard
5026 5060
5027 5061 Your history of visited directories is kept in the global list
5028 5062 \family typewriter
5029 5063 _dh
5030 5064 \family default
5031 5065 , and the magic
5032 5066 \family typewriter
5033 5067 %cd
5034 5068 \family default
5035 5069 command can be used to go to any entry in that list.
5036 5070 The
5037 5071 \family typewriter
5038 5072 %dhist
5039 5073 \family default
5040 5074 command allows you to view this history.
5041 5075 \layout Subsection
5042 5076
5043 5077 Automatic parentheses and quotes
5044 5078 \layout Standard
5045 5079
5046 5080 These features were adapted from Nathan Gray's LazyPython.
5047 5081 They are meant to allow less typing for common situations.
5048 5082 \layout Subsubsection
5049 5083
5050 5084 Automatic parentheses
5051 5085 \layout Standard
5052 5086
5053 5087 Callable objects (i.e.
5054 5088 functions, methods, etc) can be invoked like this (notice the commas between
5055 5089 the arguments):
5056 5090 \layout Standard
5057 5091
5058 5092
5059 5093 \family typewriter
5060 5094 >>> callable_ob arg1, arg2, arg3
5061 5095 \layout Standard
5062 5096
5063 5097 and the input will be translated to this:
5064 5098 \layout Standard
5065 5099
5066 5100
5067 5101 \family typewriter
5068 5102 --> callable_ob(arg1, arg2, arg3)
5069 5103 \layout Standard
5070 5104
5071 5105 You can force automatic parentheses by using '/' as the first character
5072 5106 of a line.
5073 5107 For example:
5074 5108 \layout Standard
5075 5109
5076 5110
5077 5111 \family typewriter
5078 5112 >>> /globals # becomes 'globals()'
5079 5113 \layout Standard
5080 5114
5081 5115 Note that the '/' MUST be the first character on the line! This won't work:
5082 5116
5083 5117 \layout Standard
5084 5118
5085 5119
5086 5120 \family typewriter
5087 5121 >>> print /globals # syntax error
5088 5122 \layout Standard
5089 5123
5090 5124 In most cases the automatic algorithm should work, so you should rarely
5091 5125 need to explicitly invoke /.
5092 5126 One notable exception is if you are trying to call a function with a list
5093 5127 of tuples as arguments (the parenthesis will confuse IPython):
5094 5128 \layout Standard
5095 5129
5096 5130
5097 5131 \family typewriter
5098 5132 In [1]: zip (1,2,3),(4,5,6) # won't work
5099 5133 \layout Standard
5100 5134
5101 5135 but this will work:
5102 5136 \layout Standard
5103 5137
5104 5138
5105 5139 \family typewriter
5106 5140 In [2]: /zip (1,2,3),(4,5,6)
5107 5141 \newline
5108 5142 ------> zip ((1,2,3),(4,5,6))
5109 5143 \newline
5110 5144 Out[2]= [(1, 4), (2, 5), (3, 6)]
5111 5145 \layout Standard
5112 5146
5113 5147 IPython tells you that it has altered your command line by displaying the
5114 5148 new command line preceded by
5115 5149 \family typewriter
5116 5150 -->
5117 5151 \family default
5118 5152 .
5119 5153 e.g.:
5120 5154 \layout Standard
5121 5155
5122 5156
5123 5157 \family typewriter
5124 5158 In [18]: callable list
5125 5159 \newline
5126 5160 -------> callable (list)
5127 5161 \layout Subsubsection
5128 5162
5129 5163 Automatic quoting
5130 5164 \layout Standard
5131 5165
5132 5166 You can force automatic quoting of a function's arguments by using
5133 5167 \family typewriter
5134 5168 `,'
5135 5169 \family default
5136 5170 or
5137 5171 \family typewriter
5138 5172 `;'
5139 5173 \family default
5140 5174 as the first character of a line.
5141 5175 For example:
5142 5176 \layout Standard
5143 5177
5144 5178
5145 5179 \family typewriter
5146 5180 >>> ,my_function /home/me # becomes my_function("/home/me")
5147 5181 \layout Standard
5148 5182
5149 5183 If you use
5150 5184 \family typewriter
5151 5185 `;'
5152 5186 \family default
5153 5187 instead, the whole argument is quoted as a single string (while
5154 5188 \family typewriter
5155 5189 `,'
5156 5190 \family default
5157 5191 splits on whitespace):
5158 5192 \layout Standard
5159 5193
5160 5194
5161 5195 \family typewriter
5162 5196 >>> ,my_function a b c # becomes my_function("a","b","c")
5163 5197 \layout Standard
5164 5198
5165 5199
5166 5200 \family typewriter
5167 5201 >>> ;my_function a b c # becomes my_function("a b c")
5168 5202 \layout Standard
5169 5203
5170 5204 Note that the `
5171 5205 \family typewriter
5172 5206 ,
5173 5207 \family default
5174 5208 ' or `
5175 5209 \family typewriter
5176 5210 ;
5177 5211 \family default
5178 5212 ' MUST be the first character on the line! This won't work:
5179 5213 \layout Standard
5180 5214
5181 5215
5182 5216 \family typewriter
5183 5217 >>> x = ,my_function /home/me # syntax error
5184 5218 \layout Section
5185 5219
5186 5220
5187 5221 \begin_inset LatexCommand \label{sec:customization}
5188 5222
5189 5223 \end_inset
5190 5224
5191 5225 Customization
5192 5226 \layout Standard
5193 5227
5194 5228 As we've already mentioned, IPython reads a configuration file which can
5195 5229 be specified at the command line (
5196 5230 \family typewriter
5197 5231 -rcfile
5198 5232 \family default
5199 5233 ) or which by default is assumed to be called
5200 5234 \family typewriter
5201 5235 ipythonrc
5202 5236 \family default
5203 5237 .
5204 5238 Such a file is looked for in the current directory where IPython is started
5205 5239 and then in your
5206 5240 \family typewriter
5207 5241 IPYTHONDIR
5208 5242 \family default
5209 5243 , which allows you to have local configuration files for specific projects.
5210 5244 In this section we will call these types of configuration files simply
5211 5245 rcfiles (short for resource configuration file).
5212 5246 \layout Standard
5213 5247
5214 5248 The syntax of an rcfile is one of key-value pairs separated by whitespace,
5215 5249 one per line.
5216 5250 Lines beginning with a
5217 5251 \family typewriter
5218 5252 #
5219 5253 \family default
5220 5254 are ignored as comments, but comments can
5221 5255 \series bold
5222 5256 not
5223 5257 \series default
5224 5258 be put on lines with data (the parser is fairly primitive).
5225 5259 Note that these are not python files, and this is deliberate, because it
5226 5260 allows us to do some things which would be quite tricky to implement if
5227 5261 they were normal python files.
5228 5262 \layout Standard
5229 5263
5230 5264 First, an rcfile can contain permanent default values for almost all command
5231 5265 line options (except things like
5232 5266 \family typewriter
5233 5267 -help
5234 5268 \family default
5235 5269 or
5236 5270 \family typewriter
5237 5271 -Version
5238 5272 \family default
5239 5273 ).
5240 5274 Sec\SpecialChar ~
5241 5275
5242 5276 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5243 5277
5244 5278 \end_inset
5245 5279
5246 5280 contains a description of all command-line options.
5247 5281 However, values you explicitly specify at the command line override the
5248 5282 values defined in the rcfile.
5249 5283 \layout Standard
5250 5284
5251 5285 Besides command line option values, the rcfile can specify values for certain
5252 5286 extra special options which are not available at the command line.
5253 5287 These options are briefly described below.
5254 5288
5255 5289 \layout Standard
5256 5290
5257 5291 Each of these options may appear as many times as you need it in the file.
5258 5292 \layout List
5259 5293 \labelwidthstring 00.00.0000
5260 5294
5261 5295
5262 5296 \family typewriter
5263 5297 \series bold
5264 5298 include\SpecialChar ~
5265 5299 <file1>\SpecialChar ~
5266 5300 <file2>\SpecialChar ~
5267 5301 ...
5268 5302 \family default
5269 5303 \series default
5270 5304 : you can name
5271 5305 \emph on
5272 5306 other
5273 5307 \emph default
5274 5308 rcfiles you want to recursively load up to 15 levels (don't use the
5275 5309 \family typewriter
5276 5310 <>
5277 5311 \family default
5278 5312 brackets in your names!).
5279 5313 This feature allows you to define a 'base' rcfile with general options
5280 5314 and special-purpose files which can be loaded only when needed with particular
5281 5315 configuration options.
5282 5316 To make this more convenient, IPython accepts the
5283 5317 \family typewriter
5284 5318 -profile <name>
5285 5319 \family default
5286 5320 option (abbreviates to
5287 5321 \family typewriter
5288 5322 -p <name
5289 5323 \family default
5290 5324 >)
5291 5325 \family typewriter
5292 5326 which
5293 5327 \family default
5294 5328 tells it to look for an rcfile named
5295 5329 \family typewriter
5296 5330 ipythonrc-<name>
5297 5331 \family default
5298 5332 .
5299 5333
5300 5334 \layout List
5301 5335 \labelwidthstring 00.00.0000
5302 5336
5303 5337
5304 5338 \family typewriter
5305 5339 \series bold
5306 5340 import_mod\SpecialChar ~
5307 5341 <mod1>\SpecialChar ~
5308 5342 <mod2>\SpecialChar ~
5309 5343 ...
5310 5344 \family default
5311 5345 \series default
5312 5346 : import modules with '
5313 5347 \family typewriter
5314 5348 import
5315 5349 \family default
5316 5350
5317 5351 \family typewriter
5318 5352 <mod1>,<mod2>,...
5319 5353 \family default
5320 5354 '
5321 5355 \layout List
5322 5356 \labelwidthstring 00.00.0000
5323 5357
5324 5358
5325 5359 \family typewriter
5326 5360 \series bold
5327 5361 import_some\SpecialChar ~
5328 5362 <mod>\SpecialChar ~
5329 5363 <f1>\SpecialChar ~
5330 5364 <f2>\SpecialChar ~
5331 5365 ...
5332 5366 \family default
5333 5367 \series default
5334 5368 : import functions with '
5335 5369 \family typewriter
5336 5370 from <mod> import
5337 5371 \family default
5338 5372
5339 5373 \family typewriter
5340 5374 <f1>,<f2>,...
5341 5375 \family default
5342 5376 '
5343 5377 \layout List
5344 5378 \labelwidthstring 00.00.0000
5345 5379
5346 5380
5347 5381 \family typewriter
5348 5382 \series bold
5349 5383 import_all\SpecialChar ~
5350 5384 <mod1>\SpecialChar ~
5351 5385 <mod2>\SpecialChar ~
5352 5386 ...
5353 5387 \family default
5354 5388 \series default
5355 5389 : for each module listed import functions with '
5356 5390 \family typewriter
5357 5391 from <mod> import *
5358 5392 \family default
5359 5393 '
5360 5394 \layout List
5361 5395 \labelwidthstring 00.00.0000
5362 5396
5363 5397
5364 5398 \family typewriter
5365 5399 \series bold
5366 5400 execute\SpecialChar ~
5367 5401 <python\SpecialChar ~
5368 5402 code>
5369 5403 \family default
5370 5404 \series default
5371 5405 : give any single-line python code to be executed.
5372 5406 \layout List
5373 5407 \labelwidthstring 00.00.0000
5374 5408
5375 5409
5376 5410 \family typewriter
5377 5411 \series bold
5378 5412 execfile\SpecialChar ~
5379 5413 <filename>
5380 5414 \family default
5381 5415 \series default
5382 5416 : execute the python file given with an '
5383 5417 \family typewriter
5384 5418 execfile(filename)
5385 5419 \family default
5386 5420 ' command.
5387 5421 Username expansion is performed on the given names.
5388 5422 So if you need any amount of extra fancy customization that won't fit in
5389 5423 any of the above 'canned' options, you can just put it in a separate python
5390 5424 file and execute it.
5391 5425 \layout List
5392 5426 \labelwidthstring 00.00.0000
5393 5427
5394 5428
5395 5429 \family typewriter
5396 5430 \series bold
5397 5431 alias\SpecialChar ~
5398 5432 <alias_def>
5399 5433 \family default
5400 5434 \series default
5401 5435 : this is equivalent to calling '
5402 5436 \family typewriter
5403 5437 %alias\SpecialChar ~
5404 5438 <alias_def>
5405 5439 \family default
5406 5440 ' at the IPython command line.
5407 5441 This way, from within IPython you can do common system tasks without having
5408 5442 to exit it or use the
5409 5443 \family typewriter
5410 5444 !
5411 5445 \family default
5412 5446 escape.
5413 5447 IPython isn't meant to be a shell replacement, but it is often very useful
5414 5448 to be able to do things with files while testing code.
5415 5449 This gives you the flexibility to have within IPython any aliases you may
5416 5450 be used to under your normal system shell.
5417 5451 \layout Subsection
5418 5452
5419 5453
5420 5454 \begin_inset LatexCommand \label{sec:ipytonrc-sample}
5421 5455
5422 5456 \end_inset
5423 5457
5424 5458 Sample
5425 5459 \family typewriter
5426 5460 ipythonrc
5427 5461 \family default
5428 5462 file
5429 5463 \layout Standard
5430 5464
5431 5465 The default rcfile, called
5432 5466 \family typewriter
5433 5467 ipythonrc
5434 5468 \family default
5435 5469 and supplied in your
5436 5470 \family typewriter
5437 5471 IPYTHONDIR
5438 5472 \family default
5439 5473 directory contains lots of comments on all of these options.
5440 5474 We reproduce it here for reference:
5441 5475 \layout Standard
5442 5476
5443 5477
5444 5478 \begin_inset ERT
5445 5479 status Open
5446 5480
5447 5481 \layout Standard
5448 5482
5449 5483 \backslash
5450 5484 codelist{../IPython/UserConfig/ipythonrc}
5451 5485 \end_inset
5452 5486
5453 5487
5454 5488 \layout Subsection
5455 5489
5456 5490
5457 5491 \begin_inset LatexCommand \label{sec:prompts}
5458 5492
5459 5493 \end_inset
5460 5494
5461 5495 Fine-tuning your prompt
5462 5496 \layout Standard
5463 5497
5464 5498 IPython's prompts can be customized using a syntax similar to that of the
5465 5499
5466 5500 \family typewriter
5467 5501 bash
5468 5502 \family default
5469 5503 shell.
5470 5504 Many of
5471 5505 \family typewriter
5472 5506 bash
5473 5507 \family default
5474 5508 's escapes are supported, as well as a few additional ones.
5475 5509 We list them below:
5476 5510 \layout Description
5477 5511
5478 5512
5479 5513 \backslash
5480 5514 # the prompt/history count number
5481 5515 \layout Description
5482 5516
5483 5517
5484 5518 \backslash
5485 5519 D the prompt/history count, with the actual digits replaced by dots.
5486 5520 Used mainly in continuation prompts (prompt_in2)
5487 5521 \layout Description
5488 5522
5489 5523
5490 5524 \backslash
5491 5525 w the current working directory
5492 5526 \layout Description
5493 5527
5494 5528
5495 5529 \backslash
5496 5530 W the basename of current working directory
5497 5531 \layout Description
5498 5532
5499 5533
5500 5534 \backslash
5501 5535 X
5502 5536 \emph on
5503 5537 n
5504 5538 \emph default
5505 5539 where
5506 5540 \begin_inset Formula $n=0\ldots5.$
5507 5541 \end_inset
5508 5542
5509 5543 The current working directory, with
5510 5544 \family typewriter
5511 5545 $HOME
5512 5546 \family default
5513 5547 replaced by
5514 5548 \family typewriter
5515 5549 ~
5516 5550 \family default
5517 5551 , and filtered out to contain only
5518 5552 \begin_inset Formula $n$
5519 5553 \end_inset
5520 5554
5521 5555 path elements
5522 5556 \layout Description
5523 5557
5524 5558
5525 5559 \backslash
5526 5560 Y
5527 5561 \emph on
5528 5562 n
5529 5563 \emph default
5530 5564 Similar to
5531 5565 \backslash
5532 5566 X
5533 5567 \emph on
5534 5568 n
5535 5569 \emph default
5536 5570 , but with the
5537 5571 \begin_inset Formula $n+1$
5538 5572 \end_inset
5539 5573
5540 5574 element included if it is
5541 5575 \family typewriter
5542 5576 ~
5543 5577 \family default
5544 5578 (this is similar to the behavior of the %c
5545 5579 \emph on
5546 5580 n
5547 5581 \emph default
5548 5582 escapes in
5549 5583 \family typewriter
5550 5584 tcsh
5551 5585 \family default
5552 5586 )
5553 5587 \layout Description
5554 5588
5555 5589
5556 5590 \backslash
5557 5591 u the username of the current user
5558 5592 \layout Description
5559 5593
5560 5594
5561 5595 \backslash
5562 5596 $ if the effective UID is 0, a #, otherwise a $
5563 5597 \layout Description
5564 5598
5565 5599
5566 5600 \backslash
5567 5601 h the hostname up to the first `.'
5568 5602 \layout Description
5569 5603
5570 5604
5571 5605 \backslash
5572 5606 H the hostname
5573 5607 \layout Description
5574 5608
5575 5609
5576 5610 \backslash
5577 5611 n a newline
5578 5612 \layout Description
5579 5613
5580 5614
5581 5615 \backslash
5582 5616 r a carriage return
5583 5617 \layout Description
5584 5618
5585 5619
5586 5620 \backslash
5587 5621 v IPython version string
5588 5622 \layout Standard
5589 5623
5590 5624 In addition to these, ANSI color escapes can be insterted into the prompts,
5591 5625 as
5592 5626 \family typewriter
5593 5627
5594 5628 \backslash
5595 5629 C_
5596 5630 \emph on
5597 5631 ColorName
5598 5632 \family default
5599 5633 \emph default
5600 5634 .
5601 5635 The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green,
5602 5636 LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor,
5603 5637 Normal, Purple, Red, White, Yellow.
5604 5638 \layout Standard
5605 5639
5606 5640 Finally, IPython supports the evaluation of arbitrary expressions in your
5607 5641 prompt string.
5608 5642 The prompt strings are evaluated through the syntax of PEP 215, but basically
5609 5643 you can use
5610 5644 \family typewriter
5611 5645 $x.y
5612 5646 \family default
5613 5647 to expand the value of
5614 5648 \family typewriter
5615 5649 x.y
5616 5650 \family default
5617 5651 , and for more complicated expressions you can use braces:
5618 5652 \family typewriter
5619 5653 ${foo()+x}
5620 5654 \family default
5621 5655 will call function
5622 5656 \family typewriter
5623 5657 foo
5624 5658 \family default
5625 5659 and add to it the value of
5626 5660 \family typewriter
5627 5661 x
5628 5662 \family default
5629 5663 , before putting the result into your prompt.
5630 5664 For example, using
5631 5665 \newline
5632 5666
5633 5667 \family typewriter
5634 5668 prompt_in1 '${commands.getoutput("uptime")}
5635 5669 \backslash
5636 5670 nIn [
5637 5671 \backslash
5638 5672 #]: '
5639 5673 \newline
5640 5674
5641 5675 \family default
5642 5676 will print the result of the uptime command on each prompt (assuming the
5643 5677
5644 5678 \family typewriter
5645 5679 commands
5646 5680 \family default
5647 5681 module has been imported in your
5648 5682 \family typewriter
5649 5683 ipythonrc
5650 5684 \family default
5651 5685 file).
5652 5686 \layout Subsubsection
5653 5687
5654 5688 Prompt examples
5655 5689 \layout Standard
5656 5690
5657 5691 The following options in an ipythonrc file will give you IPython's default
5658 5692 prompts:
5659 5693 \layout Standard
5660 5694
5661 5695
5662 5696 \family typewriter
5663 5697 prompt_in1 'In [
5664 5698 \backslash
5665 5699 #]:'
5666 5700 \newline
5667 5701 prompt_in2 '\SpecialChar ~
5668 5702 \SpecialChar ~
5669 5703 \SpecialChar ~
5670 5704 .
5671 5705 \backslash
5672 5706 D.:'
5673 5707 \newline
5674 5708 prompt_out 'Out[
5675 5709 \backslash
5676 5710 #]:'
5677 5711 \layout Standard
5678 5712
5679 5713 which look like this:
5680 5714 \layout Standard
5681 5715
5682 5716
5683 5717 \family typewriter
5684 5718 In [1]: 1+2
5685 5719 \newline
5686 5720 Out[1]: 3
5687 5721 \layout Standard
5688 5722
5689 5723
5690 5724 \family typewriter
5691 5725 In [2]: for i in (1,2,3):
5692 5726 \newline
5693 5727
5694 5728 \begin_inset ERT
5695 5729 status Collapsed
5696 5730
5697 5731 \layout Standard
5698 5732
5699 5733 \backslash
5700 5734 hspace*{0mm}
5701 5735 \end_inset
5702 5736
5703 5737 \SpecialChar ~
5704 5738 \SpecialChar ~
5705 5739 \SpecialChar ~
5706 5740 ...: \SpecialChar ~
5707 5741 \SpecialChar ~
5708 5742 \SpecialChar ~
5709 5743 \SpecialChar ~
5710 5744 print i,
5711 5745 \newline
5712 5746
5713 5747 \begin_inset ERT
5714 5748 status Collapsed
5715 5749
5716 5750 \layout Standard
5717 5751
5718 5752 \backslash
5719 5753 hspace*{0mm}
5720 5754 \end_inset
5721 5755
5722 5756 \SpecialChar ~
5723 5757 \SpecialChar ~
5724 5758 \SpecialChar ~
5725 5759 ...:
5726 5760 \newline
5727 5761 1 2 3
5728 5762 \layout Standard
5729 5763
5730 5764 These will give you a very colorful prompt with path information:
5731 5765 \layout Standard
5732 5766
5733 5767
5734 5768 \family typewriter
5735 5769 #prompt_in1 '
5736 5770 \backslash
5737 5771 C_Red
5738 5772 \backslash
5739 5773 u
5740 5774 \backslash
5741 5775 C_Blue[
5742 5776 \backslash
5743 5777 C_Cyan
5744 5778 \backslash
5745 5779 Y1
5746 5780 \backslash
5747 5781 C_Blue]
5748 5782 \backslash
5749 5783 C_LightGreen
5750 5784 \backslash
5751 5785 #>'
5752 5786 \newline
5753 5787 prompt_in2 ' ..
5754 5788 \backslash
5755 5789 D>'
5756 5790 \newline
5757 5791 prompt_out '<
5758 5792 \backslash
5759 5793 #>'
5760 5794 \layout Standard
5761 5795
5762 5796 which look like this:
5763 5797 \layout Standard
5764 5798
5765 5799
5766 5800 \family typewriter
5767 5801 \color red
5768 5802 fperez
5769 5803 \color blue
5770 5804 [
5771 5805 \color cyan
5772 5806 ~/ipython
5773 5807 \color blue
5774 5808 ]
5775 5809 \color green
5776 5810 1>
5777 5811 \color default
5778 5812 1+2
5779 5813 \newline
5780 5814
5781 5815 \begin_inset ERT
5782 5816 status Collapsed
5783 5817
5784 5818 \layout Standard
5785 5819
5786 5820 \backslash
5787 5821 hspace*{0mm}
5788 5822 \end_inset
5789 5823
5790 5824 \SpecialChar ~
5791 5825 \SpecialChar ~
5792 5826 \SpecialChar ~
5793 5827 \SpecialChar ~
5794 5828 \SpecialChar ~
5795 5829 \SpecialChar ~
5796 5830 \SpecialChar ~
5797 5831 \SpecialChar ~
5798 5832 \SpecialChar ~
5799 5833 \SpecialChar ~
5800 5834 \SpecialChar ~
5801 5835 \SpecialChar ~
5802 5836 \SpecialChar ~
5803 5837 \SpecialChar ~
5804 5838 \SpecialChar ~
5805 5839 \SpecialChar ~
5806 5840
5807 5841 \color red
5808 5842 <1>
5809 5843 \color default
5810 5844 3
5811 5845 \newline
5812 5846
5813 5847 \color red
5814 5848 fperez
5815 5849 \color blue
5816 5850 [
5817 5851 \color cyan
5818 5852 ~/ipython
5819 5853 \color blue
5820 5854 ]
5821 5855 \color green
5822 5856 2>
5823 5857 \color default
5824 5858 for i in (1,2,3):
5825 5859 \newline
5826 5860
5827 5861 \begin_inset ERT
5828 5862 status Collapsed
5829 5863
5830 5864 \layout Standard
5831 5865
5832 5866 \backslash
5833 5867 hspace*{0mm}
5834 5868 \end_inset
5835 5869
5836 5870 \SpecialChar ~
5837 5871 \SpecialChar ~
5838 5872 \SpecialChar ~
5839 5873 \SpecialChar ~
5840 5874 \SpecialChar ~
5841 5875 \SpecialChar ~
5842 5876 \SpecialChar ~
5843 5877 \SpecialChar ~
5844 5878 \SpecialChar ~
5845 5879 \SpecialChar ~
5846 5880 \SpecialChar ~
5847 5881 \SpecialChar ~
5848 5882 \SpecialChar ~
5849 5883 \SpecialChar ~
5850 5884 \SpecialChar ~
5851 5885
5852 5886 \color green
5853 5887 ...>
5854 5888 \color default
5855 5889 \SpecialChar ~
5856 5890 \SpecialChar ~
5857 5891 \SpecialChar ~
5858 5892 \SpecialChar ~
5859 5893 print i,
5860 5894 \newline
5861 5895
5862 5896 \begin_inset ERT
5863 5897 status Collapsed
5864 5898
5865 5899 \layout Standard
5866 5900
5867 5901 \backslash
5868 5902 hspace*{0mm}
5869 5903 \end_inset
5870 5904
5871 5905 \SpecialChar ~
5872 5906 \SpecialChar ~
5873 5907 \SpecialChar ~
5874 5908 \SpecialChar ~
5875 5909 \SpecialChar ~
5876 5910 \SpecialChar ~
5877 5911 \SpecialChar ~
5878 5912 \SpecialChar ~
5879 5913 \SpecialChar ~
5880 5914 \SpecialChar ~
5881 5915 \SpecialChar ~
5882 5916 \SpecialChar ~
5883 5917 \SpecialChar ~
5884 5918 \SpecialChar ~
5885 5919 \SpecialChar ~
5886 5920
5887 5921 \color green
5888 5922 ...>
5889 5923 \color default
5890 5924
5891 5925 \newline
5892 5926 1 2 3
5893 5927 \layout Standard
5894 5928
5895 5929 The following shows the usage of dynamic expression evaluation:
5896 5930 \layout Subsection
5897 5931
5898 5932
5899 5933 \begin_inset LatexCommand \label{sec:profiles}
5900 5934
5901 5935 \end_inset
5902 5936
5903 5937 IPython profiles
5904 5938 \layout Standard
5905 5939
5906 5940 As we already mentioned, IPython supports the
5907 5941 \family typewriter
5908 5942 -profile
5909 5943 \family default
5910 5944 command-line option (see sec.
5911 5945
5912 5946 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5913 5947
5914 5948 \end_inset
5915 5949
5916 5950 ).
5917 5951 A profile is nothing more than a particular configuration file like your
5918 5952 basic
5919 5953 \family typewriter
5920 5954 ipythonrc
5921 5955 \family default
5922 5956 one, but with particular customizations for a specific purpose.
5923 5957 When you start IPython with '
5924 5958 \family typewriter
5925 5959 ipython -profile <name>
5926 5960 \family default
5927 5961 ', it assumes that in your
5928 5962 \family typewriter
5929 5963 IPYTHONDIR
5930 5964 \family default
5931 5965 there is a file called
5932 5966 \family typewriter
5933 5967 ipythonrc-<name>
5934 5968 \family default
5935 5969 , and loads it instead of the normal
5936 5970 \family typewriter
5937 5971 ipythonrc
5938 5972 \family default
5939 5973 .
5940 5974 \layout Standard
5941 5975
5942 5976 This system allows you to maintain multiple configurations which load modules,
5943 5977 set options, define functions, etc.
5944 5978 suitable for different tasks and activate them in a very simple manner.
5945 5979 In order to avoid having to repeat all of your basic options (common things
5946 5980 that don't change such as your color preferences, for example), any profile
5947 5981 can include another configuration file.
5948 5982 The most common way to use profiles is then to have each one include your
5949 5983 basic
5950 5984 \family typewriter
5951 5985 ipythonrc
5952 5986 \family default
5953 5987 file as a starting point, and then add further customizations.
5954 5988 \layout Standard
5955 5989
5956 5990 In sections
5957 5991 \begin_inset LatexCommand \ref{sec:syntax-extensions}
5958 5992
5959 5993 \end_inset
5960 5994
5961 5995 and
5962 5996 \begin_inset LatexCommand \ref{sec:Gnuplot}
5963 5997
5964 5998 \end_inset
5965 5999
5966 6000 we discuss some particular profiles which come as part of the standard
5967 6001 IPython distribution.
5968 6002 You may also look in your
5969 6003 \family typewriter
5970 6004 IPYTHONDIR
5971 6005 \family default
5972 6006 directory, any file whose name begins with
5973 6007 \family typewriter
5974 6008 ipythonrc-
5975 6009 \family default
5976 6010 is a profile.
5977 6011 You can use those as examples for further customizations to suit your own
5978 6012 needs.
5979 6013 \layout Section
5980 6014
5981 6015
5982 6016 \begin_inset OptArg
5983 6017 collapsed false
5984 6018
5985 6019 \layout Standard
5986 6020
5987 6021 IPython as default...
5988 6022 \end_inset
5989 6023
5990 6024 IPython as your default Python environment
5991 6025 \layout Standard
5992 6026
5993 6027 Python honors the environment variable
5994 6028 \family typewriter
5995 6029 PYTHONSTARTUP
5996 6030 \family default
5997 6031 and will execute at startup the file referenced by this variable.
5998 6032 If you put at the end of this file the following two lines of code:
5999 6033 \layout Standard
6000 6034
6001 6035
6002 6036 \family typewriter
6003 6037 import IPython
6004 6038 \newline
6005 6039 IPython.Shell.IPShell().mainloop(sys_exit=1)
6006 6040 \layout Standard
6007 6041
6008 6042 then IPython will be your working environment anytime you start Python.
6009 6043 The
6010 6044 \family typewriter
6011 6045 sys_exit=1
6012 6046 \family default
6013 6047 is needed to have IPython issue a call to
6014 6048 \family typewriter
6015 6049 sys.exit()
6016 6050 \family default
6017 6051 when it finishes, otherwise you'll be back at the normal Python '
6018 6052 \family typewriter
6019 6053 >>>
6020 6054 \family default
6021 6055 ' prompt
6022 6056 \begin_inset Foot
6023 6057 collapsed true
6024 6058
6025 6059 \layout Standard
6026 6060
6027 6061 Based on an idea by Holger Krekel.
6028 6062 \end_inset
6029 6063
6030 6064 .
6031 6065 \layout Standard
6032 6066
6033 6067 This is probably useful to developers who manage multiple Python versions
6034 6068 and don't want to have correspondingly multiple IPython versions.
6035 6069 Note that in this mode, there is no way to pass IPython any command-line
6036 6070 options, as those are trapped first by Python itself.
6037 6071 \layout Section
6038 6072
6039 6073
6040 6074 \begin_inset LatexCommand \label{sec:embed}
6041 6075
6042 6076 \end_inset
6043 6077
6044 6078 Embedding IPython
6045 6079 \layout Standard
6046 6080
6047 6081 It is possible to start an IPython instance
6048 6082 \emph on
6049 6083 inside
6050 6084 \emph default
6051 6085 your own Python programs.
6052 6086 This allows you to evaluate dynamically the state of your code, operate
6053 6087 with your variables, analyze them, etc.
6054 6088 Note however that any changes you make to values while in the shell do
6055 6089
6056 6090 \emph on
6057 6091 not
6058 6092 \emph default
6059 6093 propagate back to the running code, so it is safe to modify your values
6060 6094 because you won't break your code in bizarre ways by doing so.
6061 6095 \layout Standard
6062 6096
6063 6097 This feature allows you to easily have a fully functional python environment
6064 6098 for doing object introspection anywhere in your code with a simple function
6065 6099 call.
6066 6100 In some cases a simple print statement is enough, but if you need to do
6067 6101 more detailed analysis of a code fragment this feature can be very valuable.
6068 6102 \layout Standard
6069 6103
6070 6104 It can also be useful in scientific computing situations where it is common
6071 6105 to need to do some automatic, computationally intensive part and then stop
6072 6106 to look at data, plots, etc
6073 6107 \begin_inset Foot
6074 6108 collapsed true
6075 6109
6076 6110 \layout Standard
6077 6111
6078 6112 This functionality was inspired by IDL's combination of the
6079 6113 \family typewriter
6080 6114 stop
6081 6115 \family default
6082 6116 keyword and the
6083 6117 \family typewriter
6084 6118 .continue
6085 6119 \family default
6086 6120 executive command, which I have found very useful in the past, and by a
6087 6121 posting on comp.lang.python by cmkl <cmkleffner-AT-gmx.de> on Dec.
6088 6122 06/01 concerning similar uses of pyrepl.
6089 6123 \end_inset
6090 6124
6091 6125 .
6092 6126 Opening an IPython instance will give you full access to your data and
6093 6127 functions, and you can resume program execution once you are done with
6094 6128 the interactive part (perhaps to stop again later, as many times as needed).
6095 6129 \layout Standard
6096 6130
6097 6131 The following code snippet is the bare minimum you need to include in your
6098 6132 Python programs for this to work (detailed examples follow later):
6099 6133 \layout LyX-Code
6100 6134
6101 6135 from IPython.Shell import IPShellEmbed
6102 6136 \layout LyX-Code
6103 6137
6104 6138 ipshell = IPShellEmbed()
6105 6139 \layout LyX-Code
6106 6140
6107 6141 ipshell() # this call anywhere in your program will start IPython
6108 6142 \layout Standard
6109 6143
6110 6144 You can run embedded instances even in code which is itself being run at
6111 6145 the IPython interactive prompt with '
6112 6146 \family typewriter
6113 6147 %run\SpecialChar ~
6114 6148 <filename>
6115 6149 \family default
6116 6150 '.
6117 6151 Since it's easy to get lost as to where you are (in your top-level IPython
6118 6152 or in your embedded one), it's a good idea in such cases to set the in/out
6119 6153 prompts to something different for the embedded instances.
6120 6154 The code examples below illustrate this.
6121 6155 \layout Standard
6122 6156
6123 6157 You can also have multiple IPython instances in your program and open them
6124 6158 separately, for example with different options for data presentation.
6125 6159 If you close and open the same instance multiple times, its prompt counters
6126 6160 simply continue from each execution to the next.
6127 6161 \layout Standard
6128 6162
6129 6163 Please look at the docstrings in the
6130 6164 \family typewriter
6131 6165 Shell.py
6132 6166 \family default
6133 6167 module for more details on the use of this system.
6134 6168 \layout Standard
6135 6169
6136 6170 The following sample file illustrating how to use the embedding functionality
6137 6171 is provided in the examples directory as
6138 6172 \family typewriter
6139 6173 example-embed.py
6140 6174 \family default
6141 6175 .
6142 6176 It should be fairly self-explanatory:
6143 6177 \layout Standard
6144 6178
6145 6179
6146 6180 \begin_inset ERT
6147 6181 status Open
6148 6182
6149 6183 \layout Standard
6150 6184
6151 6185 \backslash
6152 6186 codelist{examples/example-embed.py}
6153 6187 \end_inset
6154 6188
6155 6189
6156 6190 \layout Standard
6157 6191
6158 6192 Once you understand how the system functions, you can use the following
6159 6193 code fragments in your programs which are ready for cut and paste:
6160 6194 \layout Standard
6161 6195
6162 6196
6163 6197 \begin_inset ERT
6164 6198 status Open
6165 6199
6166 6200 \layout Standard
6167 6201
6168 6202 \backslash
6169 6203 codelist{examples/example-embed-short.py}
6170 6204 \end_inset
6171 6205
6172 6206
6173 6207 \layout Section
6174 6208
6175 6209
6176 6210 \begin_inset LatexCommand \label{sec:using-pdb}
6177 6211
6178 6212 \end_inset
6179 6213
6180 6214 Using the Python debugger (
6181 6215 \family typewriter
6182 6216 pdb
6183 6217 \family default
6184 6218 )
6185 6219 \layout Subsection
6186 6220
6187 6221 Running entire programs via
6188 6222 \family typewriter
6189 6223 pdb
6190 6224 \layout Standard
6191 6225
6192 6226
6193 6227 \family typewriter
6194 6228 pdb
6195 6229 \family default
6196 6230 , the Python debugger, is a powerful interactive debugger which allows you
6197 6231 to step through code, set breakpoints, watch variables, etc.
6198 6232 IPython makes it very easy to start any script under the control of
6199 6233 \family typewriter
6200 6234 pdb
6201 6235 \family default
6202 6236 , regardless of whether you have wrapped it into a
6203 6237 \family typewriter
6204 6238 `main()'
6205 6239 \family default
6206 6240 function or not.
6207 6241 For this, simply type
6208 6242 \family typewriter
6209 6243 `%run -d myscript'
6210 6244 \family default
6211 6245 at an IPython prompt.
6212 6246 See the
6213 6247 \family typewriter
6214 6248 %run
6215 6249 \family default
6216 6250 command's documentation (via
6217 6251 \family typewriter
6218 6252 `%run?'
6219 6253 \family default
6220 6254 or in Sec.\SpecialChar ~
6221 6255
6222 6256 \begin_inset LatexCommand \ref{sec:magic}
6223 6257
6224 6258 \end_inset
6225 6259
6226 6260 ) for more details, including how to control where
6227 6261 \family typewriter
6228 6262 pdb
6229 6263 \family default
6230 6264 will stop execution first.
6231 6265 \layout Standard
6232 6266
6233 6267 For more information on the use of the
6234 6268 \family typewriter
6235 6269 pdb
6236 6270 \family default
6237 6271 debugger, read the included
6238 6272 \family typewriter
6239 6273 pdb.doc
6240 6274 \family default
6241 6275 file (part of the standard Python distribution).
6242 6276 On a stock Linux system it is located at
6243 6277 \family typewriter
6244 6278 /usr/lib/python2.3/pdb.doc
6245 6279 \family default
6246 6280 , but the easiest way to read it is by using the
6247 6281 \family typewriter
6248 6282 help()
6249 6283 \family default
6250 6284 function of the
6251 6285 \family typewriter
6252 6286 pdb
6253 6287 \family default
6254 6288 module as follows (in an IPython prompt):
6255 6289 \layout Standard
6256 6290
6257 6291
6258 6292 \family typewriter
6259 6293 In [1]: import pdb
6260 6294 \newline
6261 6295 In [2]: pdb.help()
6262 6296 \layout Standard
6263 6297
6264 6298 This will load the
6265 6299 \family typewriter
6266 6300 pdb.doc
6267 6301 \family default
6268 6302 document in a file viewer for you automatically.
6269 6303 \layout Subsection
6270 6304
6271 6305 Automatic invocation of
6272 6306 \family typewriter
6273 6307 pdb
6274 6308 \family default
6275 6309 on exceptions
6276 6310 \layout Standard
6277 6311
6278 6312 IPython, if started with the
6279 6313 \family typewriter
6280 6314 -pdb
6281 6315 \family default
6282 6316 option (or if the option is set in your rc file) can call the Python
6283 6317 \family typewriter
6284 6318 pdb
6285 6319 \family default
6286 6320 debugger every time your code triggers an uncaught exception
6287 6321 \begin_inset Foot
6288 6322 collapsed true
6289 6323
6290 6324 \layout Standard
6291 6325
6292 6326 Many thanks to Christopher Hart for the request which prompted adding this
6293 6327 feature to IPython.
6294 6328 \end_inset
6295 6329
6296 6330 .
6297 6331 This feature can also be toggled at any time with the
6298 6332 \family typewriter
6299 6333 %pdb
6300 6334 \family default
6301 6335 magic command.
6302 6336 This can be extremely useful in order to find the origin of subtle bugs,
6303 6337 because
6304 6338 \family typewriter
6305 6339 pdb
6306 6340 \family default
6307 6341 opens up at the point in your code which triggered the exception, and while
6308 6342 your program is at this point `dead', all the data is still available and
6309 6343 you can walk up and down the stack frame and understand the origin of the
6310 6344 problem.
6311 6345 \layout Standard
6312 6346
6313 6347 Furthermore, you can use these debugging facilities both with the embedded
6314 6348 IPython mode and without IPython at all.
6315 6349 For an embedded shell (see sec.
6316 6350
6317 6351 \begin_inset LatexCommand \ref{sec:embed}
6318 6352
6319 6353 \end_inset
6320 6354
6321 6355 ), simply call the constructor with
6322 6356 \family typewriter
6323 6357 `-pdb'
6324 6358 \family default
6325 6359 in the argument string and automatically
6326 6360 \family typewriter
6327 6361 pdb
6328 6362 \family default
6329 6363 will be called if an uncaught exception is triggered by your code.
6330 6364
6331 6365 \layout Standard
6332 6366
6333 6367 For stand-alone use of the feature in your programs which do not use IPython
6334 6368 at all, put the following lines toward the top of your `main' routine:
6335 6369 \layout Standard
6336 6370 \align left
6337 6371
6338 6372 \family typewriter
6339 6373 import sys,IPython.ultraTB
6340 6374 \newline
6341 6375 sys.excepthook = IPython.ultraTB.FormattedTB(mode=`Verbose', color_scheme=`Linux',
6342 6376 call_pdb=1)
6343 6377 \layout Standard
6344 6378
6345 6379 The
6346 6380 \family typewriter
6347 6381 mode
6348 6382 \family default
6349 6383 keyword can be either
6350 6384 \family typewriter
6351 6385 `Verbose'
6352 6386 \family default
6353 6387 or
6354 6388 \family typewriter
6355 6389 `Plain'
6356 6390 \family default
6357 6391 , giving either very detailed or normal tracebacks respectively.
6358 6392 The
6359 6393 \family typewriter
6360 6394 color_scheme
6361 6395 \family default
6362 6396 keyword can be one of
6363 6397 \family typewriter
6364 6398 `NoColor'
6365 6399 \family default
6366 6400 ,
6367 6401 \family typewriter
6368 6402 `Linux'
6369 6403 \family default
6370 6404 (default) or
6371 6405 \family typewriter
6372 6406 `LightBG'
6373 6407 \family default
6374 6408 .
6375 6409 These are the same options which can be set in IPython with
6376 6410 \family typewriter
6377 6411 -colors
6378 6412 \family default
6379 6413 and
6380 6414 \family typewriter
6381 6415 -xmode
6382 6416 \family default
6383 6417 .
6384 6418 \layout Standard
6385 6419
6386 6420 This will give any of your programs detailed, colored tracebacks with automatic
6387 6421 invocation of
6388 6422 \family typewriter
6389 6423 pdb
6390 6424 \family default
6391 6425 .
6392 6426 \layout Section
6393 6427
6394 6428
6395 6429 \begin_inset LatexCommand \label{sec:syntax-extensions}
6396 6430
6397 6431 \end_inset
6398 6432
6399 6433 Extensions for syntax processing
6400 6434 \layout Standard
6401 6435
6402 6436 This isn't for the faint of heart, because the potential for breaking things
6403 6437 is quite high.
6404 6438 But it can be a very powerful and useful feature.
6405 6439 In a nutshell, you can redefine the way IPython processes the user input
6406 6440 line to accept new, special extensions to the syntax without needing to
6407 6441 change any of IPython's own code.
6408 6442 \layout Standard
6409 6443
6410 6444 In the
6411 6445 \family typewriter
6412 6446 IPython/Extensions
6413 6447 \family default
6414 6448 directory you will find some examples supplied, which we will briefly describe
6415 6449 now.
6416 6450 These can be used `as is' (and both provide very useful functionality),
6417 6451 or you can use them as a starting point for writing your own extensions.
6418 6452 \layout Subsection
6419 6453
6420 6454 Pasting of code starting with
6421 6455 \family typewriter
6422 6456 `>>>
6423 6457 \family default
6424 6458 ' or
6425 6459 \family typewriter
6426 6460 `...
6427 6461
6428 6462 \family default
6429 6463 '
6430 6464 \layout Standard
6431 6465
6432 6466 In the python tutorial it is common to find code examples which have been
6433 6467 taken from real python sessions.
6434 6468 The problem with those is that all the lines begin with either
6435 6469 \family typewriter
6436 6470 `>>>
6437 6471 \family default
6438 6472 ' or
6439 6473 \family typewriter
6440 6474 `...
6441 6475
6442 6476 \family default
6443 6477 ', which makes it impossible to paste them all at once.
6444 6478 One must instead do a line by line manual copying, carefully removing the
6445 6479 leading extraneous characters.
6446 6480 \layout Standard
6447 6481
6448 6482 This extension identifies those starting characters and removes them from
6449 6483 the input automatically, so that one can paste multi-line examples directly
6450 6484 into IPython, saving a lot of time.
6451 6485 Please look at the file
6452 6486 \family typewriter
6453 6487 InterpreterPasteInput.py
6454 6488 \family default
6455 6489 in the
6456 6490 \family typewriter
6457 6491 IPython/Extensions
6458 6492 \family default
6459 6493 directory for details on how this is done.
6460 6494 \layout Standard
6461 6495
6462 6496 IPython comes with a special profile enabling this feature, called
6463 6497 \family typewriter
6464 6498 tutorial
6465 6499 \family default
6466 6500 \emph on
6467 6501 .
6468 6502
6469 6503 \emph default
6470 6504 Simply start IPython via
6471 6505 \family typewriter
6472 6506 `ipython\SpecialChar ~
6473 6507 -p\SpecialChar ~
6474 6508 tutorial'
6475 6509 \family default
6476 6510 and the feature will be available.
6477 6511 In a normal IPython session you can activate the feature by importing the
6478 6512 corresponding module with:
6479 6513 \newline
6480 6514
6481 6515 \family typewriter
6482 6516 In [1]: import IPython.Extensions.InterpreterPasteInput
6483 6517 \layout Standard
6484 6518
6485 6519 The following is a 'screenshot' of how things work when this extension is
6486 6520 on, copying an example from the standard tutorial:
6487 6521 \layout Standard
6488 6522
6489 6523
6490 6524 \family typewriter
6491 6525 IPython profile: tutorial
6492 6526 \newline
6493 6527 \SpecialChar ~
6494 6528
6495 6529 \newline
6496 6530 *** Pasting of code with ">>>" or "..." has been enabled.
6497 6531 \newline
6498 6532 \SpecialChar ~
6499 6533
6500 6534 \newline
6501 6535 In [1]: >>> def fib2(n): # return Fibonacci series up to n
6502 6536 \newline
6503 6537
6504 6538 \begin_inset ERT
6505 6539 status Collapsed
6506 6540
6507 6541 \layout Standard
6508 6542
6509 6543 \backslash
6510 6544 hspace*{0mm}
6511 6545 \end_inset
6512 6546
6513 6547 \SpecialChar ~
6514 6548 \SpecialChar ~
6515 6549 ...: ...\SpecialChar ~
6516 6550 \SpecialChar ~
6517 6551 \SpecialChar ~
6518 6552 \SpecialChar ~
6519 6553 """Return a list containing the Fibonacci series up to n."""
6520 6554 \newline
6521 6555
6522 6556 \begin_inset ERT
6523 6557 status Collapsed
6524 6558
6525 6559 \layout Standard
6526 6560
6527 6561 \backslash
6528 6562 hspace*{0mm}
6529 6563 \end_inset
6530 6564
6531 6565 \SpecialChar ~
6532 6566 \SpecialChar ~
6533 6567 ...: ...\SpecialChar ~
6534 6568 \SpecialChar ~
6535 6569 \SpecialChar ~
6536 6570 \SpecialChar ~
6537 6571 result = []
6538 6572 \newline
6539 6573
6540 6574 \begin_inset ERT
6541 6575 status Collapsed
6542 6576
6543 6577 \layout Standard
6544 6578
6545 6579 \backslash
6546 6580 hspace*{0mm}
6547 6581 \end_inset
6548 6582
6549 6583 \SpecialChar ~
6550 6584 \SpecialChar ~
6551 6585 ...: ...\SpecialChar ~
6552 6586 \SpecialChar ~
6553 6587 \SpecialChar ~
6554 6588 \SpecialChar ~
6555 6589 a, b = 0, 1
6556 6590 \newline
6557 6591
6558 6592 \begin_inset ERT
6559 6593 status Collapsed
6560 6594
6561 6595 \layout Standard
6562 6596
6563 6597 \backslash
6564 6598 hspace*{0mm}
6565 6599 \end_inset
6566 6600
6567 6601 \SpecialChar ~
6568 6602 \SpecialChar ~
6569 6603 ...: ...\SpecialChar ~
6570 6604 \SpecialChar ~
6571 6605 \SpecialChar ~
6572 6606 \SpecialChar ~
6573 6607 while b < n:
6574 6608 \newline
6575 6609
6576 6610 \begin_inset ERT
6577 6611 status Collapsed
6578 6612
6579 6613 \layout Standard
6580 6614
6581 6615 \backslash
6582 6616 hspace*{0mm}
6583 6617 \end_inset
6584 6618
6585 6619 \SpecialChar ~
6586 6620 \SpecialChar ~
6587 6621 ...: ...\SpecialChar ~
6588 6622 \SpecialChar ~
6589 6623 \SpecialChar ~
6590 6624 \SpecialChar ~
6591 6625 \SpecialChar ~
6592 6626 \SpecialChar ~
6593 6627 \SpecialChar ~
6594 6628 \SpecialChar ~
6595 6629 result.append(b)\SpecialChar ~
6596 6630 \SpecialChar ~
6597 6631 \SpecialChar ~
6598 6632 # see below
6599 6633 \newline
6600 6634
6601 6635 \begin_inset ERT
6602 6636 status Collapsed
6603 6637
6604 6638 \layout Standard
6605 6639
6606 6640 \backslash
6607 6641 hspace*{0mm}
6608 6642 \end_inset
6609 6643
6610 6644 \SpecialChar ~
6611 6645 \SpecialChar ~
6612 6646 ...: ...\SpecialChar ~
6613 6647 \SpecialChar ~
6614 6648 \SpecialChar ~
6615 6649 \SpecialChar ~
6616 6650 \SpecialChar ~
6617 6651 \SpecialChar ~
6618 6652 \SpecialChar ~
6619 6653 \SpecialChar ~
6620 6654 a, b = b, a+b
6621 6655 \newline
6622 6656
6623 6657 \begin_inset ERT
6624 6658 status Collapsed
6625 6659
6626 6660 \layout Standard
6627 6661
6628 6662 \backslash
6629 6663 hspace*{0mm}
6630 6664 \end_inset
6631 6665
6632 6666 \SpecialChar ~
6633 6667 \SpecialChar ~
6634 6668 ...: ...\SpecialChar ~
6635 6669 \SpecialChar ~
6636 6670 \SpecialChar ~
6637 6671 \SpecialChar ~
6638 6672 return result
6639 6673 \newline
6640 6674
6641 6675 \begin_inset ERT
6642 6676 status Collapsed
6643 6677
6644 6678 \layout Standard
6645 6679
6646 6680 \backslash
6647 6681 hspace*{0mm}
6648 6682 \end_inset
6649 6683
6650 6684 \SpecialChar ~
6651 6685 \SpecialChar ~
6652 6686 ...:
6653 6687 \newline
6654 6688 \SpecialChar ~
6655 6689
6656 6690 \newline
6657 6691 In [2]: fib2(10)
6658 6692 \newline
6659 6693 Out[2]: [1, 1, 2, 3, 5, 8]
6660 6694 \layout Standard
6661 6695
6662 6696 Note that as currently written, this extension does
6663 6697 \emph on
6664 6698 not
6665 6699 \emph default
6666 6700 recognize IPython's prompts for pasting.
6667 6701 Those are more complicated, since the user can change them very easily,
6668 6702 they involve numbers and can vary in length.
6669 6703 One could however extract all the relevant information from the IPython
6670 6704 instance and build an appropriate regular expression.
6671 6705 This is left as an exercise for the reader.
6672 6706 \layout Subsection
6673 6707
6674 6708 Input of physical quantities with units
6675 6709 \layout Standard
6676 6710
6677 6711 The module
6678 6712 \family typewriter
6679 6713 PhysicalQInput
6680 6714 \family default
6681 6715 allows a simplified form of input for physical quantities with units.
6682 6716 This file is meant to be used in conjunction with the
6683 6717 \family typewriter
6684 6718 PhysicalQInteractive
6685 6719 \family default
6686 6720 module (in the same directory) and
6687 6721 \family typewriter
6688 6722 Physics.PhysicalQuantities
6689 6723 \family default
6690 6724 from Konrad Hinsen's ScientificPython (
6691 6725 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/hinsen/scientific.html}
6692 6726
6693 6727 \end_inset
6694 6728
6695 6729 ).
6696 6730 \layout Standard
6697 6731
6698 6732 The
6699 6733 \family typewriter
6700 6734 Physics.PhysicalQuantities
6701 6735 \family default
6702 6736 module defines
6703 6737 \family typewriter
6704 6738 PhysicalQuantity
6705 6739 \family default
6706 6740 objects, but these must be declared as instances of a class.
6707 6741 For example, to define
6708 6742 \family typewriter
6709 6743 v
6710 6744 \family default
6711 6745 as a velocity of 3\SpecialChar ~
6712 6746 m/s, normally you would write:
6713 6747 \family typewriter
6714 6748
6715 6749 \newline
6716 6750 In [1]: v = PhysicalQuantity(3,'m/s')
6717 6751 \layout Standard
6718 6752
6719 6753 Using the
6720 6754 \family typewriter
6721 6755 PhysicalQ_Input
6722 6756 \family default
6723 6757 extension this can be input instead as:
6724 6758 \family typewriter
6725 6759
6726 6760 \newline
6727 6761 In [1]: v = 3 m/s
6728 6762 \family default
6729 6763
6730 6764 \newline
6731 6765 which is much more convenient for interactive use (even though it is blatantly
6732 6766 invalid Python syntax).
6733 6767 \layout Standard
6734 6768
6735 6769 The
6736 6770 \family typewriter
6737 6771 physics
6738 6772 \family default
6739 6773 profile supplied with IPython (enabled via
6740 6774 \family typewriter
6741 6775 'ipython -p physics'
6742 6776 \family default
6743 6777 ) uses these extensions, which you can also activate with:
6744 6778 \layout Standard
6745 6779
6746 6780
6747 6781 \family typewriter
6748 6782 from math import * # math MUST be imported BEFORE PhysicalQInteractive
6749 6783 \newline
6750 6784 from IPython.Extensions.PhysicalQInteractive import *
6751 6785 \newline
6752 6786 import IPython.Extensions.PhysicalQInput
6753 6787 \layout Section
6754 6788
6755 6789 IPython as a system shell
6756 6790 \layout Standard
6757 6791
6758 6792 IPython ships with a special profile called
6759 6793 \family typewriter
6760 6794 pysh
6761 6795 \family default
6762 6796 , which you can activate at the command line as
6763 6797 \family typewriter
6764 6798 `ipython -p pysh'
6765 6799 \family default
6766 6800 .
6767 6801 This loads
6768 6802 \family typewriter
6769 6803 InterpreterExec
6770 6804 \family default
6771 6805 , along with some additional facilities and a prompt customized for filesystem
6772 6806 navigation.
6773 6807 \layout Standard
6774 6808
6775 6809 Note that this does
6776 6810 \emph on
6777 6811 not
6778 6812 \emph default
6779 6813 make IPython a full-fledged system shell.
6780 6814 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
6781 6815 you'll suspend pysh itself, not the process you just started.
6782 6816
6783 6817 \layout Standard
6784 6818
6785 6819 What the shell profile allows you to do is to use the convenient and powerful
6786 6820 syntax of Python to do quick scripting at the command line.
6787 6821 Below we describe some of its features.
6788 6822 \layout Subsection
6789 6823
6790 6824 Aliases
6791 6825 \layout Standard
6792 6826
6793 6827 All of your
6794 6828 \family typewriter
6795 6829 $PATH
6796 6830 \family default
6797 6831 has been loaded as IPython aliases, so you should be able to type any normal
6798 6832 system command and have it executed.
6799 6833 See
6800 6834 \family typewriter
6801 6835 %alias?
6802 6836 \family default
6803 6837 and
6804 6838 \family typewriter
6805 6839 %unalias?
6806 6840 \family default
6807 6841 for details on the alias facilities.
6808 6842 See also
6809 6843 \family typewriter
6810 6844 %rehash?
6811 6845 \family default
6812 6846 and
6813 6847 \family typewriter
6814 6848 %rehashx?
6815 6849 \family default
6816 6850 for details on the mechanism used to load
6817 6851 \family typewriter
6818 6852 $PATH
6819 6853 \family default
6820 6854 .
6821 6855 \layout Subsection
6822 6856
6823 6857 Special syntax
6824 6858 \layout Standard
6825 6859
6826 6860 Any lines which begin with
6827 6861 \family typewriter
6828 6862 `~'
6829 6863 \family default
6830 6864 ,
6831 6865 \family typewriter
6832 6866 `/'
6833 6867 \family default
6834 6868 and
6835 6869 \family typewriter
6836 6870 `.'
6837 6871 \family default
6838 6872 will be executed as shell commands instead of as Python code.
6839 6873 The special escapes below are also recognized.
6840 6874
6841 6875 \family typewriter
6842 6876 !cmd
6843 6877 \family default
6844 6878 is valid in single or multi-line input, all others are only valid in single-lin
6845 6879 e input:
6846 6880 \layout Description
6847 6881
6848 6882
6849 6883 \family typewriter
6850 6884 !cmd
6851 6885 \family default
6852 6886 pass `cmd' directly to the shell
6853 6887 \layout Description
6854 6888
6855 6889
6856 6890 \family typewriter
6857 6891 !!cmd
6858 6892 \family default
6859 6893 execute `cmd' and return output as a list (split on `
6860 6894 \backslash
6861 6895 n')
6862 6896 \layout Description
6863 6897
6864 6898
6865 6899 \family typewriter
6866 6900 $var=cmd
6867 6901 \family default
6868 6902 capture output of cmd into var, as a string
6869 6903 \layout Description
6870 6904
6871 6905
6872 6906 \family typewriter
6873 6907 $$var=cmd
6874 6908 \family default
6875 6909 capture output of cmd into var, as a list (split on `
6876 6910 \backslash
6877 6911 n')
6878 6912 \layout Standard
6879 6913
6880 6914 The
6881 6915 \family typewriter
6882 6916 $
6883 6917 \family default
6884 6918 /
6885 6919 \family typewriter
6886 6920 $$
6887 6921 \family default
6888 6922 syntaxes make Python variables from system output, which you can later
6889 6923 use for further scripting.
6890 6924 The converse is also possible: when executing an alias or calling to the
6891 6925 system via
6892 6926 \family typewriter
6893 6927 !
6894 6928 \family default
6895 6929 /
6896 6930 \family typewriter
6897 6931 !!
6898 6932 \family default
6899 6933 , you can expand any python variable or expression by prepending it with
6900 6934
6901 6935 \family typewriter
6902 6936 $
6903 6937 \family default
6904 6938 .
6905 6939 Full details of the allowed syntax can be found in Python's PEP 215.
6906 6940 \layout Standard
6907 6941
6908 6942 A few brief examples will illustrate these (note that the indentation below
6909 6943 may be incorrectly displayed):
6910 6944 \layout Standard
6911 6945
6912 6946
6913 6947 \family typewriter
6914 6948 fperez[~/test]|3> !ls *s.py
6915 6949 \newline
6916 6950 scopes.py strings.py
6917 6951 \layout Standard
6918 6952
6919 6953 ls is an internal alias, so there's no need to use
6920 6954 \family typewriter
6921 6955 !
6922 6956 \family default
6923 6957 :
6924 6958 \layout Standard
6925 6959
6926 6960
6927 6961 \family typewriter
6928 6962 fperez[~/test]|4> ls *s.py
6929 6963 \newline
6930 6964 scopes.py* strings.py
6931 6965 \layout Standard
6932 6966
6933 6967 !!ls will return the output into a Python variable:
6934 6968 \layout Standard
6935 6969
6936 6970
6937 6971 \family typewriter
6938 6972 fperez[~/test]|5> !!ls *s.py
6939 6973 \newline
6940 6974
6941 6975 \begin_inset ERT
6942 6976 status Collapsed
6943 6977
6944 6978 \layout Standard
6945 6979
6946 6980 \backslash
6947 6981 hspace*{0mm}
6948 6982 \end_inset
6949 6983
6950 6984 \SpecialChar ~
6951 6985 \SpecialChar ~
6952 6986 \SpecialChar ~
6953 6987 \SpecialChar ~
6954 6988 \SpecialChar ~
6955 6989 \SpecialChar ~
6956 6990 \SpecialChar ~
6957 6991 \SpecialChar ~
6958 6992 \SpecialChar ~
6959 6993 \SpecialChar ~
6960 6994 \SpecialChar ~
6961 6995 \SpecialChar ~
6962 6996 \SpecialChar ~
6963 6997 \SpecialChar ~
6964 6998 <5> ['scopes.py', 'strings.py']
6965 6999 \newline
6966 7000 fperez[~/test]|6> print _5
6967 7001 \newline
6968 7002 ['scopes.py', 'strings.py']
6969 7003 \layout Standard
6970 7004
6971 7005
6972 7006 \family typewriter
6973 7007 $
6974 7008 \family default
6975 7009 and
6976 7010 \family typewriter
6977 7011 $$
6978 7012 \family default
6979 7013 allow direct capture to named variables:
6980 7014 \layout Standard
6981 7015
6982 7016
6983 7017 \family typewriter
6984 7018 fperez[~/test]|7> $astr = ls *s.py
6985 7019 \newline
6986 7020 fperez[~/test]|8> astr
6987 7021 \newline
6988 7022
6989 7023 \begin_inset ERT
6990 7024 status Collapsed
6991 7025
6992 7026 \layout Standard
6993 7027
6994 7028 \backslash
6995 7029 hspace*{0mm}
6996 7030 \end_inset
6997 7031
6998 7032 \SpecialChar ~
6999 7033 \SpecialChar ~
7000 7034 \SpecialChar ~
7001 7035 \SpecialChar ~
7002 7036 \SpecialChar ~
7003 7037 \SpecialChar ~
7004 7038 \SpecialChar ~
7005 7039 \SpecialChar ~
7006 7040 \SpecialChar ~
7007 7041 \SpecialChar ~
7008 7042 \SpecialChar ~
7009 7043 \SpecialChar ~
7010 7044 \SpecialChar ~
7011 7045 \SpecialChar ~
7012 7046 <8> 'scopes.py
7013 7047 \backslash
7014 7048 nstrings.py'
7015 7049 \layout Standard
7016 7050
7017 7051
7018 7052 \family typewriter
7019 7053 fperez[~/test]|9> $$alist = ls *s.py
7020 7054 \newline
7021 7055 fperez[~/test]|10> alist
7022 7056 \newline
7023 7057
7024 7058 \begin_inset ERT
7025 7059 status Collapsed
7026 7060
7027 7061 \layout Standard
7028 7062
7029 7063 \backslash
7030 7064 hspace*{0mm}
7031 7065 \end_inset
7032 7066
7033 7067 \SpecialChar ~
7034 7068 \SpecialChar ~
7035 7069 \SpecialChar ~
7036 7070 \SpecialChar ~
7037 7071 \SpecialChar ~
7038 7072 \SpecialChar ~
7039 7073 \SpecialChar ~
7040 7074 \SpecialChar ~
7041 7075 \SpecialChar ~
7042 7076 \SpecialChar ~
7043 7077 \SpecialChar ~
7044 7078 \SpecialChar ~
7045 7079 \SpecialChar ~
7046 7080 \SpecialChar ~
7047 7081 <10> ['scopes.py', 'strings.py']
7048 7082 \layout Standard
7049 7083
7050 7084 alist is now a normal python list you can loop over.
7051 7085 Using
7052 7086 \family typewriter
7053 7087 $
7054 7088 \family default
7055 7089 will expand back the python values when alias calls are made:
7056 7090 \layout Standard
7057 7091
7058 7092
7059 7093 \family typewriter
7060 7094 fperez[~/test]|11> for f in alist:
7061 7095 \newline
7062 7096
7063 7097 \begin_inset ERT
7064 7098 status Collapsed
7065 7099
7066 7100 \layout Standard
7067 7101
7068 7102 \backslash
7069 7103 hspace*{0mm}
7070 7104 \end_inset
7071 7105
7072 7106 \SpecialChar ~
7073 7107 \SpecialChar ~
7074 7108 \SpecialChar ~
7075 7109 \SpecialChar ~
7076 7110 \SpecialChar ~
7077 7111 \SpecialChar ~
7078 7112 \SpecialChar ~
7079 7113 \SpecialChar ~
7080 7114 \SpecialChar ~
7081 7115 \SpecialChar ~
7082 7116 \SpecialChar ~
7083 7117 \SpecialChar ~
7084 7118 \SpecialChar ~
7085 7119 \SpecialChar ~
7086 7120 |..> \SpecialChar ~
7087 7121 \SpecialChar ~
7088 7122 \SpecialChar ~
7089 7123 \SpecialChar ~
7090 7124 print 'file',f,
7091 7125 \newline
7092 7126
7093 7127 \begin_inset ERT
7094 7128 status Collapsed
7095 7129
7096 7130 \layout Standard
7097 7131
7098 7132 \backslash
7099 7133 hspace*{0mm}
7100 7134 \end_inset
7101 7135
7102 7136 \SpecialChar ~
7103 7137 \SpecialChar ~
7104 7138 \SpecialChar ~
7105 7139 \SpecialChar ~
7106 7140 \SpecialChar ~
7107 7141 \SpecialChar ~
7108 7142 \SpecialChar ~
7109 7143 \SpecialChar ~
7110 7144 \SpecialChar ~
7111 7145 \SpecialChar ~
7112 7146 \SpecialChar ~
7113 7147 \SpecialChar ~
7114 7148 \SpecialChar ~
7115 7149 \SpecialChar ~
7116 7150 |..> \SpecialChar ~
7117 7151 \SpecialChar ~
7118 7152 \SpecialChar ~
7119 7153 \SpecialChar ~
7120 7154 wc -l $f
7121 7155 \newline
7122 7156
7123 7157 \begin_inset ERT
7124 7158 status Collapsed
7125 7159
7126 7160 \layout Standard
7127 7161
7128 7162 \backslash
7129 7163 hspace*{0mm}
7130 7164 \end_inset
7131 7165
7132 7166 \SpecialChar ~
7133 7167 \SpecialChar ~
7134 7168 \SpecialChar ~
7135 7169 \SpecialChar ~
7136 7170 \SpecialChar ~
7137 7171 \SpecialChar ~
7138 7172 \SpecialChar ~
7139 7173 \SpecialChar ~
7140 7174 \SpecialChar ~
7141 7175 \SpecialChar ~
7142 7176 \SpecialChar ~
7143 7177 \SpecialChar ~
7144 7178 \SpecialChar ~
7145 7179 \SpecialChar ~
7146 7180 |..>
7147 7181 \newline
7148 7182 file scopes.py 13 scopes.py
7149 7183 \newline
7150 7184 file strings.py 4 strings.py
7151 7185 \layout Standard
7152 7186
7153 7187 Note that you may need to protect your variables with braces if you want
7154 7188 to append strings to their names.
7155 7189 To copy all files in alist to
7156 7190 \family typewriter
7157 7191 .bak
7158 7192 \family default
7159 7193 extensions, you must use:
7160 7194 \layout Standard
7161 7195
7162 7196
7163 7197 \family typewriter
7164 7198 fperez[~/test]|12> for f in alist:
7165 7199 \newline
7166 7200
7167 7201 \begin_inset ERT
7168 7202 status Collapsed
7169 7203
7170 7204 \layout Standard
7171 7205
7172 7206 \backslash
7173 7207 hspace*{0mm}
7174 7208 \end_inset
7175 7209
7176 7210 \SpecialChar ~
7177 7211 \SpecialChar ~
7178 7212 \SpecialChar ~
7179 7213 \SpecialChar ~
7180 7214 \SpecialChar ~
7181 7215 \SpecialChar ~
7182 7216 \SpecialChar ~
7183 7217 \SpecialChar ~
7184 7218 \SpecialChar ~
7185 7219 \SpecialChar ~
7186 7220 \SpecialChar ~
7187 7221 \SpecialChar ~
7188 7222 \SpecialChar ~
7189 7223 \SpecialChar ~
7190 7224 |..> \SpecialChar ~
7191 7225 \SpecialChar ~
7192 7226 \SpecialChar ~
7193 7227 \SpecialChar ~
7194 7228 cp $f ${f}.bak
7195 7229 \layout Standard
7196 7230
7197 7231 If you try using
7198 7232 \family typewriter
7199 7233 $f.bak
7200 7234 \family default
7201 7235 , you'll get an AttributeError exception saying that your string object
7202 7236 doesn't have a
7203 7237 \family typewriter
7204 7238 .bak
7205 7239 \family default
7206 7240 attribute.
7207 7241 This is because the
7208 7242 \family typewriter
7209 7243 $
7210 7244 \family default
7211 7245 expansion mechanism allows you to expand full Python expressions:
7212 7246 \layout Standard
7213 7247
7214 7248
7215 7249 \family typewriter
7216 7250 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
7217 7251 \newline
7218 7252 sys.platform is: linux2
7219 7253 \layout Standard
7220 7254
7221 7255 IPython's input history handling is still active, which allows you to rerun
7222 7256 a single block of multi-line input by simply using exec:
7223 7257 \newline
7224 7258
7225 7259 \family typewriter
7226 7260 fperez[~/test]|14> $$alist = ls *.eps
7227 7261 \newline
7228 7262 fperez[~/test]|15> exec _i11
7229 7263 \newline
7230 7264 file image2.eps 921 image2.eps
7231 7265 \newline
7232 7266 file image.eps 921 image.eps
7233 7267 \layout Standard
7234 7268
7235 7269 While these are new special-case syntaxes, they are designed to allow very
7236 7270 efficient use of the shell with minimal typing.
7237 7271 At an interactive shell prompt, conciseness of expression wins over readability.
7238 7272 \layout Subsection
7239 7273
7240 7274 Useful functions and modules
7241 7275 \layout Standard
7242 7276
7243 7277 The os, sys and shutil modules from the Python standard library are automaticall
7244 7278 y loaded.
7245 7279 Some additional functions, useful for shell usage, are listed below.
7246 7280 You can request more help about them with `
7247 7281 \family typewriter
7248 7282 ?
7249 7283 \family default
7250 7284 '.
7251 7285 \layout Description
7252 7286
7253 7287
7254 7288 \family typewriter
7255 7289 shell
7256 7290 \family default
7257 7291 - execute a command in the underlying system shell
7258 7292 \layout Description
7259 7293
7260 7294
7261 7295 \family typewriter
7262 7296 system
7263 7297 \family default
7264 7298 - like
7265 7299 \family typewriter
7266 7300 shell()
7267 7301 \family default
7268 7302 , but return the exit status of the command
7269 7303 \layout Description
7270 7304
7271 7305
7272 7306 \family typewriter
7273 7307 sout
7274 7308 \family default
7275 7309 - capture the output of a command as a string
7276 7310 \layout Description
7277 7311
7278 7312
7279 7313 \family typewriter
7280 7314 lout
7281 7315 \family default
7282 7316 - capture the output of a command as a list (split on `
7283 7317 \backslash
7284 7318 n')
7285 7319 \layout Description
7286 7320
7287 7321
7288 7322 \family typewriter
7289 7323 getoutputerror
7290 7324 \family default
7291 7325 - capture (output,error) of a shell commandss
7292 7326 \layout Standard
7293 7327
7294 7328
7295 7329 \family typewriter
7296 7330 sout
7297 7331 \family default
7298 7332 /
7299 7333 \family typewriter
7300 7334 lout
7301 7335 \family default
7302 7336 are the functional equivalents of
7303 7337 \family typewriter
7304 7338 $
7305 7339 \family default
7306 7340 /
7307 7341 \family typewriter
7308 7342 $$
7309 7343 \family default
7310 7344 .
7311 7345 They are provided to allow you to capture system output in the middle of
7312 7346 true python code, function definitions, etc (where
7313 7347 \family typewriter
7314 7348 $
7315 7349 \family default
7316 7350 and
7317 7351 \family typewriter
7318 7352 $$
7319 7353 \family default
7320 7354 are invalid).
7321 7355 \layout Subsection
7322 7356
7323 7357 Directory management
7324 7358 \layout Standard
7325 7359
7326 7360 Since each command passed by pysh to the underlying system is executed in
7327 7361 a subshell which exits immediately, you can NOT use !cd to navigate the
7328 7362 filesystem.
7329 7363 \layout Standard
7330 7364
7331 7365 Pysh provides its own builtin
7332 7366 \family typewriter
7333 7367 `%cd
7334 7368 \family default
7335 7369 ' magic command to move in the filesystem (the
7336 7370 \family typewriter
7337 7371 %
7338 7372 \family default
7339 7373 is not required with automagic on).
7340 7374 It also maintains a list of visited directories (use
7341 7375 \family typewriter
7342 7376 %dhist
7343 7377 \family default
7344 7378 to see it) and allows direct switching to any of them.
7345 7379 Type
7346 7380 \family typewriter
7347 7381 `cd?
7348 7382 \family default
7349 7383 ' for more details.
7350 7384 \layout Standard
7351 7385
7352 7386
7353 7387 \family typewriter
7354 7388 %pushd
7355 7389 \family default
7356 7390 ,
7357 7391 \family typewriter
7358 7392 %popd
7359 7393 \family default
7360 7394 and
7361 7395 \family typewriter
7362 7396 %dirs
7363 7397 \family default
7364 7398 are provided for directory stack handling.
7365 7399 \layout Subsection
7366 7400
7367 7401 Prompt customization
7368 7402 \layout Standard
7369 7403
7370 7404 The supplied
7371 7405 \family typewriter
7372 7406 ipythonrc-pysh
7373 7407 \family default
7374 7408 profile comes with an example of a very colored and detailed prompt, mainly
7375 7409 to serve as an illustration.
7376 7410 The valid escape sequences, besides color names, are:
7377 7411 \layout Description
7378 7412
7379 7413
7380 7414 \backslash
7381 7415 # - Prompt number.
7382 7416 \layout Description
7383 7417
7384 7418
7385 7419 \backslash
7386 7420 D - Dots, as many as there are digits in
7387 7421 \backslash
7388 7422 # (so they align).
7389 7423 \layout Description
7390 7424
7391 7425
7392 7426 \backslash
7393 7427 w - Current working directory (cwd).
7394 7428 \layout Description
7395 7429
7396 7430
7397 7431 \backslash
7398 7432 W - Basename of current working directory.
7399 7433 \layout Description
7400 7434
7401 7435
7402 7436 \backslash
7403 7437 X
7404 7438 \emph on
7405 7439 N
7406 7440 \emph default
7407 7441 - Where
7408 7442 \emph on
7409 7443 N
7410 7444 \emph default
7411 7445 =0..5.
7412 7446 N terms of the cwd, with $HOME written as ~.
7413 7447 \layout Description
7414 7448
7415 7449
7416 7450 \backslash
7417 7451 Y
7418 7452 \emph on
7419 7453 N
7420 7454 \emph default
7421 7455 - Where
7422 7456 \emph on
7423 7457 N
7424 7458 \emph default
7425 7459 =0..5.
7426 7460 Like X
7427 7461 \emph on
7428 7462 N
7429 7463 \emph default
7430 7464 , but if ~ is term
7431 7465 \emph on
7432 7466 N
7433 7467 \emph default
7434 7468 +1 it's also shown.
7435 7469 \layout Description
7436 7470
7437 7471
7438 7472 \backslash
7439 7473 u - Username.
7440 7474 \layout Description
7441 7475
7442 7476
7443 7477 \backslash
7444 7478 H - Full hostname.
7445 7479 \layout Description
7446 7480
7447 7481
7448 7482 \backslash
7449 7483 h - Hostname up to first '.'
7450 7484 \layout Description
7451 7485
7452 7486
7453 7487 \backslash
7454 7488 $ - Root symbol ($ or #).
7455 7489
7456 7490 \layout Description
7457 7491
7458 7492
7459 7493 \backslash
7460 7494 t - Current time, in H:M:S format.
7461 7495 \layout Description
7462 7496
7463 7497
7464 7498 \backslash
7465 7499 v - IPython release version.
7466 7500
7467 7501 \layout Description
7468 7502
7469 7503
7470 7504 \backslash
7471 7505 n - Newline.
7472 7506
7473 7507 \layout Description
7474 7508
7475 7509
7476 7510 \backslash
7477 7511 r - Carriage return.
7478 7512
7479 7513 \layout Description
7480 7514
7481 7515
7482 7516 \backslash
7483 7517
7484 7518 \backslash
7485 7519 - An explicitly escaped '
7486 7520 \backslash
7487 7521 '.
7488 7522 \layout Standard
7489 7523
7490 7524 You can configure your prompt colors using any ANSI color escape.
7491 7525 Each color escape sets the color for any subsequent text, until another
7492 7526 escape comes in and changes things.
7493 7527 The valid color escapes are:
7494 7528 \layout Description
7495 7529
7496 7530
7497 7531 \backslash
7498 7532 C_Black
7499 7533 \layout Description
7500 7534
7501 7535
7502 7536 \backslash
7503 7537 C_Blue
7504 7538 \layout Description
7505 7539
7506 7540
7507 7541 \backslash
7508 7542 C_Brown
7509 7543 \layout Description
7510 7544
7511 7545
7512 7546 \backslash
7513 7547 C_Cyan
7514 7548 \layout Description
7515 7549
7516 7550
7517 7551 \backslash
7518 7552 C_DarkGray
7519 7553 \layout Description
7520 7554
7521 7555
7522 7556 \backslash
7523 7557 C_Green
7524 7558 \layout Description
7525 7559
7526 7560
7527 7561 \backslash
7528 7562 C_LightBlue
7529 7563 \layout Description
7530 7564
7531 7565
7532 7566 \backslash
7533 7567 C_LightCyan
7534 7568 \layout Description
7535 7569
7536 7570
7537 7571 \backslash
7538 7572 C_LightGray
7539 7573 \layout Description
7540 7574
7541 7575
7542 7576 \backslash
7543 7577 C_LightGreen
7544 7578 \layout Description
7545 7579
7546 7580
7547 7581 \backslash
7548 7582 C_LightPurple
7549 7583 \layout Description
7550 7584
7551 7585
7552 7586 \backslash
7553 7587 C_LightRed
7554 7588 \layout Description
7555 7589
7556 7590
7557 7591 \backslash
7558 7592 C_Purple
7559 7593 \layout Description
7560 7594
7561 7595
7562 7596 \backslash
7563 7597 C_Red
7564 7598 \layout Description
7565 7599
7566 7600
7567 7601 \backslash
7568 7602 C_White
7569 7603 \layout Description
7570 7604
7571 7605
7572 7606 \backslash
7573 7607 C_Yellow
7574 7608 \layout Description
7575 7609
7576 7610
7577 7611 \backslash
7578 7612 C_Normal Stop coloring, defaults to your terminal settings.
7579 7613 \layout Section
7580 7614
7581 7615
7582 7616 \begin_inset LatexCommand \label{sec:Threading-support}
7583 7617
7584 7618 \end_inset
7585 7619
7586 7620 Threading support
7587 7621 \layout Standard
7588 7622
7589 7623
7590 7624 \series bold
7591 7625 WARNING:
7592 7626 \series default
7593 7627 The threading support is still somewhat experimental, and it has only seen
7594 7628 reasonable testing under Linux.
7595 7629 Threaded code is particularly tricky to debug, and it tends to show extremely
7596 7630 platform-dependent behavior.
7597 7631 Since I only have access to Linux machines, I will have to rely on user's
7598 7632 experiences and assistance for this area of IPython to improve under other
7599 7633 platforms.
7600 7634 \layout Standard
7601 7635
7602 7636 IPython, via the
7603 7637 \family typewriter
7604 7638 -gthread
7605 7639 \family default
7606 7640 ,
7607 7641 \family typewriter
7608 7642 -qthread
7609 7643 \family default
7610 7644 and
7611 7645 \family typewriter
7612 7646 -wthread
7613 7647 \family default
7614 7648 options (described in Sec.\SpecialChar ~
7615 7649
7616 7650 \begin_inset LatexCommand \ref{sec:threading-opts}
7617 7651
7618 7652 \end_inset
7619 7653
7620 7654 ), can run in multithreaded mode to support pyGTK, Qt and WXPython applications
7621 7655 respectively.
7622 7656 These GUI toolkits need to control the python main loop of execution, so
7623 7657 under a normal Python interpreter, starting a pyGTK, Qt or WXPython application
7624 7658 will immediately freeze the shell.
7625 7659
7626 7660 \layout Standard
7627 7661
7628 7662 IPython, with one of these options (you can only use one at a time), separates
7629 7663 the graphical loop and IPython's code execution run into different threads.
7630 7664 This allows you to test interactively (with
7631 7665 \family typewriter
7632 7666 %run
7633 7667 \family default
7634 7668 , for example) your GUI code without blocking.
7635 7669 \layout Standard
7636 7670
7637 7671 A nice mini-tutorial on using IPython along with the Qt Designer application
7638 7672 is available at the SciPy wiki:
7639 7673 \begin_inset LatexCommand \htmlurl{http://www.scipy.org/wikis/topical_software/QtWithIPythonAndDesigner}
7640 7674
7641 7675 \end_inset
7642 7676
7643 7677 .
7644 7678 \layout Subsection
7645 7679
7646 7680 Tk issues
7647 7681 \layout Standard
7648 7682
7649 7683 As indicated in Sec.\SpecialChar ~
7650 7684
7651 7685 \begin_inset LatexCommand \ref{sec:threading-opts}
7652 7686
7653 7687 \end_inset
7654 7688
7655 7689 , a special
7656 7690 \family typewriter
7657 7691 -tk
7658 7692 \family default
7659 7693 option is provided to try and allow Tk graphical applications to coexist
7660 7694 interactively with WX, Qt or GTK ones.
7661 7695 Whether this works at all, however, is very platform and configuration
7662 7696 dependent.
7663 7697 Please experiment with simple test cases before committing to using this
7664 7698 combination of Tk and GTK/Qt/WX threading in a production environment.
7665 7699 \layout Subsection
7666 7700
7667 7701 Signals and Threads
7668 7702 \layout Standard
7669 7703
7670 7704 When any of the thread systems (GTK, Qt or WX) are active, either directly
7671 7705 or via
7672 7706 \family typewriter
7673 7707 -pylab
7674 7708 \family default
7675 7709 with a threaded backend, it is impossible to interrupt long-running Python
7676 7710 code via
7677 7711 \family typewriter
7678 7712 Ctrl-C
7679 7713 \family default
7680 7714 .
7681 7715 IPython can not pass the KeyboardInterrupt exception (or the underlying
7682 7716
7683 7717 \family typewriter
7684 7718 SIGINT
7685 7719 \family default
7686 7720 ) across threads, so any long-running process started from IPython will
7687 7721 run to completion, or will have to be killed via an external (OS-based)
7688 7722 mechanism.
7689 7723 \layout Standard
7690 7724
7691 7725 To the best of my knowledge, this limitation is imposed by the Python interprete
7692 7726 r itself, and it comes from the difficulty of writing portable signal/threaded
7693 7727 code.
7694 7728 If any user is an expert on this topic and can suggest a better solution,
7695 7729 I would love to hear about it.
7696 7730 In the IPython sources, look at the
7697 7731 \family typewriter
7698 7732 Shell.py
7699 7733 \family default
7700 7734 module, and in particular at the
7701 7735 \family typewriter
7702 7736 runcode()
7703 7737 \family default
7704 7738 method.
7705 7739
7706 7740 \layout Subsection
7707 7741
7708 7742 I/O pitfalls
7709 7743 \layout Standard
7710 7744
7711 7745 Be mindful that the Python interpreter switches between threads every
7712 7746 \begin_inset Formula $N$
7713 7747 \end_inset
7714 7748
7715 7749 bytecodes, where the default value as of Python\SpecialChar ~
7716 7750 2.3 is
7717 7751 \begin_inset Formula $N=100.$
7718 7752 \end_inset
7719 7753
7720 7754 This value can be read by using the
7721 7755 \family typewriter
7722 7756 sys.getcheckinterval()
7723 7757 \family default
7724 7758 function, and it can be reset via
7725 7759 \family typewriter
7726 7760 sys.setcheckinterval(
7727 7761 \emph on
7728 7762 N
7729 7763 \emph default
7730 7764 )
7731 7765 \family default
7732 7766 .
7733 7767 This switching of threads can cause subtly confusing effects if one of
7734 7768 your threads is doing file I/O.
7735 7769 In text mode, most systems only flush file buffers when they encounter
7736 7770 a
7737 7771 \family typewriter
7738 7772 `
7739 7773 \backslash
7740 7774 n'
7741 7775 \family default
7742 7776 .
7743 7777 An instruction as simple as
7744 7778 \family typewriter
7745 7779
7746 7780 \newline
7747 7781 \SpecialChar ~
7748 7782 \SpecialChar ~
7749 7783 print >> filehandle,
7750 7784 \begin_inset Quotes eld
7751 7785 \end_inset
7752 7786
7753 7787 hello world
7754 7788 \begin_inset Quotes erd
7755 7789 \end_inset
7756 7790
7757 7791
7758 7792 \family default
7759 7793
7760 7794 \newline
7761 7795 actually consists of several bytecodes, so it is possible that the newline
7762 7796 does not reach your file before the next thread switch.
7763 7797 Similarly, if you are writing to a file in binary mode, the file won't
7764 7798 be flushed until the buffer fills, and your other thread may see apparently
7765 7799 truncated files.
7766 7800
7767 7801 \layout Standard
7768 7802
7769 7803 For this reason, if you are using IPython's thread support and have (for
7770 7804 example) a GUI application which will read data generated by files written
7771 7805 to from the IPython thread, the safest approach is to open all of your
7772 7806 files in unbuffered mode (the third argument to the
7773 7807 \family typewriter
7774 7808 file/open
7775 7809 \family default
7776 7810 function is the buffering value):
7777 7811 \newline
7778 7812
7779 7813 \family typewriter
7780 7814 \SpecialChar ~
7781 7815 \SpecialChar ~
7782 7816 filehandle = open(filename,mode,0)
7783 7817 \layout Standard
7784 7818
7785 7819 This is obviously a brute force way of avoiding race conditions with the
7786 7820 file buffering.
7787 7821 If you want to do it cleanly, and you have a resource which is being shared
7788 7822 by the interactive IPython loop and your GUI thread, you should really
7789 7823 handle it with thread locking and syncrhonization properties.
7790 7824 The Python documentation discusses these.
7791 7825 \layout Section
7792 7826
7793 7827
7794 7828 \begin_inset LatexCommand \label{sec:interactive-demos}
7795 7829
7796 7830 \end_inset
7797 7831
7798 7832 Interactive demos with IPython
7799 7833 \layout Standard
7800 7834
7801 7835 IPython ships with a basic system for running scripts interactively in sections,
7802 7836 useful when presenting code to audiences.
7803 7837 A few tags embedded in comments (so that the script remains valid Python
7804 7838 code) divide a file into separate blocks, and the demo can be run one block
7805 7839 at a time, with IPython printing (with syntax highlighting) the block before
7806 7840 executing it, and returning to the interactive prompt after each block.
7807 7841 The interactive namespace is updated after each block is run with the contents
7808 7842 of the demo's namespace.
7809 7843 \layout Standard
7810 7844
7811 7845 This allows you to show a piece of code, run it and then execute interactively
7812 7846 commands based on the variables just created.
7813 7847 Once you want to continue, you simply execute the next block of the demo.
7814 7848 The following listing shows the markup necessary for dividing a script
7815 7849 into sections for execution as a demo.
7816 7850 \layout Standard
7817 7851
7818 7852
7819 7853 \begin_inset ERT
7820 7854 status Open
7821 7855
7822 7856 \layout Standard
7823 7857
7824 7858 \backslash
7825 7859 codelist{examples/example-demo.py}
7826 7860 \end_inset
7827 7861
7828 7862
7829 7863 \layout Standard
7830 7864
7831 7865 In order to run a file as a demo, you must first make a
7832 7866 \family typewriter
7833 7867 Demo
7834 7868 \family default
7835 7869 object out of it.
7836 7870 If the file is named
7837 7871 \family typewriter
7838 7872 myscript.py
7839 7873 \family default
7840 7874 , the following code will make a demo:
7841 7875 \layout LyX-Code
7842 7876
7843 7877 from IPython.demo import Demo
7844 7878 \layout LyX-Code
7845 7879
7846 7880 mydemo = Demo('myscript.py')
7847 7881 \layout Standard
7848 7882
7849 7883 This creates the
7850 7884 \family typewriter
7851 7885 mydemo
7852 7886 \family default
7853 7887 object, whose blocks you run one at a time by simply calling the object
7854 7888 with no arguments.
7855 7889 If you have autocall active in IPython (the default), all you need to do
7856 7890 is type
7857 7891 \layout LyX-Code
7858 7892
7859 7893 mydemo
7860 7894 \layout Standard
7861 7895
7862 7896 and IPython will call it, executing each block.
7863 7897 Demo objects can be restarted, you can move forward or back skipping blocks,
7864 7898 re-execute the last block, etc.
7865 7899 Simply use the Tab key on a demo object to see its methods, and call
7866 7900 \family typewriter
7867 7901 `?'
7868 7902 \family default
7869 7903 on them to see their docstrings for more usage details.
7870 7904 In addition, the
7871 7905 \family typewriter
7872 7906 demo
7873 7907 \family default
7874 7908 module itself contains a comprehensive docstring, which you can access
7875 7909 via
7876 7910 \layout LyX-Code
7877 7911
7878 7912 from IPython import demo
7879 7913 \layout LyX-Code
7880 7914
7881 7915 demo?
7882 7916 \layout Standard
7883 7917
7884 7918
7885 7919 \series bold
7886 7920 Limitations:
7887 7921 \series default
7888 7922 It is important to note that these demos are limited to fairly simple uses.
7889 7923 In particular, you can
7890 7924 \emph on
7891 7925 not
7892 7926 \emph default
7893 7927 put division marks in indented code (loops, if statements, function definitions
7894 7928 , etc.) Supporting something like this would basically require tracking the
7895 7929 internal execution state of the Python interpreter, so only top-level divisions
7896 7930 are allowed.
7897 7931 If you want to be able to open an IPython instance at an arbitrary point
7898 7932 in a program, you can use IPython's embedding facilities, described in
7899 7933 detail in Sec\SpecialChar \@.
7900 7934 \SpecialChar ~
7901 7935
7902 7936 \begin_inset LatexCommand \ref{sec:embed}
7903 7937
7904 7938 \end_inset
7905 7939
7906 7940 .
7907 7941 \layout Section
7908 7942
7909 7943
7910 7944 \begin_inset LatexCommand \label{sec:matplotlib-support}
7911 7945
7912 7946 \end_inset
7913 7947
7914 7948 Plotting with
7915 7949 \family typewriter
7916 7950 matplotlib
7917 7951 \family default
7918 7952
7919 7953 \layout Standard
7920 7954
7921 7955 The matplotlib library (
7922 7956 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
7923 7957
7924 7958 \end_inset
7925 7959
7926 7960 ) provides high quality 2D plotting for Python.
7927 7961 Matplotlib can produce plots on screen using a variety of GUI toolkits,
7928 7962 including Tk, GTK and WXPython.
7929 7963 It also provides a number of commands useful for scientific computing,
7930 7964 all with a syntax compatible with that of the popular Matlab program.
7931 7965 \layout Standard
7932 7966
7933 7967 IPython accepts the special option
7934 7968 \family typewriter
7935 7969 -pylab
7936 7970 \family default
7937 7971 (Sec.\SpecialChar ~
7938 7972
7939 7973 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
7940 7974
7941 7975 \end_inset
7942 7976
7943 7977 ).
7944 7978 This configures it to support matplotlib, honoring the settings in the
7945 7979
7946 7980 \family typewriter
7947 7981 .matplotlibrc
7948 7982 \family default
7949 7983 file.
7950 7984 IPython will detect the user's choice of matplotlib GUI backend, and automatica
7951 7985 lly select the proper threading model to prevent blocking.
7952 7986 It also sets matplotlib in interactive mode and modifies
7953 7987 \family typewriter
7954 7988 %run
7955 7989 \family default
7956 7990 slightly, so that any matplotlib-based script can be executed using
7957 7991 \family typewriter
7958 7992 %run
7959 7993 \family default
7960 7994 and the final
7961 7995 \family typewriter
7962 7996 show()
7963 7997 \family default
7964 7998 command does not block the interactive shell.
7965 7999 \layout Standard
7966 8000
7967 8001 The
7968 8002 \family typewriter
7969 8003 -pylab
7970 8004 \family default
7971 8005 option must be given first in order for IPython to configure its threading
7972 8006 mode.
7973 8007 However, you can still issue other options afterwards.
7974 8008 This allows you to have a matplotlib-based environment customized with
7975 8009 additional modules using the standard IPython profile mechanism (Sec.\SpecialChar ~
7976 8010
7977 8011 \begin_inset LatexCommand \ref{sec:profiles}
7978 8012
7979 8013 \end_inset
7980 8014
7981 8015 ): ``
7982 8016 \family typewriter
7983 8017 ipython -pylab -p myprofile
7984 8018 \family default
7985 8019 '' will load the profile defined in
7986 8020 \family typewriter
7987 8021 ipythonrc-myprofile
7988 8022 \family default
7989 8023 after configuring matplotlib.
7990 8024 \layout Section
7991 8025
7992 8026
7993 8027 \begin_inset LatexCommand \label{sec:Gnuplot}
7994 8028
7995 8029 \end_inset
7996 8030
7997 8031 Plotting with
7998 8032 \family typewriter
7999 8033 Gnuplot
8000 8034 \layout Standard
8001 8035
8002 8036 Through the magic extension system described in sec.
8003 8037
8004 8038 \begin_inset LatexCommand \ref{sec:magic}
8005 8039
8006 8040 \end_inset
8007 8041
8008 8042 , IPython incorporates a mechanism for conveniently interfacing with the
8009 8043 Gnuplot system (
8010 8044 \begin_inset LatexCommand \htmlurl{http://www.gnuplot.info}
8011 8045
8012 8046 \end_inset
8013 8047
8014 8048 ).
8015 8049 Gnuplot is a very complete 2D and 3D plotting package available for many
8016 8050 operating systems and commonly included in modern Linux distributions.
8017 8051
8018 8052 \layout Standard
8019 8053
8020 8054 Besides having Gnuplot installed, this functionality requires the
8021 8055 \family typewriter
8022 8056 Gnuplot.py
8023 8057 \family default
8024 8058 module for interfacing python with Gnuplot.
8025 8059 It can be downloaded from:
8026 8060 \begin_inset LatexCommand \htmlurl{http://gnuplot-py.sourceforge.net}
8027 8061
8028 8062 \end_inset
8029 8063
8030 8064 .
8031 8065 \layout Subsection
8032 8066
8033 8067 Proper Gnuplot configuration
8034 8068 \layout Standard
8035 8069
8036 8070 As of version 4.0, Gnuplot has excellent mouse and interactive keyboard support.
8037 8071 However, as of
8038 8072 \family typewriter
8039 8073 Gnuplot.py
8040 8074 \family default
8041 8075 version 1.7, a new option was added to communicate between Python and Gnuplot
8042 8076 via FIFOs (pipes).
8043 8077 This mechanism, while fast, also breaks the mouse system.
8044 8078 You must therefore set the variable
8045 8079 \family typewriter
8046 8080 prefer_fifo_data
8047 8081 \family default
8048 8082 to
8049 8083 \family typewriter
8050 8084 0
8051 8085 \family default
8052 8086 in file
8053 8087 \family typewriter
8054 8088 gp_unix.py
8055 8089 \family default
8056 8090 if you wish to keep the interactive mouse and keyboard features working
8057 8091 properly (
8058 8092 \family typewriter
8059 8093 prefer_inline_data
8060 8094 \family default
8061 8095 also must be
8062 8096 \family typewriter
8063 8097 0
8064 8098 \family default
8065 8099 , but this is the default so unless you've changed it manually you should
8066 8100 be fine).
8067 8101 \layout Standard
8068 8102
8069 8103 'Out of the box', Gnuplot is configured with a rather poor set of size,
8070 8104 color and linewidth choices which make the graphs fairly hard to read on
8071 8105 modern high-resolution displays (although they work fine on old 640x480
8072 8106 ones).
8073 8107 Below is a section of my
8074 8108 \family typewriter
8075 8109 .Xdefaults
8076 8110 \family default
8077 8111 file which I use for having a more convenient Gnuplot setup.
8078 8112 Remember to load it by running
8079 8113 \family typewriter
8080 8114 `xrdb .Xdefaults`
8081 8115 \family default
8082 8116 :
8083 8117 \layout Standard
8084 8118
8085 8119
8086 8120 \family typewriter
8087 8121 !******************************************************************
8088 8122 \newline
8089 8123 ! gnuplot options
8090 8124 \newline
8091 8125 ! modify this for a convenient window size
8092 8126 \newline
8093 8127 gnuplot*geometry: 780x580
8094 8128 \layout Standard
8095 8129
8096 8130
8097 8131 \family typewriter
8098 8132 ! on-screen font (not for PostScript)
8099 8133 \newline
8100 8134 gnuplot*font: -misc-fixed-bold-r-normal--15-120-100-100-c-90-iso8859-1
8101 8135 \layout Standard
8102 8136
8103 8137
8104 8138 \family typewriter
8105 8139 ! color options
8106 8140 \newline
8107 8141 gnuplot*background: black
8108 8142 \newline
8109 8143 gnuplot*textColor: white
8110 8144 \newline
8111 8145 gnuplot*borderColor: white
8112 8146 \newline
8113 8147 gnuplot*axisColor: white
8114 8148 \newline
8115 8149 gnuplot*line1Color: red
8116 8150 \newline
8117 8151 gnuplot*line2Color: green
8118 8152 \newline
8119 8153 gnuplot*line3Color: blue
8120 8154 \newline
8121 8155 gnuplot*line4Color: magenta
8122 8156 \newline
8123 8157 gnuplot*line5Color: cyan
8124 8158 \newline
8125 8159 gnuplot*line6Color: sienna
8126 8160 \newline
8127 8161 gnuplot*line7Color: orange
8128 8162 \newline
8129 8163 gnuplot*line8Color: coral
8130 8164 \layout Standard
8131 8165
8132 8166
8133 8167 \family typewriter
8134 8168 ! multiplicative factor for point styles
8135 8169 \newline
8136 8170 gnuplot*pointsize: 2
8137 8171 \layout Standard
8138 8172
8139 8173
8140 8174 \family typewriter
8141 8175 ! line width options (in pixels)
8142 8176 \newline
8143 8177 gnuplot*borderWidth: 2
8144 8178 \newline
8145 8179 gnuplot*axisWidth: 2
8146 8180 \newline
8147 8181 gnuplot*line1Width: 2
8148 8182 \newline
8149 8183 gnuplot*line2Width: 2
8150 8184 \newline
8151 8185 gnuplot*line3Width: 2
8152 8186 \newline
8153 8187 gnuplot*line4Width: 2
8154 8188 \newline
8155 8189 gnuplot*line5Width: 2
8156 8190 \newline
8157 8191 gnuplot*line6Width: 2
8158 8192 \newline
8159 8193 gnuplot*line7Width: 2
8160 8194 \newline
8161 8195 gnuplot*line8Width: 2
8162 8196 \layout Subsection
8163 8197
8164 8198 The
8165 8199 \family typewriter
8166 8200 IPython.GnuplotRuntime
8167 8201 \family default
8168 8202 module
8169 8203 \layout Standard
8170 8204
8171 8205 IPython includes a module called
8172 8206 \family typewriter
8173 8207 Gnuplot2.py
8174 8208 \family default
8175 8209 which extends and improves the default
8176 8210 \family typewriter
8177 8211 Gnuplot
8178 8212 \family default
8179 8213 .
8180 8214 \family typewriter
8181 8215 py
8182 8216 \family default
8183 8217 (which it still relies upon).
8184 8218 For example, the new
8185 8219 \family typewriter
8186 8220 plot
8187 8221 \family default
8188 8222 function adds several improvements to the original making it more convenient
8189 8223 for interactive use, and
8190 8224 \family typewriter
8191 8225 hardcopy
8192 8226 \family default
8193 8227 fixes a bug in the original which under some circumstances blocks the creation
8194 8228 of PostScript output.
8195 8229 \layout Standard
8196 8230
8197 8231 For scripting use,
8198 8232 \family typewriter
8199 8233 GnuplotRuntime.py
8200 8234 \family default
8201 8235 is provided, which wraps
8202 8236 \family typewriter
8203 8237 Gnuplot2.py
8204 8238 \family default
8205 8239 and creates a series of global aliases.
8206 8240 These make it easy to control Gnuplot plotting jobs through the Python
8207 8241 language.
8208 8242 \layout Standard
8209 8243
8210 8244 Below is some example code which illustrates how to configure Gnuplot inside
8211 8245 your own programs but have it available for further interactive use through
8212 8246 an embedded IPython instance.
8213 8247 Simply run this file at a system prompt.
8214 8248 This file is provided as
8215 8249 \family typewriter
8216 8250 example-gnuplot.py
8217 8251 \family default
8218 8252 in the examples directory:
8219 8253 \layout Standard
8220 8254
8221 8255
8222 8256 \begin_inset ERT
8223 8257 status Open
8224 8258
8225 8259 \layout Standard
8226 8260
8227 8261 \backslash
8228 8262 codelist{examples/example-gnuplot.py}
8229 8263 \end_inset
8230 8264
8231 8265
8232 8266 \layout Subsection
8233 8267
8234 8268 The
8235 8269 \family typewriter
8236 8270 numeric
8237 8271 \family default
8238 8272 profile: a scientific computing environment
8239 8273 \layout Standard
8240 8274
8241 8275 The
8242 8276 \family typewriter
8243 8277 numeric
8244 8278 \family default
8245 8279 IPython profile, which you can activate with
8246 8280 \family typewriter
8247 8281 `ipython -p numeric
8248 8282 \family default
8249 8283 ' will automatically load the IPython Gnuplot extensions (plus Numeric and
8250 8284 other useful things for numerical computing), contained in the
8251 8285 \family typewriter
8252 8286 IPython.GnuplotInteractive
8253 8287 \family default
8254 8288 module.
8255 8289 This will create the globals
8256 8290 \family typewriter
8257 8291 Gnuplot
8258 8292 \family default
8259 8293 (an alias to the improved Gnuplot2 module),
8260 8294 \family typewriter
8261 8295 gp
8262 8296 \family default
8263 8297 (a Gnuplot active instance), the new magic commands
8264 8298 \family typewriter
8265 8299 %gpc
8266 8300 \family default
8267 8301 and
8268 8302 \family typewriter
8269 8303 %gp_set_instance
8270 8304 \family default
8271 8305 and several other convenient globals.
8272 8306 Type
8273 8307 \family typewriter
8274 8308 gphelp()
8275 8309 \family default
8276 8310 for further details.
8277 8311 \layout Standard
8278 8312
8279 8313 This should turn IPython into a convenient environment for numerical computing,
8280 8314 with all the functions in the NumPy library and the Gnuplot facilities
8281 8315 for plotting.
8282 8316 Further improvements can be obtained by loading the SciPy libraries for
8283 8317 scientific computing, available at
8284 8318 \begin_inset LatexCommand \htmlurl{http://scipy.org}
8285 8319
8286 8320 \end_inset
8287 8321
8288 8322 .
8289 8323 \layout Standard
8290 8324
8291 8325 If you are in the middle of a working session with numerical objects and
8292 8326 need to plot them but you didn't start the
8293 8327 \family typewriter
8294 8328 numeric
8295 8329 \family default
8296 8330 profile, you can load these extensions at any time by typing
8297 8331 \newline
8298 8332
8299 8333 \family typewriter
8300 8334 from IPython.GnuplotInteractive import *
8301 8335 \newline
8302 8336
8303 8337 \family default
8304 8338 at the IPython prompt.
8305 8339 This will allow you to keep your objects intact and start using Gnuplot
8306 8340 to view them.
8307 8341 \layout Section
8308 8342
8309 8343 Reporting bugs
8310 8344 \layout Subsection*
8311 8345
8312 8346 Automatic crash reports
8313 8347 \layout Standard
8314 8348
8315 8349 Ideally, IPython itself shouldn't crash.
8316 8350 It will catch exceptions produced by you, but bugs in its internals will
8317 8351 still crash it.
8318 8352 \layout Standard
8319 8353
8320 8354 In such a situation, IPython will leave a file named
8321 8355 \family typewriter
8322 8356 IPython_crash_report.txt
8323 8357 \family default
8324 8358 in your IPYTHONDIR directory (that way if crashes happen several times
8325 8359 it won't litter many directories, the post-mortem file is always located
8326 8360 in the same place and new occurrences just overwrite the previous one).
8327 8361 If you can mail this file to the developers (see sec.
8328 8362
8329 8363 \begin_inset LatexCommand \ref{sec:credits}
8330 8364
8331 8365 \end_inset
8332 8366
8333 8367 for names and addresses), it will help us
8334 8368 \emph on
8335 8369 a lot
8336 8370 \emph default
8337 8371 in understanding the cause of the problem and fixing it sooner.
8338 8372 \layout Subsection*
8339 8373
8340 8374 The bug tracker
8341 8375 \layout Standard
8342 8376
8343 8377 IPython also has an online bug-tracker, located at
8344 8378 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython}
8345 8379
8346 8380 \end_inset
8347 8381
8348 8382 .
8349 8383 In addition to mailing the developers, it would be a good idea to file
8350 8384 a bug report here.
8351 8385 This will ensure that the issue is properly followed to conclusion.
8352 8386 \layout Standard
8353 8387
8354 8388 You can also use this bug tracker to file feature requests.
8355 8389 \layout Section
8356 8390
8357 8391 Brief history
8358 8392 \layout Subsection
8359 8393
8360 8394 Origins
8361 8395 \layout Standard
8362 8396
8363 8397 The current IPython system grew out of the following three projects:
8364 8398 \layout List
8365 8399 \labelwidthstring 00.00.0000
8366 8400
8367 8401 ipython by Fernando Pérez.
8368 8402 I was working on adding Mathematica-type prompts and a flexible configuration
8369 8403 system (something better than
8370 8404 \family typewriter
8371 8405 $PYTHONSTARTUP
8372 8406 \family default
8373 8407 ) to the standard Python interactive interpreter.
8374 8408 \layout List
8375 8409 \labelwidthstring 00.00.0000
8376 8410
8377 8411 IPP by Janko Hauser.
8378 8412 Very well organized, great usability.
8379 8413 Had an old help system.
8380 8414 IPP was used as the `container' code into which I added the functionality
8381 8415 from ipython and LazyPython.
8382 8416 \layout List
8383 8417 \labelwidthstring 00.00.0000
8384 8418
8385 8419 LazyPython by Nathan Gray.
8386 8420 Simple but
8387 8421 \emph on
8388 8422 very
8389 8423 \emph default
8390 8424 powerful.
8391 8425 The quick syntax (auto parens, auto quotes) and verbose/colored tracebacks
8392 8426 were all taken from here.
8393 8427 \layout Standard
8394 8428
8395 8429 When I found out (see sec.
8396 8430
8397 8431 \begin_inset LatexCommand \ref{figgins}
8398 8432
8399 8433 \end_inset
8400 8434
8401 8435 ) about IPP and LazyPython I tried to join all three into a unified system.
8402 8436 I thought this could provide a very nice working environment, both for
8403 8437 regular programming and scientific computing: shell-like features, IDL/Matlab
8404 8438 numerics, Mathematica-type prompt history and great object introspection
8405 8439 and help facilities.
8406 8440 I think it worked reasonably well, though it was a lot more work than I
8407 8441 had initially planned.
8408 8442 \layout Subsection
8409 8443
8410 8444 Current status
8411 8445 \layout Standard
8412 8446
8413 8447 The above listed features work, and quite well for the most part.
8414 8448 But until a major internal restructuring is done (see below), only bug
8415 8449 fixing will be done, no other features will be added (unless very minor
8416 8450 and well localized in the cleaner parts of the code).
8417 8451 \layout Standard
8418 8452
8419 8453 IPython consists of some 12000 lines of pure python code, of which roughly
8420 8454 50% are fairly clean.
8421 8455 The other 50% are fragile, messy code which needs a massive restructuring
8422 8456 before any further major work is done.
8423 8457 Even the messy code is fairly well documented though, and most of the problems
8424 8458 in the (non-existent) class design are well pointed to by a PyChecker run.
8425 8459 So the rewriting work isn't that bad, it will just be time-consuming.
8426 8460 \layout Subsection
8427 8461
8428 8462 Future
8429 8463 \layout Standard
8430 8464
8431 8465 See the separate
8432 8466 \family typewriter
8433 8467 new_design
8434 8468 \family default
8435 8469 document for details.
8436 8470 Ultimately, I would like to see IPython become part of the standard Python
8437 8471 distribution as a `big brother with batteries' to the standard Python interacti
8438 8472 ve interpreter.
8439 8473 But that will never happen with the current state of the code, so all contribut
8440 8474 ions are welcome.
8441 8475 \layout Section
8442 8476
8443 8477 License
8444 8478 \layout Standard
8445 8479
8446 8480 IPython is released under the terms of the BSD license, whose general form
8447 8481 can be found at:
8448 8482 \begin_inset LatexCommand \htmlurl{http://www.opensource.org/licenses/bsd-license.php}
8449 8483
8450 8484 \end_inset
8451 8485
8452 8486 .
8453 8487 The full text of the IPython license is reproduced below:
8454 8488 \layout Quote
8455 8489
8456 8490
8457 8491 \family typewriter
8458 8492 \size small
8459 8493 IPython is released under a BSD-type license.
8460 8494 \layout Quote
8461 8495
8462 8496
8463 8497 \family typewriter
8464 8498 \size small
8465 8499 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
8466 8500 \layout Quote
8467 8501
8468 8502
8469 8503 \family typewriter
8470 8504 \size small
8471 8505 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
8472 8506 \newline
8473 8507 Nathaniel Gray <n8gray@caltech.edu>.
8474 8508 \layout Quote
8475 8509
8476 8510
8477 8511 \family typewriter
8478 8512 \size small
8479 8513 All rights reserved.
8480 8514 \layout Quote
8481 8515
8482 8516
8483 8517 \family typewriter
8484 8518 \size small
8485 8519 Redistribution and use in source and binary forms, with or without modification,
8486 8520 are permitted provided that the following conditions are met:
8487 8521 \layout Quote
8488 8522
8489 8523
8490 8524 \family typewriter
8491 8525 \size small
8492 8526 a.
8493 8527 Redistributions of source code must retain the above copyright notice,
8494 8528 this list of conditions and the following disclaimer.
8495 8529 \layout Quote
8496 8530
8497 8531
8498 8532 \family typewriter
8499 8533 \size small
8500 8534 b.
8501 8535 Redistributions in binary form must reproduce the above copyright notice,
8502 8536 this list of conditions and the following disclaimer in the documentation
8503 8537 and/or other materials provided with the distribution.
8504 8538 \layout Quote
8505 8539
8506 8540
8507 8541 \family typewriter
8508 8542 \size small
8509 8543 c.
8510 8544 Neither the name of the copyright holders nor the names of any contributors
8511 8545 to this software may be used to endorse or promote products derived from
8512 8546 this software without specific prior written permission.
8513 8547 \layout Quote
8514 8548
8515 8549
8516 8550 \family typewriter
8517 8551 \size small
8518 8552 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8519 8553 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
8520 8554 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
8521 8555 PURPOSE ARE DISCLAIMED.
8522 8556 IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
8523 8557 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
8524 8558 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
8525 8559 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
8526 8560 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8527 8561 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8528 8562 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8529 8563
8530 8564 \layout Standard
8531 8565
8532 8566 Individual authors are the holders of the copyright for their code and are
8533 8567 listed in each file.
8534 8568 \layout Standard
8535 8569
8536 8570 Some files (
8537 8571 \family typewriter
8538 8572 DPyGetOpt.py
8539 8573 \family default
8540 8574 , for example) may be licensed under different conditions.
8541 8575 Ultimately each file indicates clearly the conditions under which its author/au
8542 8576 thors have decided to publish the code.
8543 8577 \layout Standard
8544 8578
8545 8579 Versions of IPython up to and including 0.6.3 were released under the GNU
8546 8580 Lesser General Public License (LGPL), available at
8547 8581 \begin_inset LatexCommand \htmlurl{http://www.gnu.org/copyleft/lesser.html}
8548 8582
8549 8583 \end_inset
8550 8584
8551 8585 .
8552 8586 \layout Section
8553 8587
8554 8588
8555 8589 \begin_inset LatexCommand \label{sec:credits}
8556 8590
8557 8591 \end_inset
8558 8592
8559 8593 Credits
8560 8594 \layout Standard
8561 8595
8562 8596 IPython is mainly developed by Fernando Pérez
8563 8597 \family typewriter
8564 8598 <fperez@colorado.edu>
8565 8599 \family default
8566 8600 , but the project was born from mixing in Fernando's code with the IPP project
8567 8601 by Janko Hauser
8568 8602 \family typewriter
8569 8603 <jhauser-AT-zscout.de>
8570 8604 \family default
8571 8605 and LazyPython by Nathan Gray
8572 8606 \family typewriter
8573 8607 <n8gray-AT-caltech.edu>
8574 8608 \family default
8575 8609 .
8576 8610 For all IPython-related requests, please contact Fernando.
8577 8611
8578 8612 \layout Standard
8579 8613
8580 8614 As of late 2005, the following developers have joined the core team:
8581 8615 \layout List
8582 8616 \labelwidthstring 00.00.0000
8583 8617
8584 8618 Robert\SpecialChar ~
8585 8619 Kern
8586 8620 \family typewriter
8587 8621 <rkern-AT-enthought.com>
8588 8622 \family default
8589 8623 : co-mentored the 2005 Google Summer of Code project to develop python interacti
8590 8624 ve notebooks (XML documents) and graphical interface.
8591 8625 This project was awarded to the students Tzanko Matev
8592 8626 \family typewriter
8593 8627 <tsanko-AT-gmail.com>
8594 8628 \family default
8595 8629 and Toni Alatalo
8596 8630 \family typewriter
8597 8631 <antont-AT-an.org>
8598 8632 \layout List
8599 8633 \labelwidthstring 00.00.0000
8600 8634
8601 8635 Brian\SpecialChar ~
8602 8636 Granger
8603 8637 \family typewriter
8604 8638 <bgranger-AT-scu.edu>
8605 8639 \family default
8606 8640 : extending IPython to allow support for interactive parallel computing.
8607 8641 \layout Standard
8608 8642
8609 8643 User or development help should be requested via the IPython mailing lists:
8610 8644 \layout Description
8611 8645
8612 8646 User\SpecialChar ~
8613 8647 list:
8614 8648 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-user}
8615 8649
8616 8650 \end_inset
8617 8651
8618 8652
8619 8653 \layout Description
8620 8654
8621 8655 Developer's\SpecialChar ~
8622 8656 list:
8623 8657 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-dev}
8624 8658
8625 8659 \end_inset
8626 8660
8627 8661
8628 8662 \layout Standard
8629 8663
8630 8664 The IPython project is also very grateful to
8631 8665 \begin_inset Foot
8632 8666 collapsed true
8633 8667
8634 8668 \layout Standard
8635 8669
8636 8670 I've mangled email addresses to reduce spam, since the IPython manuals can
8637 8671 be accessed online.
8638 8672 \end_inset
8639 8673
8640 8674 :
8641 8675 \layout Standard
8642 8676
8643 8677 Bill Bumgarner
8644 8678 \family typewriter
8645 8679 <bbum-AT-friday.com>
8646 8680 \family default
8647 8681 : for providing the DPyGetOpt module which gives very powerful and convenient
8648 8682 handling of command-line options (light years ahead of what Python 2.1.1's
8649 8683 getopt module does).
8650 8684 \layout Standard
8651 8685
8652 8686 Ka-Ping Yee
8653 8687 \family typewriter
8654 8688 <ping-AT-lfw.org>
8655 8689 \family default
8656 8690 : for providing the Itpl module for convenient and powerful string interpolation
8657 8691 with a much nicer syntax than formatting through the '%' operator.
8658 8692 \layout Standard
8659 8693
8660 8694 Arnd Bäcker
8661 8695 \family typewriter
8662 8696 <baecker-AT-physik.tu-dresden.de>
8663 8697 \family default
8664 8698 : for his many very useful suggestions and comments, and lots of help with
8665 8699 testing and documentation checking.
8666 8700 Many of IPython's newer features are a result of discussions with him (bugs
8667 8701 are still my fault, not his).
8668 8702 \layout Standard
8669 8703
8670 8704 Obviously Guido van\SpecialChar ~
8671 8705 Rossum and the whole Python development team, that goes
8672 8706 without saying.
8673 8707 \layout Standard
8674 8708
8675 8709 IPython's website is generously hosted at
8676 8710 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
8677 8711
8678 8712 \end_inset
8679 8713
8680 8714 by Enthought (
8681 8715 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
8682 8716
8683 8717 \end_inset
8684 8718
8685 8719 ).
8686 8720 I am very grateful to them and all of the SciPy team for their contribution.
8687 8721 \layout Standard
8688 8722
8689 8723
8690 8724 \begin_inset LatexCommand \label{figgins}
8691 8725
8692 8726 \end_inset
8693 8727
8694 8728 Fernando would also like to thank Stephen Figgins
8695 8729 \family typewriter
8696 8730 <fig-AT-monitor.net>
8697 8731 \family default
8698 8732 , an O'Reilly Python editor.
8699 8733 His Oct/11/2001 article about IPP and LazyPython, was what got this project
8700 8734 started.
8701 8735 You can read it at:
8702 8736 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html}
8703 8737
8704 8738 \end_inset
8705 8739
8706 8740 .
8707 8741 \layout Standard
8708 8742
8709 8743 And last but not least, all the kind IPython users who have emailed new
8710 8744 code, bug reports, fixes, comments and ideas.
8711 8745 A brief list follows, please let me know if I have ommitted your name by
8712 8746 accident:
8713 8747 \layout List
8714 8748 \labelwidthstring 00.00.0000
8715 8749
8716 8750 Jack\SpecialChar ~
8717 8751 Moffit
8718 8752 \family typewriter
8719 8753 <jack-AT-xiph.org>
8720 8754 \family default
8721 8755 Bug fixes, including the infamous color problem.
8722 8756 This bug alone caused many lost hours and frustration, many thanks to him
8723 8757 for the fix.
8724 8758 I've always been a fan of Ogg & friends, now I have one more reason to
8725 8759 like these folks.
8726 8760 \newline
8727 8761 Jack is also contributing with Debian packaging and many other things.
8728 8762 \layout List
8729 8763 \labelwidthstring 00.00.0000
8730 8764
8731 8765 Alexander\SpecialChar ~
8732 8766 Schmolck
8733 8767 \family typewriter
8734 8768 <a.schmolck-AT-gmx.net>
8735 8769 \family default
8736 8770 Emacs work, bug reports, bug fixes, ideas, lots more.
8737 8771 The ipython.el mode for (X)Emacs is Alex's code, providing full support
8738 8772 for IPython under (X)Emacs.
8739 8773 \layout List
8740 8774 \labelwidthstring 00.00.0000
8741 8775
8742 8776 Andrea\SpecialChar ~
8743 8777 Riciputi
8744 8778 \family typewriter
8745 8779 <andrea.riciputi-AT-libero.it>
8746 8780 \family default
8747 8781 Mac OSX information, Fink package management.
8748 8782 \layout List
8749 8783 \labelwidthstring 00.00.0000
8750 8784
8751 8785 Gary\SpecialChar ~
8752 8786 Bishop
8753 8787 \family typewriter
8754 8788 <gb-AT-cs.unc.edu>
8755 8789 \family default
8756 8790 Bug reports, and patches to work around the exception handling idiosyncracies
8757 8791 of WxPython.
8758 8792 Readline and color support for Windows.
8759 8793 \layout List
8760 8794 \labelwidthstring 00.00.0000
8761 8795
8762 8796 Jeffrey\SpecialChar ~
8763 8797 Collins
8764 8798 \family typewriter
8765 8799 <Jeff.Collins-AT-vexcel.com>
8766 8800 \family default
8767 8801 Bug reports.
8768 8802 Much improved readline support, including fixes for Python 2.3.
8769 8803 \layout List
8770 8804 \labelwidthstring 00.00.0000
8771 8805
8772 8806 Dryice\SpecialChar ~
8773 8807 Liu
8774 8808 \family typewriter
8775 8809 <dryice-AT-liu.com.cn>
8776 8810 \family default
8777 8811 FreeBSD port.
8778 8812 \layout List
8779 8813 \labelwidthstring 00.00.0000
8780 8814
8781 8815 Mike\SpecialChar ~
8782 8816 Heeter
8783 8817 \family typewriter
8784 8818 <korora-AT-SDF.LONESTAR.ORG>
8785 8819 \layout List
8786 8820 \labelwidthstring 00.00.0000
8787 8821
8788 8822 Christopher\SpecialChar ~
8789 8823 Hart
8790 8824 \family typewriter
8791 8825 <hart-AT-caltech.edu>
8792 8826 \family default
8793 8827 PDB integration.
8794 8828 \layout List
8795 8829 \labelwidthstring 00.00.0000
8796 8830
8797 8831 Milan\SpecialChar ~
8798 8832 Zamazal
8799 8833 \family typewriter
8800 8834 <pdm-AT-zamazal.org>
8801 8835 \family default
8802 8836 Emacs info.
8803 8837 \layout List
8804 8838 \labelwidthstring 00.00.0000
8805 8839
8806 8840 Philip\SpecialChar ~
8807 8841 Hisley
8808 8842 \family typewriter
8809 8843 <compsys-AT-starpower.net>
8810 8844 \layout List
8811 8845 \labelwidthstring 00.00.0000
8812 8846
8813 8847 Holger\SpecialChar ~
8814 8848 Krekel
8815 8849 \family typewriter
8816 8850 <pyth-AT-devel.trillke.net>
8817 8851 \family default
8818 8852 Tab completion, lots more.
8819 8853 \layout List
8820 8854 \labelwidthstring 00.00.0000
8821 8855
8822 8856 Robin\SpecialChar ~
8823 8857 Siebler
8824 8858 \family typewriter
8825 8859 <robinsiebler-AT-starband.net>
8826 8860 \layout List
8827 8861 \labelwidthstring 00.00.0000
8828 8862
8829 8863 Ralf\SpecialChar ~
8830 8864 Ahlbrink
8831 8865 \family typewriter
8832 8866 <ralf_ahlbrink-AT-web.de>
8833 8867 \layout List
8834 8868 \labelwidthstring 00.00.0000
8835 8869
8836 8870 Thorsten\SpecialChar ~
8837 8871 Kampe
8838 8872 \family typewriter
8839 8873 <thorsten-AT-thorstenkampe.de>
8840 8874 \layout List
8841 8875 \labelwidthstring 00.00.0000
8842 8876
8843 8877 Fredrik\SpecialChar ~
8844 8878 Kant
8845 8879 \family typewriter
8846 8880 <fredrik.kant-AT-front.com>
8847 8881 \family default
8848 8882 Windows setup.
8849 8883 \layout List
8850 8884 \labelwidthstring 00.00.0000
8851 8885
8852 8886 Syver\SpecialChar ~
8853 8887 Enstad
8854 8888 \family typewriter
8855 8889 <syver-en-AT-online.no>
8856 8890 \family default
8857 8891 Windows setup.
8858 8892 \layout List
8859 8893 \labelwidthstring 00.00.0000
8860 8894
8861 8895 Richard
8862 8896 \family typewriter
8863 8897 <rxe-AT-renre-europe.com>
8864 8898 \family default
8865 8899 Global embedding.
8866 8900 \layout List
8867 8901 \labelwidthstring 00.00.0000
8868 8902
8869 8903 Hayden\SpecialChar ~
8870 8904 Callow
8871 8905 \family typewriter
8872 8906 <h.callow-AT-elec.canterbury.ac.nz>
8873 8907 \family default
8874 8908 Gnuplot.py 1.6 compatibility.
8875 8909 \layout List
8876 8910 \labelwidthstring 00.00.0000
8877 8911
8878 8912 Leonardo\SpecialChar ~
8879 8913 Santagada
8880 8914 \family typewriter
8881 8915 <retype-AT-terra.com.br>
8882 8916 \family default
8883 8917 Fixes for Windows installation.
8884 8918 \layout List
8885 8919 \labelwidthstring 00.00.0000
8886 8920
8887 8921 Christopher\SpecialChar ~
8888 8922 Armstrong
8889 8923 \family typewriter
8890 8924 <radix-AT-twistedmatrix.com>
8891 8925 \family default
8892 8926 Bugfixes.
8893 8927 \layout List
8894 8928 \labelwidthstring 00.00.0000
8895 8929
8896 8930 Francois\SpecialChar ~
8897 8931 Pinard
8898 8932 \family typewriter
8899 8933 <pinard-AT-iro.umontreal.ca>
8900 8934 \family default
8901 8935 Code and documentation fixes.
8902 8936 \layout List
8903 8937 \labelwidthstring 00.00.0000
8904 8938
8905 8939 Cory\SpecialChar ~
8906 8940 Dodt
8907 8941 \family typewriter
8908 8942 <cdodt-AT-fcoe.k12.ca.us>
8909 8943 \family default
8910 8944 Bug reports and Windows ideas.
8911 8945 Patches for Windows installer.
8912 8946 \layout List
8913 8947 \labelwidthstring 00.00.0000
8914 8948
8915 8949 Olivier\SpecialChar ~
8916 8950 Aubert
8917 8951 \family typewriter
8918 8952 <oaubert-AT-bat710.univ-lyon1.fr>
8919 8953 \family default
8920 8954 New magics.
8921 8955 \layout List
8922 8956 \labelwidthstring 00.00.0000
8923 8957
8924 8958 King\SpecialChar ~
8925 8959 C.\SpecialChar ~
8926 8960 Shu
8927 8961 \family typewriter
8928 8962 <kingshu-AT-myrealbox.com>
8929 8963 \family default
8930 8964 Autoindent patch.
8931 8965 \layout List
8932 8966 \labelwidthstring 00.00.0000
8933 8967
8934 8968 Chris\SpecialChar ~
8935 8969 Drexler
8936 8970 \family typewriter
8937 8971 <chris-AT-ac-drexler.de>
8938 8972 \family default
8939 8973 Readline packages for Win32/CygWin.
8940 8974 \layout List
8941 8975 \labelwidthstring 00.00.0000
8942 8976
8943 8977 Gustavo\SpecialChar ~
8944 8978 Córdova\SpecialChar ~
8945 8979 Avila
8946 8980 \family typewriter
8947 8981 <gcordova-AT-sismex.com>
8948 8982 \family default
8949 8983 EvalDict code for nice, lightweight string interpolation.
8950 8984 \layout List
8951 8985 \labelwidthstring 00.00.0000
8952 8986
8953 8987 Kasper\SpecialChar ~
8954 8988 Souren
8955 8989 \family typewriter
8956 8990 <Kasper.Souren-AT-ircam.fr>
8957 8991 \family default
8958 8992 Bug reports, ideas.
8959 8993 \layout List
8960 8994 \labelwidthstring 00.00.0000
8961 8995
8962 8996 Gever\SpecialChar ~
8963 8997 Tulley
8964 8998 \family typewriter
8965 8999 <gever-AT-helium.com>
8966 9000 \family default
8967 9001 Code contributions.
8968 9002 \layout List
8969 9003 \labelwidthstring 00.00.0000
8970 9004
8971 9005 Ralf\SpecialChar ~
8972 9006 Schmitt
8973 9007 \family typewriter
8974 9008 <ralf-AT-brainbot.com>
8975 9009 \family default
8976 9010 Bug reports & fixes.
8977 9011 \layout List
8978 9012 \labelwidthstring 00.00.0000
8979 9013
8980 9014 Oliver\SpecialChar ~
8981 9015 Sander
8982 9016 \family typewriter
8983 9017 <osander-AT-gmx.de>
8984 9018 \family default
8985 9019 Bug reports.
8986 9020 \layout List
8987 9021 \labelwidthstring 00.00.0000
8988 9022
8989 9023 Rod\SpecialChar ~
8990 9024 Holland
8991 9025 \family typewriter
8992 9026 <rhh-AT-structurelabs.com>
8993 9027 \family default
8994 9028 Bug reports and fixes to logging module.
8995 9029 \layout List
8996 9030 \labelwidthstring 00.00.0000
8997 9031
8998 9032 Daniel\SpecialChar ~
8999 9033 'Dang'\SpecialChar ~
9000 9034 Griffith
9001 9035 \family typewriter
9002 9036 <pythondev-dang-AT-lazytwinacres.net>
9003 9037 \family default
9004 9038 Fixes, enhancement suggestions for system shell use.
9005 9039 \layout List
9006 9040 \labelwidthstring 00.00.0000
9007 9041
9008 9042 Viktor\SpecialChar ~
9009 9043 Ransmayr
9010 9044 \family typewriter
9011 9045 <viktor.ransmayr-AT-t-online.de>
9012 9046 \family default
9013 9047 Tests and reports on Windows installation issues.
9014 9048 Contributed a true Windows binary installer.
9015 9049 \layout List
9016 9050 \labelwidthstring 00.00.0000
9017 9051
9018 9052 Mike\SpecialChar ~
9019 9053 Salib
9020 9054 \family typewriter
9021 9055 <msalib-AT-mit.edu>
9022 9056 \family default
9023 9057 Help fixing a subtle bug related to traceback printing.
9024 9058 \layout List
9025 9059 \labelwidthstring 00.00.0000
9026 9060
9027 9061 W.J.\SpecialChar ~
9028 9062 van\SpecialChar ~
9029 9063 der\SpecialChar ~
9030 9064 Laan
9031 9065 \family typewriter
9032 9066 <gnufnork-AT-hetdigitalegat.nl>
9033 9067 \family default
9034 9068 Bash-like prompt specials.
9035 9069 \layout List
9036 9070 \labelwidthstring 00.00.0000
9037 9071
9038 9072 Ville\SpecialChar ~
9039 9073 Vainio
9040 9074 \family typewriter
9041 9075 <vivainio-AT-kolumbus.fi>
9042 9076 \family default
9043 9077 Bugfixes and suggestions.
9044 9078 Excellent patches for many new features.
9045 9079 \layout List
9046 9080 \labelwidthstring 00.00.0000
9047 9081
9048 9082 Antoon\SpecialChar ~
9049 9083 Pardon
9050 9084 \family typewriter
9051 9085 <Antoon.Pardon-AT-rece.vub.ac.be>
9052 9086 \family default
9053 9087 Critical fix for the multithreaded IPython.
9054 9088 \layout List
9055 9089 \labelwidthstring 00.00.0000
9056 9090
9057 9091 John\SpecialChar ~
9058 9092 Hunter
9059 9093 \family typewriter
9060 9094 <jdhunter-AT-nitace.bsd.uchicago.edu>
9061 9095 \family default
9062 9096 Matplotlib author, helped with all the development of support for matplotlib
9063 9097 in IPyhton, including making necessary changes to matplotlib itself.
9064 9098 \layout List
9065 9099 \labelwidthstring 00.00.0000
9066 9100
9067 9101 Matthew\SpecialChar ~
9068 9102 Arnison
9069 9103 \family typewriter
9070 9104 <maffew-AT-cat.org.au>
9071 9105 \family default
9072 9106 Bug reports, `
9073 9107 \family typewriter
9074 9108 %run -d
9075 9109 \family default
9076 9110 ' idea.
9077 9111 \layout List
9078 9112 \labelwidthstring 00.00.0000
9079 9113
9080 9114 Prabhu\SpecialChar ~
9081 9115 Ramachandran
9082 9116 \family typewriter
9083 9117 <prabhu_r-AT-users.sourceforge.net>
9084 9118 \family default
9085 9119 Help with (X)Emacs support, threading patches, ideas...
9086 9120 \layout List
9087 9121 \labelwidthstring 00.00.0000
9088 9122
9089 9123 Norbert\SpecialChar ~
9090 9124 Tretkowski
9091 9125 \family typewriter
9092 9126 <tretkowski-AT-inittab.de>
9093 9127 \family default
9094 9128 help with Debian packaging and distribution.
9095 9129 \layout List
9096 9130 \labelwidthstring 00.00.0000
9097 9131
9098 9132 George\SpecialChar ~
9099 9133 Sakkis <
9100 9134 \family typewriter
9101 9135 gsakkis-AT-eden.rutgers.edu>
9102 9136 \family default
9103 9137 New matcher for tab-completing named arguments of user-defined functions.
9104 9138 \layout List
9105 9139 \labelwidthstring 00.00.0000
9106 9140
9107 9141 J�rgen\SpecialChar ~
9108 9142 Stenarson
9109 9143 \family typewriter
9110 9144 <jorgen.stenarson-AT-bostream.nu>
9111 9145 \family default
9112 9146 Wildcard support implementation for searching namespaces.
9113 9147 \layout List
9114 9148 \labelwidthstring 00.00.0000
9115 9149
9116 9150 Vivian\SpecialChar ~
9117 9151 De\SpecialChar ~
9118 9152 Smedt
9119 9153 \family typewriter
9120 9154 <vivian-AT-vdesmedt.com>
9121 9155 \family default
9122 9156 Debugger enhancements, so that when pdb is activated from within IPython,
9123 9157 coloring, tab completion and other features continue to work seamlessly.
9158 \layout List
9159 \labelwidthstring 00.00.0000
9160
9161 Scott (email unknown) Support for automatic editor invocation on syntax
9162 errors (see
9163 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython/issue36}
9164
9165 \end_inset
9166
9167 ).
9124 9168 \the_end
General Comments 0
You need to be logged in to leave comments. Login now